# CLAUDE.md — 10x Engineer Configuration

> Integrated Anthropic official best practices + VibeGuard seven-layer defense.
> Different from "recommended compliance" configuration - rules, guard scripts, hooks, and workflow commands provide layered coverage; not every rule is mechanically blocked.

---

## Chat Contract

Compact Chat Contract: progress updates, concise answers, plain formatting.

- Progress updates: for non-trivial or tool-heavy work, send a short update at start, after discovery, before edits, after verification, and when blocked.
- Default verbosity: keep answers concise by default; use short paragraphs for simple tasks and expand only when the work is complex or the user asks for depth.
- Formatting: use Markdown only when it helps; prefer prose first, flat bullets only for natural lists, and avoid decorative structure.

## Workflow Orchestration

### 1. Routing Contract

Follow the canonical router in `workflows/references/routing-contract.md`.

- Precedence: `user_override` → `risk/destructive gate` → `ambiguity gate` → `readiness classifier` → `execution/delegation lane`
- Readiness outputs: `execute_direct`, `plan_first`, `clarify_first`
- Planning handoff keys: `mode`, `artifacts`, `runtime_pinning_snapshot`, `verification_owner`, `stop_conditions`, `lane_map`

Do not recreate a separate file-count router inside project-specific CLAUDE instructions.

### 2. Spec-Driven (Spec-Driven)

When the routing contract resolves to `plan_first`, write the spec/plan before implementation:
1. **Understand first** — read the relevant code and draw the current data flow
2. **Write spec** — what to change, why, which files are affected, and interface definitions
3. **Implement according to spec** — do not deviate, update spec first if problems are found
4. **Verification** — Check each item against the spec

When readiness resolves to `execute_direct`, make the change directly without overdoing the process.

### 3. Subagent Strategy

- Use child agents to keep the main context window clean only after the routing contract allows delegation
- Follow `workflows/references/delegation-contract.md` for every child-agent assignment
- Research, exploration, and parallel analysis can run in `readonly` mode before write ownership is clear
- Write lanes require a task slice, allowed files, forbidden files, read-only files, authority, required evidence, blockers, a single integration owner, verification owner, and handoff artifacts
- One focused task per sub-agent

### 4. Autonomous Execution

- Receive bug report: **Fix it directly only when readiness resolves to `execute_direct`**
- See logs/error reports/failed tests — locate the root cause and resolve it
- User zero context switch

---

## Context Management (Context Management — Anthropic official recommendation)

The context window is the most important resource and is actively managed:

- **Two Correction Rules**: After correcting the same problem twice → `/clear` restart, the dirty context will only become more and more wrong as it is corrected
- **Inter-task `/clear`**: Clear the context between unrelated tasks, do not let history interfere with new tasks
- **Compact Preservation Directive**: When compacting, always preserve: modified file lists, constraint sets, test commands, architectural decisions
- **Sub-agent isolation**: A large number of file reads are handed over to the sub-agent without polluting the main context.
- **Long Session Alert**: Performance degrades when the context is almost full, active `/clear` or `/compact`

---

## Self-Improvement Loop (self-evolution loop)

> Not "recommend AI learning", but **automatically generate new defense rules every time a mistake is made**.

```
Make a mistake → /vibeguard:learn → Analyze the root cause → Generate new guard rules/Hook → Never make the same mistake again
```

- After being corrected, run `/vibeguard:learn` to automatically generate defense rules
- Rules can be converted into Hook scripts, which will be **automatically intercepted** next time
- The effect can be quantified: `/vibeguard:stats` View interception/warning/release statistics

---

## Seven-Layer Defense (Mixed Coverage)

Rules, guard scripts, hooks, and workflow commands provide the coverage. Not every layer is hook-blocked:

| Layers | Constraints | Execution Mode |
|----|------|----------|
| **L1** | Must search for existing implementations before creating new one | **Hook reminder by default; block when configured** |
| **L2** | Python snake_case, API camelCase | Guard script |
| **L3** | Disable silent exception swallowing; disable Any type | **Hook warning** |
| **L4** | Blank display with no data; API not invented | **Hook Warning** |
| **L5** | Only do what is asked | Review constraints |
| **L6** | Follow the canonical routing contract in `workflows/references/routing-contract.md` | Process constraints |
| **L7** | Disable AI tag / force push / key | Agent/review contract + pre-commit quality/build checks + git pre-push remote-history block |

---

## Auto-Enforcement (automatic execution)

### Hooks — real-time interception

| Trigger conditions | Behavior |
|----------|------|
| `Write` creates a new source code file | **Warn by default** — Search for existing implementations first; configure `VIBEGUARD_WRITE_MODE=block` or `write_mode=block` in `~/.vibeguard/config.json` to hard-block |
| `Bash` dangerous local cleanup (`rm -rf`, `git clean -f`, `git checkout/restore .`) | **Block** — gives a safe alternative |
| git `pre-push` detects non-fast-forward push / branch deletion | **Block** — protects remote history; rewrites and deletions require explicit human approval plus the repository bypass policy |
| `Edit` non-existent file | **Block** — Read first to confirm |
| `Edit` added unwrap/expect (Rust) | **Warn** — Output repair method |
| `Edit` adds hardcoded path | **Warn** — Prompt configuration |
| `Edit` added console.log / print | **Warn** — Prompt to use logger |
| `Stop` has unverified source code changes | **Signal** — logs a reminder; Stop exits 0 to avoid feedback loops |

### Observability

All events are logged to `~/.vibeguard/events.jsonl`, and `/vibeguard:stats` is used to view statistics.

---

## Verification Before Done (Must be verified before completion - Anthropic official highest priority)

> "Give Claude a way to verify its work — this is the single highest-leverage thing you can do."

**Stop Hook automatic access control**: When Claude wants to end, if there are unverified source code changes, it will automatically remind you to complete the verification.

### Coding verification (after one round of modification is completed)

```
Rust: cargo check  |  TypeScript: npx tsc --noEmit  |  Go: go build ./...
```

### Verification before submission

```
Rust: cargo test  |  TypeScript: npm test  |  Go: go test ./...  |  Python: pytest
```

### Guard verification

```
/vibeguard:check ← Full guard scan + compliance report
```

Ask yourself: **"Would a Staff Engineer approve this?"**

---

## Code Rules (iron law of code)

- **No backward compatibility** — delete old code directly
- **No hard coding** — port, URL, configuration file
- **Don’t over-design** — only do necessary functions
- **Single file ≤ 200 lines** - must be split if more than 200 lines
- **Search first and then write** — Expand if it already exists, the third repetition must be abstract
- **Blank if no data** — no fake data required
- **Tested with every repair**
- **Follow the existing pattern of the project**
- **Unauthorized modification of .env is prohibited**

---

## Git Discipline (submit discipline)

- **BANNED** AI generated tags (Generated by Claude / Co-Authored-By)
- **Disable** force push — history rewrites require explicit human approval
- rebase keeps history clean and does not commit keys

---

## Interview Mode (Interview Mode — Anthropic Official Recommendation)

Before launching a big feature, let the AI interview you instead of you describing the requirements:

```
/vibeguard:interview <Function description>
```

AI will use AskUserQuestion to drill down step by step: functional boundaries → technical implementation → edge cases → acceptance criteria.
After the interview, the structured SPEC.md is output. It is recommended to execute it in a **new session** to get a clean context.

---

## Path-Scoped Rules (Path Scoped Rules - Optional)

Place scope rules under the project `.claude/rules/`, and different directories will automatically load different constraints:

```
.claude/rules/api-security.md      # globs: ["**/api/**", "**/routes/**"]
.claude/rules/test-patterns.md     # globs: ["**/*test*", "**/tests/**"]
.claude/rules/config-protection.md # globs: ["**/.env*", "**/config/**"]
```

Templates are in `vibeguard/templates/project-rules/`, copied to the project as needed.

---

## Command Workflow (command workflow)

```
interview → preflight → coding → check → review → learn → stats
```

| Command | Purpose |
|------|------|
| `/vibeguard:interview` | In-depth interview on large functional requirements, output SPEC |
| `/vibeguard:preflight` | Generate constraint set before modification |
| `/vibeguard:check` | Full guard scan + compliance report |
| `/vibeguard:review` | Structured code review |
| `/vibeguard:cross-review` | Dual model adversarial review (Claude + Codex) |
| `/vibeguard:build-fix` | Build error fix |
| `/vibeguard:learn` | Generate new guards from mistakes |
| `/vibeguard:skill-validate` | Gate proposed skills with repair/regression evidence |
| `/vibeguard:exec-plan` | Long-term task execution plan (cross-session recovery) |
| `/vibeguard:live-truth` | Fresh evidence gates for mutable claims |
| `/vibeguard:gc` | Garbage collection (log archiving + worktree cleaning + rule budget + code garbage scanning) |
| `/vibeguard:stats` | Hook trigger statistics |

---

## Core Principles

- **Simplicity First** — the simplest solution, minimal changes
- **No Laziness** — Find the root cause, no patch
- **Minimal Impact** — only touch the code that must be touched
- **Mechanical Enforcement** — can be scripted without conscious effort
- **Failure → Defense** — Every mistake becomes a new line of defense
- **Verify Before Ship** — Code that is not verified is equal to not being written.

---

## Setup

```bash
git clone https://github.com/majiayu000/vibeguard.git ~/vibeguard
bash ~/vibeguard/setup.sh #default core
bash ~/vibeguard/setup.sh --profile full # additionally enable Stop signal / Learn evaluator
```

It takes effect when you open a new Claude Code session. The default `core` profile injects seven layers of rules and core Hooks; the `full` profile additionally enables the Stop signal.
