init repo

This commit is contained in:
sanbuphy
2026-04-01 18:41:21 +08:00
commit ce8ca4a8e7
24 changed files with 5451 additions and 0 deletions

View File

@@ -0,0 +1,124 @@
# Telemetry & Privacy Analysis
> Based on publicly available online references and community discussions on Claude Code v2.1.88.
## Overview
Claude Code implements a two-tier analytics pipeline that collects extensive environment and usage metadata. While there is no evidence of keylogging or user code exfiltration, the breadth of collection and inability to fully opt out raises legitimate privacy concerns.
## Data Pipeline Architecture
### First-Party Logging (1P)
- **Endpoint**: `https://api.anthropic.com/api/event_logging/batch`
- **Protocol**: OpenTelemetry with Protocol Buffers
- **Batch size**: Up to 200 events per batch, flushed every 10 seconds
- **Retry**: Quadratic backoff, up to 8 attempts, disk-persisted for durability
- **Storage**: Failed events saved to `~/.claude/telemetry/`
Source: `src/services/analytics/firstPartyEventLoggingExporter.ts`
### Third-Party Logging (Datadog)
- **Endpoint**: `https://http-intake.logs.us5.datadoghq.com/api/v2/logs`
- **Scope**: Limited to 64 pre-approved event types
- **Token**: `pubbbf48e6d78dae54bceaa4acf463299bf`
Source: `src/services/analytics/datadog.ts`
## What Is Collected
### Environment Fingerprint
Every event carries this metadata (`src/services/analytics/metadata.ts:417-452`):
```
- platform, platformRaw, arch, nodeVersion
- terminal type
- installed package managers and runtimes
- CI/CD detection, GitHub Actions metadata
- WSL version, Linux distro, kernel version
- VCS (version control system) type
- Claude Code version and build time
- deployment environment
```
### Process Metrics (`metadata.ts:457-467`)
```
- uptime, rss, heapTotal, heapUsed
- CPU usage and percentage
- memory arrays and external allocations
```
### User Tracking (`metadata.ts:472-496`)
```
- model in use
- session ID, user ID, device ID
- account UUID, organization UUID
- subscription tier (max, pro, enterprise, team)
- repository remote URL hash (SHA256, first 16 chars)
- agent type, team name, parent session ID
```
### Tool Input Logging
Tool inputs are truncated by default:
```
- Strings: truncated at 512 chars, displayed as 128 + ellipsis
- JSON: limited to 4,096 chars
- Arrays: max 20 items
- Nested objects: max 2 levels deep
```
Source: `metadata.ts:236-241`
However, when `OTEL_LOG_TOOL_DETAILS=1` is set, **full tool inputs are logged**.
Source: `metadata.ts:86-88`
### File Extension Tracking
Bash commands involving `rm, mv, cp, touch, mkdir, chmod, chown, cat, head, tail, sort, stat, diff, wc, grep, rg, sed` have their file arguments' extensions extracted and logged.
Source: `metadata.ts:340-412`
## The Opt-Out Problem
The first-party logging pipeline **cannot be disabled** for direct Anthropic API users.
```typescript
// src/services/analytics/firstPartyEventLogger.ts:141-144
export function is1PEventLoggingEnabled(): boolean {
return !isAnalyticsDisabled()
}
```
`isAnalyticsDisabled()` returns true only for:
- Test environments
- Third-party cloud providers (Bedrock, Vertex)
- Global telemetry opt-out (not exposed in settings UI)
There is **no user-facing setting** to disable first-party event logging.
## GrowthBook A/B Testing
Users are assigned to experiment groups via GrowthBook without explicit consent. The system sends user attributes including:
```
- id, sessionId, deviceID
- platform, organizationUUID, subscriptionType
```
Source: `src/services/analytics/growthbook.ts`
## Key Takeaways
1. **Volume**: Hundreds of events per session are collected
2. **No opt-out**: First-party logging cannot be disabled by direct API users
3. **Persistence**: Failed events are saved to disk and retried aggressively
4. **Third-party sharing**: Data flows to Datadog
5. **Tool detail backdoor**: `OTEL_LOG_TOOL_DETAILS=1` enables full input logging
6. **Repository fingerprinting**: Repo URLs are hashed and sent for server-side correlation

View File

@@ -0,0 +1,112 @@
# Hidden Features & Model Codenames
> Based on publicly available online references and community discussions on Claude Code v2.1.88.
## Model Codename System
Anthropic uses **animal names** as internal model codenames. These are aggressively protected from leaking into external builds.
### Known Codenames
| Codename | Role | Evidence |
|----------|------|----------|
| **Tengu** (天狗) | Product/telemetry prefix, possibly a model | Used as `tengu_*` prefix for all 250+ analytics events and feature flags |
| **Capybara** | Sonnet-series model, currently at v8 | `capybara-v2-fast[1m]`, prompt patches for v8 behavior issues |
| **Fennec** (耳廓狐) | Predecessor to Opus 4.6 | Migration: `fennec-latest``opus` |
| **Numbat** (袋食蚁兽) | Next model launch | Comment: "Remove this section when we launch numbat" |
### Codename Protection
The `undercover` mode explicitly lists protected codenames:
```typescript
// src/utils/undercover.ts:48-49
NEVER include in commit messages or PR descriptions:
- Internal model codenames (animal names like Capybara, Tengu, etc.)
- Unreleased model version numbers (e.g., opus-4-7, sonnet-4-8)
```
The build system uses `scripts/excluded-strings.txt` to scan for leaked codenames. Buddy system species are encoded via `String.fromCharCode()` to avoid triggering the canary:
```typescript
// src/buddy/types.ts:10-13
// One species name collides with a model-codename canary in excluded-strings.txt.
// The check greps build output (not source), so runtime-constructing the value keeps
// the literal out of the bundle while the check stays armed for the actual codename.
```
That colliding species is **capybara** — both a pet species and a model codename.
### Capybara Behavior Issues (v8)
The architecture reveals specific behavioral problems with Capybara v8:
1. **Stop sequence false trigger** (~10% rate when `<functions>` at prompt tail)
- Source: `src/utils/messages.ts:2141`
2. **Empty tool_result causes zero output**
- Source: `src/utils/toolResultStorage.ts:281`
3. **Over-commenting** — requires dedicated anti-comment prompt patches
- Source: `src/constants/prompts.ts:204`
4. **High false-claims rate**: v8 has 29-30% FC rate vs v4's 16.7%
- Source: `src/constants/prompts.ts:237`
5. **Insufficient verification** — requires "thoroughness counterweight"
- Source: `src/constants/prompts.ts:210`
## Feature Flag Naming Convention
All feature flags use the `tengu_` prefix with **random word pairs** to obscure their purpose:
| Flag | Purpose |
|------|---------|
| `tengu_onyx_plover` | Auto Dream (background memory consolidation) |
| `tengu_coral_fern` | memdir feature |
| `tengu_moth_copse` | Another memdir switch |
| `tengu_herring_clock` | Team memory |
| `tengu_passport_quail` | Path feature |
| `tengu_slate_thimble` | Another memdir switch |
| `tengu_sedge_lantern` | Away Summary |
| `tengu_frond_boric` | Analytics kill switch |
| `tengu_amber_quartz_disabled` | Voice mode kill switch |
| `tengu_amber_flint` | Agent teams |
| `tengu_hive_evidence` | Verification agent |
The random word pattern (adjective/material + nature/object) prevents external observers from inferring feature purpose from flag names alone.
## Internal vs External User Difference
Anthropic employees (`USER_TYPE === 'ant'`) receive significantly better treatment:
### Prompt Differences (`src/constants/prompts.ts`)
| Dimension | External Users | Internal (ant) |
|-----------|---------------|----------------|
| Output style | "Be extra concise" | "Err on the side of more explanation" |
| False-claims mitigation | None | Dedicated Capybara v8 patches |
| Numeric length anchors | None | "≤25 words between tools, ≤100 words final" |
| Verification agent | None | Required for non-trivial changes |
| Comment guidance | Generic | Dedicated anti-over-commenting prompt |
| Proactive correction | None | "If user has misconception, say so" |
### Tool Access
Internal users have access to tools not available externally:
- `REPLTool` — REPL mode
- `SuggestBackgroundPRTool` — background PR suggestions
- `TungstenTool` — performance monitoring panel
- `VerifyPlanExecutionTool` — plan verification
- Agent nesting (agents spawning agents)
## Hidden Commands
| Command | Status | Description |
|---------|--------|-------------|
| `/btw` | Active | Ask side questions without interrupting |
| `/stickers` | Active | Order Claude Code stickers (opens browser) |
| `/thinkback` | Active | 2025 Year in Review |
| `/effort` | Active | Set model effort level |
| `/good-claude` | Stub | Hidden placeholder |
| `/bughunter` | Stub | Hidden placeholder |

View File

@@ -0,0 +1,110 @@
# Undercover Mode Analysis
> Based on publicly available online references and community discussions on Claude Code v2.1.88.
## What Is Undercover Mode?
Undercover mode is a safety system for official employees contributing to external/open-source repositories. When active, it hides internal-specific AI model information and attribution, instructing the system to present its contributions as if written by a human developer. This is primarily to prevent the leakage of internal secrets and unreleased model names into the open-source community.
Source: `src/utils/undercover.ts`
## Activation Logic
```typescript
// src/utils/undercover.ts:28-37
export function isUndercover(): boolean {
if (process.env.USER_TYPE === 'ant') {
if (isEnvTruthy(process.env.CLAUDE_CODE_UNDERCOVER)) return true
// Auto: active unless positively confirmed internal repo
return getRepoClassCached() !== 'internal'
}
return false
}
```
Key properties:
- **Internal only**: Only active for official employees (`USER_TYPE === 'ant'`)
- **Default ON**: Active in all repos except those on the internal allowlist
- **No force-off**: "There is NO force-OFF. This guards against model codename leaks"
- **External builds**: Dead-code-eliminated by the bundler; never executes
## The Prompt Given to the Model
```typescript
// src/utils/undercover.ts:39-69
export function getUndercoverInstructions(): string {
return `## UNDERCOVER MODE — CRITICAL
You are operating UNDERCOVER in a PUBLIC/OPEN-SOURCE repository. Your commit
messages, PR titles, and PR bodies MUST NOT contain ANY Anthropic-internal
information. Do not blow your cover.
NEVER include in commit messages or PR descriptions:
- Internal model codenames (animal names like Capybara, Tengu, etc.)
- Unreleased model version numbers (e.g., opus-4-7, sonnet-4-8)
- Internal repo or project names (e.g., claude-cli-internal, anthropics/…)
- Internal tooling, Slack channels, or short links (e.g., go/cc, #claude-code-…)
- The phrase "Claude Code" or any mention that you are an AI
- Any hint of what model or version you are
- Co-Authored-By lines or any other attribution
Write commit messages as a human developer would — describe only what the code
change does.
GOOD:
- "Fix race condition in file watcher initialization"
- "Add support for custom key bindings"
BAD (never write these):
- "Fix bug found while testing with Claude Capybara"
- "1-shotted by claude-opus-4-6"
- "Generated with Claude Code"
- "Co-Authored-By: Claude Opus 4.6 <…>"`
}
```
## Attribution System
The attribution system (`src/utils/attribution.ts`, `src/utils/commitAttribution.ts`) complements undercover mode:
```typescript
// src/utils/attribution.ts:70-72
// @[MODEL LAUNCH]: Update the hardcoded fallback model name below
// (guards against codename leaks).
// For external repos, fall back to "Claude Opus 4.6" for unrecognized models.
```
```typescript
// src/utils/model/model.ts:386-392
function maskModelCodename(baseName: string): string {
// e.g. capybara-v2-fast → cap*****-v2-fast
const [codename = '', ...rest] = baseName.split('-')
const masked = codename.slice(0, 3) + '*'.repeat(Math.max(0, codename.length - 3))
return [masked, ...rest].join('-')
}
```
## Implications
### For Open Source
When official employees use Claude Code to contribute to open-source projects:
1. Code is written by AI but commits appear human-authored
2. No "Co-Authored-By: Claude" attribution
3. No "Generated with Claude Code" markers
4. Project maintainers and community cannot identify AI-generated contributions
5. This potentially violates open-source transparency norms regarding AI contributions
### For Official Protection
The primary stated purpose is preventing accidental leaks of:
- Internal model codenames (competitive intelligence)
- Unreleased version numbers (market timing)
- Internal infrastructure details (security)
### Ethical Considerations
The phrase "Do not blow your cover" frames the AI as an undercover agent. The intentional concealment of AI authorship in public code contributions raises questions about:
- Transparency in open-source communities
- Compliance with project contribution guidelines
- The line between trade secret protection and deception

View File

@@ -0,0 +1,161 @@
# Remote Control & Killswitches
> Based on publicly available online references and community discussions on Claude Code v2.1.88.
## Overview
Claude Code implements remote management mechanisms that allow officials (and enterprise administrators) to manage and update specific client behaviors via remote configuration to ensure system security and enterprise compliance.
## 1. Remote Managed Settings
### Architecture
Every eligible session fetches settings from:
```
GET /api/claude_code/settings
```
Source: `src/services/remoteManagedSettings/index.ts:105-107`
### Polling Behavior
```typescript
// src/services/remoteManagedSettings/index.ts:52-54
const SETTINGS_TIMEOUT_MS = 10000
const DEFAULT_MAX_RETRIES = 5
const POLLING_INTERVAL_MS = 60 * 60 * 1000 // 1 hour
```
Settings are polled every hour, with up to 5 retries on failure.
### Eligibility
- Console users (API key): All eligible
- OAuth users: Only Enterprise/C4E and Team subscribers
### Accept-or-Die Dialog
When remote settings contain "dangerous" changes, a blocking dialog is shown:
```typescript
// src/services/remoteManagedSettings/securityCheck.tsx:67-73
export function handleSecurityCheckResult(result: SecurityCheckResult): boolean {
if (result === 'rejected') {
gracefulShutdownSync(1) // Exit with code 1
return false
}
return true
}
```
Users who reject remote settings have the application **forcefully terminated**. The only options are: accept the remote settings, or Claude Code exits.
### Graceful Degradation
If the remote server is unreachable, cached settings from disk are used:
```typescript
// src/services/remoteManagedSettings/index.ts:433-436
if (cachedSettings) {
logForDebugging('Remote settings: Using stale cache after fetch failure')
setSessionCache(cachedSettings)
return cachedSettings
}
```
Once remote settings have been applied, they persist even when the server is down.
## 2. Feature Flag Killswitches
Multiple features can be remotely disabled via GrowthBook feature flags:
### Bypass Permissions Killswitch
```typescript
// src/utils/permissions/bypassPermissionsKillswitch.ts
// Checks a Statsig gate to disable bypass permissions
```
Can disable permission bypass capabilities without user consent.
### Auto Mode Circuit Breaker
```typescript
// src/utils/permissions/autoModeState.ts
// autoModeCircuitBroken state prevents re-entry to auto mode
```
Auto mode can be remotely disabled.
### Fast Mode Killswitch
```typescript
// src/utils/fastMode.ts
// Fetches from /api/claude_code_penguin_mode
// Can permanently disable fast mode for a user
```
### Analytics Sink Killswitch
```typescript
// src/services/analytics/sinkKillswitch.ts:4
const SINK_KILLSWITCH_CONFIG_NAME = 'tengu_frond_boric'
```
Can remotely stop all analytics output.
### Agent Teams Killswitch
```typescript
// src/utils/agentSwarmsEnabled.ts
// Requires both env var AND GrowthBook gate 'tengu_amber_flint'
```
### Voice Mode Killswitch
```typescript
// src/voice/voiceModeEnabled.ts:21
// 'tengu_amber_quartz_disabled' — emergency off for voice mode
```
## 3. Model Override System
To conduct canary testing or respond to unexpected online situations, the system supports dynamically switching the model versions for specific groups, such as internal employees:
```typescript
// src/utils/model/antModels.ts:32-33
// @[MODEL LAUNCH]: Update tengu_ant_model_override with new ant-only models
// @[MODEL LAUNCH]: Add the codename to scripts/excluded-strings.txt
```
The `tengu_ant_model_override` GrowthBook flag can:
- Set a default model
- Set default effort level
- Append to the system prompt
- Define custom model aliases
## 4. Penguin Mode
Fast mode status is fetched from a dedicated endpoint:
```typescript
// src/utils/fastMode.ts
// GET /api/claude_code_penguin_mode
// If API indicates disabled, permanently disabled for user
```
Multiple feature flags control fast mode availability:
- `tengu_penguins_off`
- `tengu_marble_sandcastle`
## Summary
| Mechanism | Scope | User Consent |
|-----------|-------|-------------|
| Remote managed settings | Enterprise/Team | Accept or exit |
| GrowthBook feature flags | All users | None |
| Killswitches | All users | None |
| Model override | Internal (ant) | None |
| Fast mode control | All users | None |
The remote control infrastructure is extensive. Enterprise administrators can enforce policies that users cannot override, and the system can remotely change behavior for any user through feature flags to address critical issues.

View File

@@ -0,0 +1,167 @@
# Future Roadmap — What the Architecture Reveals
> Based on publicly available online references and community discussions on Claude Code v2.1.88.
## 1. Next Model: Numbat
The most concrete evidence of the next model launch:
```typescript
// src/constants/prompts.ts:402
// @[MODEL LAUNCH]: Remove this section when we launch numbat.
```
**Numbat** (袋食蚁兽) is the codename for an upcoming model. The comment indicates the output efficiency section will be revised when Numbat launches, suggesting it may have better native output control.
### Future Version Numbers
```typescript
// src/utils/undercover.ts:49
- Unreleased model version numbers (e.g., opus-4-7, sonnet-4-8)
```
**Opus 4.7** and **Sonnet 4.8** are in development.
### Codename Evolution Chain
```
Fennec (耳廓狐) → Opus 4.6 → [Numbat?]
Capybara (水豚) → Sonnet v8 → [?]
Tengu (天狗) → telemetry/product prefix
```
The Fennec-to-Opus migration is documented:
```typescript
// src/migrations/migrateFennecToOpus.ts:7-11
// fennec-latest → opus
// fennec-latest[1m] → opus[1m]
// fennec-fast-latest → opus[1m] + fast mode
```
### MODEL LAUNCH Checklist
The codebase contains 20+ `@[MODEL LAUNCH]` markers listing everything to update:
- Default model names (`FRONTIER_MODEL_NAME`)
- Model family IDs
- Knowledge cutoff dates
- Pricing tables
- Context window configurations
- Thinking mode support flags
- Display name mappings
- Migration scripts
## 2. KAIROS — Autonomous Agent Mode
The largest unreleased feature, KAIROS transforms Claude Code from a reactive assistant into a proactive autonomous agent.
### System Prompt (excerpts)
```
// src/constants/prompts.ts:860-913
You are running autonomously.
You will receive <tick> prompts that keep you alive between turns.
If you have nothing useful to do, call SleepTool.
Bias toward action — read files, make changes, commit without asking.
## Terminal focus
- Unfocused: The user is away. Lean heavily into autonomous action.
- Focused: The user is watching. Be more collaborative.
```
### Associated Tools
| Tool | Feature Flag | Purpose |
|------|-------------|---------|
| SleepTool | KAIROS / PROACTIVE | Control pacing between autonomous actions |
| SendUserFileTool | KAIROS | Proactively send files to users |
| PushNotificationTool | KAIROS / KAIROS_PUSH_NOTIFICATION | Push notifications to user devices |
| SubscribePRTool | KAIROS_GITHUB_WEBHOOKS | Subscribe to GitHub PR webhook events |
| BriefTool | KAIROS_BRIEF | Proactive status updates |
### Behavior
- Operates on `<tick>` heartbeat prompts
- Adjusts autonomy based on terminal focus state
- Can commit, push, and make decisions independently
- Sends proactive notifications and status updates
- Monitors GitHub PRs for changes
## 3. Voice Mode
Push-to-talk voice input is fully implemented but gated behind `VOICE_MODE` feature flag.
```typescript
// src/voice/voiceModeEnabled.ts
// Connects to Anthropic's voice_stream WebSocket endpoint
// Uses conversation_engine backed models for speech-to-text
// Hold-to-talk: hold keybinding to record, release to submit
```
- OAuth-only (no API key / Bedrock / Vertex support)
- Uses mTLS for WebSocket connections
- Killswitch: `tengu_amber_quartz_disabled`
## 4. Unreleased Tools
Tools found in source but not yet enabled for external users:
| Tool | Feature Flag | Description |
|------|-------------|-------------|
| **WebBrowserTool** | `WEB_BROWSER_TOOL` | Built-in browser automation (codename: bagel) |
| **TerminalCaptureTool** | `TERMINAL_PANEL` | Terminal panel capture and monitoring |
| **WorkflowTool** | `WORKFLOW_SCRIPTS` | Execute predefined workflow scripts |
| **MonitorTool** | `MONITOR_TOOL` | System/process monitoring |
| **SnipTool** | `HISTORY_SNIP` | Conversation history snipping/truncation |
| **ListPeersTool** | `UDS_INBOX` | Unix domain socket peer discovery |
| **RemoteTriggerTool** | `AGENT_TRIGGERS_REMOTE` | Remote agent triggering |
| **TungstenTool** | ant-only | Internal performance monitoring panel |
| **VerifyPlanExecutionTool** | VERIFY_PLAN env | Plan execution verification |
| **OverflowTestTool** | `OVERFLOW_TEST_TOOL` | Context overflow testing |
| **SubscribePRTool** | `KAIROS_GITHUB_WEBHOOKS` | GitHub PR webhook subscriptions |
## 5. Coordinator Mode
Multi-agent coordination system:
```typescript
// src/coordinator/coordinatorMode.ts
// Feature flag: COORDINATOR_MODE
```
Enables coordinated task execution across multiple agents with shared state and messaging.
## 6. Buddy System (Virtual Pets)
The complete pet companion system is implemented but not yet launched:
- **18 species**: duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk
- **5 rarity tiers**: Common (60%), Uncommon (25%), Rare (10%), Epic (4%), Legendary (1%)
- **7 hats**: crown, tophat, propeller, halo, wizard, beanie, tinyduck
- **5 stats**: DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK
- **1% shiny chance**: Sparkle variant of any species
- **Deterministic generation**: Based on hash of user ID
Source: `src/buddy/`
## 7. Dream Task
Background memory consolidation subagent:
```
// src/tasks/DreamTask/
// Auto-dreaming feature that works in the background
// Controlled by 'tengu_onyx_plover' feature flag
```
Enables the AI to autonomously process and consolidate memories during idle time.
## Summary: The Three Directions
1. **New Models**: Numbat (next), Opus 4.7, Sonnet 4.8 in development
2. **Autonomous Agent**: KAIROS mode — unattended operation, proactive actions, push notifications
3. **Multi-modal**: Voice input ready, browser tool waiting, workflow automation coming
Claude Code is evolving from a **coding assistant** into an **always-on autonomous development agent**.