Metadata-Version: 2.4
Name: ata-coder
Version: 2.5.2
Summary: ATA Coder — AI-powered coding assistant
Author: ATA Coder Team
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.0
Requires-Dist: httpx<1.0,>=0.27.0
Requires-Dist: colorama>=0.4.6
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: rich>=13.0.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: prompt-toolkit>=3.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: pytest-timeout>=2.0; extra == "dev"
Requires-Dist: tiktoken>=0.5.0; extra == "dev"
Dynamic: license-file

# ATA Coder v2.5.2

**AI-powered coding assistant — async, AST-aware, single config file.**
**AI 驱动的编程助手 — 异步、AST 感知、单文件配置。**

---

> **v2.5.2** — ✨ Welcome panel now shows version number before model info.
> **v2.5.2** — ✨ 欢迎面板在模型信息前显示版本号。
> > **v2.4.8** — 🤖 Self-Bootstrapped Audit (Round 12) / 自举审计第 12 轮
> > **v2.4.7** — ⚡ Context Memory Refactor / 上下文记忆重构
> > **v2.4.6** — 🔐 OS-Native Credential Store / 操作系统凭据存储
> > **v2.4.5** — 🤖 Self-Bootstrapped Audit / 自举审计
> > **v2.4.4** — 🔒 Security Hardening / 安全加固
> > **v2.3.0~v2.4.3** — 60+ issues fixed, memory overhaul, token counting, safety pipeline / 60+ 问题修复，记忆重构，Token 计数，安全管线

---

## Overview / 概述

ATA Coder is a CLI AI coding assistant compatible with OpenAI and Anthropic APIs. It runs on a **single-threaded asyncio event loop** — no threads, no race conditions, low memory. Features deterministic AST-based code editing, sub-agent pool, MCP support, and a built-in HTTP API server.

ATA Coder 是一个命令行 AI 编码助手，兼容 OpenAI / Anthropic API。基于 **单线程 asyncio 事件循环** — 无线程、无竞态、低内存。配备确定性 AST 代码编辑、子 Agent 池、MCP 支持和内置 HTTP API 服务。

```bash
pip install ata-coder
```

---

## Architecture / 架构

```
asyncio Event Loop (single-threaded) / 事件循环（单线程）
├── REPL (prompt_toolkit + Rich)
│     await controller.submit(task)
│     await event_queue.drain() → ui.on_event()
│
├── AgentController (asyncio.Task)
│     CoderAgent.run() → async LLM loop → await tool calls / 异步 LLM 循环
│     BaseLLMClient (ABC) — unified OpenAI/Anthropic async interface / 统一异步接口
│     ExtensionManager → skill prompt aggregation / Skill 提示聚合
│     Keyword-based task classification (zero extra API calls) / 关键词分类（零额外 API 调用）
│
├── Sub-Agent Tasks (asyncio.TaskGroup) / 子 Agent 任务
│     SubAgent 1..N: independent LLM, tools, isolated context / 独立 LLM、工具、上下文
│     asyncio.Semaphore → concurrency limit / 并发限制
│
└── MCP Clients (asyncio subprocess) / MCP 客户端
      StdioConnection → create_subprocess_exec + async read loop / 异步读取循环
      HTTPConnection → httpx.AsyncClient
```

**No threads, no race conditions, no watchdog.** asyncio native cancellation replaces the old `thread_supervisor.py` (deleted).
**无线程、无竞态、无 watchdog。** asyncio 原生取消替代了旧的 `thread_supervisor.py`（已删除）。

---

## Key Features / 核心特性

| Feature 特性 | Description 说明 |
|---------|-------------|
| **Async Event Loop / 异步事件循环** | Single-threaded asyncio — zero race conditions, no thread overhead / 单线程 asyncio — 零竞态、无线程开销 |
| **AST Code Editing / AST 代码编辑** | libcst-based deterministic edits for Python, preserves all formatting / libcst 确定性 Python 编辑，完美保留格式 |
| **Safe Rename / 安全重命名** | `rename_symbol` tool — renames definitions + references, skips strings/comments / 改名不碰字符串和注释 |
| **Sub-Agent Pool / 子 Agent 池** | Parallel sub-agents with isolated context, asyncio.Semaphore bounded / 独立上下文并行执行，信号量限制并发 |
| **Skill System / Skill 系统** | Keyword-based auto-detection, single-skill activation for clean prompts / 关键词自动检测，单 Skill 激活防提示稀释 |
| **MCP Support / MCP 支持** | Model Context Protocol — cross-tool interoperability via stdio/HTTP / Model Context Protocol — 跨工具互操作 |
| **Multimodal Vision / 多模态视觉** | `analyze_image` tool — vision model auto-falls back to main API config / 视觉模型未设置自动用主模型 |
| **Diff Preview / Diff 预览** | Colorized unified diff before file edits — green/red lines in terminal / 编辑前彩色 unified diff，终端红绿高亮 |
| **Session Persistence / 会话持久化** | Save / resume / export conversation history by workspace / 按工作区保存/恢复/导出对话历史 |
| **Safety Pipeline / 安全管线** | Fool-proof validation → permissions → privilege → self-correction / 防呆 → 权限 → 特权 → 自校正 |
| **HTTP API Server / HTTP API 服务** | SSE streaming, shell sessions, multi-session management / SSE 流式、Shell 会话、多会话管理 |
| **One Dark Pro Theme / One Dark Pro 主题** | Rich syntax highlighting for code blocks / Rich 语法高亮 |
| **Web GUI / Web 界面** | SPA with SSE streaming, markdown, sidebar, command popup / SPA 单页应用，SSE 流式，Markdown 渲染 |

---

## Quick Start / 快速开始

```bash
# Install from PyPI (recommended) / 从 PyPI 安装（推荐）
pip install ata-coder

# Or install from source (development) / 或从源码安装（开发模式）
pip install -e .

ata                          # Interactive REPL / 交互模式
ata run "Add type hints"     # Single task / 单任务
ata server --port 8080       # HTTP API server / API 服务
ata --skill debugger         # With specific skill / 指定 Skill
ata --resume <session-id>    # Resume saved session / 恢复会话
```

---

## Configuration / 配置

**`settings.json` is the single source of truth.** All config lives in `~/.ata_coder/settings.json`.
**`settings.json` 是唯一配置源。** 所有配置在 `~/.ata_coder/settings.json`。

```json
{
  "env": {
    "ATA_CODER_BASE_URL": "https://api.deepseek.com",
    "ATA_CODER_API_KEY": "sk-...",
    "ATA_CODER_DEFAULT_MODEL": "deepseek-v4-pro",
    "ATA_CODER_DEFAULT_OPUS_MODEL": "deepseek-v4-pro",
    "ATA_CODER_DEFAULT_SONNET_MODEL": "deepseek-v4-pro",
    "ATA_CODER_DEFAULT_HAIKU_MODEL": "deepseek-v4-flash",
    "ATA_CODER_SUBAGENT_MODEL": "deepseek-v4-flash",
    "ATA_CODER_MAX_OUTPUT_TOKENS": "131072",
    "ATA_CODER_EFFORT_LEVEL": "max"
  },
  "complexity": { "auto_detect": true, "simple_max_chars": 60, "complex_min_chars": 500 },
  "paths": {
    "data": "~/.ata_coder", "skills": "~/.ata_coder/skills",
    "sessions": "~/.ata_coder/sessions", "memory": "~/.ata_coder/memory"
  },
  "permissions": {
    "allow": ["Bash(git:*)", "Bash(python:*)", "Read(./**)", "Edit(./**/*.{py,json,md})"],
    "deny": ["Bash(rm -rf:*)", "Bash(sudo:*)", "Read(./.env)", "Read(./**/*.key)"]
  }
}
```

- Vision model empty = auto-uses main model. No separate API config needed. / 视觉模型留空 = 自动用主模型，无需单独配置。
- Model names auto-strip `[1m]` suffix. / 模型名自动剥离 `[1m]` 后缀。
- API errors get friendly troubleshooting suggestions inline. / API 错误自动附带友好修复建议。

---

## Skills / 技能系统

Skills live in `skills/<name>/` folders with `SKILL.md` manifest (YAML frontmatter + markdown body). Single-skill activation via keyword matching — no extra LLM calls.

Skill 存放在 `skills/<名称>/` 文件夹中，使用 `SKILL.md` 清单（YAML frontmatter + markdown 正文）。通过关键词匹配单 Skill 激活 — 无需额外 LLM 调用。

```
skills/weather-skill/
├── SKILL.md           # name, version, triggers, tools, I/O spec / 名称、版本、触发器、工具、I/O 规范
├── handler.py         # Python entry point / Python 入口
├── utils.py           # Helpers / 辅助工具
├── prompts/           # LLM prompt templates / LLM 提示模板
├── resources/         # Static data / 静态数据
└── tests/             # pytest tests / pytest 测试
```

---

## Commands / 常用命令

| Command / 命令 | Description / 说明 |
|---------|-------------|
| `/help` | Show help / 帮助 |
| `/skills` | List available skills / 列出 Skill |
| `/skill <name>` | Switch skill / 切换 Skill |
| `/review` | AI code review of git diff / AI 审查代码 |
| `/fix [severity]` | Auto-fix review issues / 自动修复审查问题 |
| `/undo [n]` | Undo file changes / 撤销变更 |
| `/changes` | List tracked changes / 列出变更记录 |
| `/save` | Save current session / 保存会话 |
| `/resume <id>` | Resume saved session / 恢复会话 |
| `/sessions` | List/search session history / 列出/搜索会话历史 |
| `/compact` | Compact conversation context / 压缩上下文 |
| `/context` | Show token usage + cost / Token 用量 + 费用 |
| `/model <name>` | Change model at runtime / 切换模型 |
| `/config` | Show current configuration / 查看配置 |
| `/vision <img> [prompt]` | Analyze image / 视觉分析 |
| `/think` | Toggle thinking mode / 切换思考模式 |
| `/permissions` | Show permission rules / 查看权限规则 |
| `/git <sub>` | Git operations / Git 操作 |
| `/plan <task>` | Task planning / 任务规划 |
| `/remember` / `/recall` | Memory management / 记忆管理 |
| `/mcp search <q>` | Search MCP tools / 搜索 MCP 工具 |

---

## API Server / API 服务

```bash
ata server --port 8080
```

| Endpoint / 端点 | Description / 说明 |
|----------|-------------|
| `POST /chat` | Non-streaming chat / 非流式聊天 |
| `POST /chat/stream` | SSE streaming chat / SSE 流式聊天 |
| `GET /health` | Health check / 健康检查 |
| `GET /tools` | List tools / 列出工具 |
| `GET /skills` | List skills / 列出 Skill |
| `GET /models` | List available models / 列出可用模型 |
| `GET /sessions` | List sessions / 列出会话 |
| `DELETE /sessions/<id>` | Delete session / 删除会话 |
| `POST /api/shell` | Interactive shell / 交互式 Shell |

```bash
# Streaming chat / 流式聊天
curl -N -X POST http://localhost:8080/chat/stream \
  -H "Content-Type: application/json" \
  -d '{"message": "Explain async/await"}'

# Non-streaming / 非流式
curl -X POST http://localhost:8080/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Write hello world", "skill": "general-coder"}'
```

---

## Design Patterns / 设计模式

| Pattern / 模式 | Implementation / 实现 |
|---------|---------------|
| **Async LLM / 异步 LLM** | `BaseLLMClient` ABC — `LLMClient` and `AnthropicClient` use `httpx.AsyncClient` |
| **Tool Pipeline / 工具管线** | SafetyCheck → PermissionCheck → PrivilegeCheck → Execute → SelfCorrect |
| **AST Editing / AST 编辑** | libcst `CSTTransformer` — parse, match, replace, preserve formatting / 解析、匹配、替换、保留格式 |
| **Cancellation / 取消** | `asyncio.Task.cancel()` + `asyncio.CancelledError` — no threading events / 无线程事件 |
| **Concurrency / 并发** | `asyncio.Semaphore` for sub-agent limits, `asyncio.gather()` for parallel tools / 子 Agent 限制 + 并行工具 |
| **Event Bus / 事件总线** | `asyncio.Queue` — agent task produces, UI task consumes / agent 任务生产, UI 任务消费 |
| **Retry Jitter / 重试抖动** | Exponential backoff + random jitter in LLM clients / 指数退避 + 随机抖动 |
| **Circuit Breaker / 熔断器** | Consecutive-tool-failure counter (5 all-fail batches → break) / 连续工具失败计数（5 次全失败 → 熔断） |
| **Token Budget / Token 预算** | Auto-compact at 200k effective tokens, force-truncate at 95% of 1M max / 200k 有效 token 自动压缩 |
| **Diff Preview / Diff 预览** | `difflib.unified_diff` + Rich colored output before file writes / 写入前 Rich 彩色预览 |

---

## Project Structure / 项目结构

```
ata_coder/
├── main.py                  # CLI entry point (click) + asyncio.run() / CLI 入口
├── agent.py                 # Core agent: async run loop, event system, session mgmt / 核心 Agent
├── agent_tools.py           # ToolExecutionMixin — tool dispatch, streaming, self-correct / 工具执行
├── agent_compact.py         # CompactionMixin — thin wrapper around ContextManager / 上下文压缩
├── agent_controller.py      # asyncio.Task-based orchestrator / 异步编排器
├── agent_routing.py         # ModelRoutingMixin — keyword+length task classification / 模型路由
├── agent_extension.py       # ExtensionMixin — extension registration + lifecycle / 扩展管理
├── agent_subsystems.py      # AgentSubsystems dataclass / 子系统容器
├── context_manager.py       # ContextManager — O(1) token tracking, segment-split, compaction
├── core/                    # Extracted from agent.py / 从 agent.py 提取
│   ├── events.py            # AgentEvent dataclasses
│   ├── state.py             # AgentState dataclass
│   └── queue.py             # EventQueue (asyncio.Queue wrapper)
├── tools/                   # Tool implementations / 工具实现
│   ├── executor.py          # ToolExecutor + 14 tool handlers / 14 个工具处理器
│   ├── web.py               # WebToolsMixin — web_search, web_fetch
│   ├── subagent.py          # SubAgentToolsMixin — spawn, collect sub-agents
│   ├── definitions.py       # TOOL_DEFINITIONS (OpenAI-format tool schemas)
│   ├── strategy.py          # Strategy plugin system / 策略插件系统
│   └── result.py            # ToolResult dataclass
├── commands/                # Slash commands / 斜杠命令
│   ├── _core.py             # /help, /skills, /model, /context
│   ├── _safety.py           # /dangerous, /undo, /changes
│   ├── _settings.py         # /config, /permissions
│   └── _workflow.py         # /plan, /review, /fix
├── token_counter.py         # Unified token estimation (model-aware, cached) / 统一 Token 估算
├── llm_client.py            # OpenAI-compatible async client (httpx.AsyncClient)
├── anthropic_client.py      # Anthropic Messages API async client
├── skills.py                # Folder-based skill manager / 基于文件夹的 Skill 管理器
├── skill_extension.py       # Skill → Extension adapter / Skill 到 Extension 适配器
├── extension.py             # Plugin/extension system / 插件/扩展系统
├── sub_agent.py             # asyncio.Task-based sub-agent / 异步子 Agent
├── sub_agent_manager.py     # asyncio.Semaphore-bounded pool / 信号量并发池
├── mcp_client.py            # Async MCP (stdio + HTTP/SSE) / 异步 MCP
├── memory.py                # Persistent file-based memory / 持久化文件记忆
├── session.py               # Session save/load/search / 会话保存/加载/搜索
├── change_tracker.py        # File change undo/redo / 文件变更撤销/重做
├── safety_guard.py          # Pattern-based risk analysis / 基于模式的风险分析
├── fool_proof.py            # Unified pre-execution safety check / 统一执行前安全检查
├── permissions.py           # Interactive allow/deny rules / 交互式允许/拒绝规则
├── privilege.py             # OS-aware privilege elevation / 操作系统感知权限提升
├── config.py                # Runtime config (reads settings.json only) / 运行时配置
├── settings.py              # ~/.ata_coder/settings.json persistence / 配置持久化
├── self_correct.py          # Error diagnosis + auto-fix / 错误诊断 + 自动修复
├── system_prompt_builder.py # Dynamic prompt assembly / 动态提示构建
├── model_registry.py        # Model metadata + pricing / 模型元数据 + 定价
├── model_router.py          # Keyword-based complexity classification / 复杂度分类
├── repl_ui.py               # Rich/prompt-toolkit REPL + diff preview / REPL 界面
├── server.py                # HTTP API server + SSE streaming / HTTP API 服务
├── server_session.py        # SessionStore for multi-session management / 多会话管理
├── server_shell.py          # Persistent PowerShell/bash sessions / 持久 Shell 会话
├── server_rate_limit.py     # Rate limiter (token bucket) / 速率限制
├── utils.py                 # Shared utilities + API error helper / 共享工具
├── prompt_template.py       # {% if %} templating / 模板引擎
├── task_planner.py          # Task decomposition / 任务分解
├── git_workflow.py          # Git integration / Git 集成
├── project.py               # Project auto-detection / 项目自动检测
├── clawd_integration.py     # Clawd desktop pet HTTP integration / Clawd 桌面宠物集成
├── gui.py                   # Tkinter GUI / Tkinter 图形界面
├── terminal.py              # Terminal color helpers / 终端颜色辅助
├── setup_wizard.py          # First-run setup wizard / 首次运行配置向导
├── skills/                  # Built-in skill folders / 内置 Skill 文件夹
├── extensions/              # Plugin directory / 插件目录
├── examples/                # Usage examples / 使用示例
├── tests/                   # pytest suite (484 tests) / pytest 测试套件
└── README.md
```

---

## v2.5.0 Bug Fix Summary / Bug 修复摘要

| Severity / 严重度 | Count / 数量 | Key Fixes / 关键修复 |
|----------|--------|-------------|
| 🔴 Critical / 严重 | 7 | Compaction duplication, tool results lost, MCP missing await, memory preload race, Windows cache invalidation / 压缩重复、工具结果丢失、MCP 缺失 await、内存预加载竞态、Windows 缓存失效 |
| 🟠 High / 高 | 18 | chat() interleaving, workspace boundary blocking, extension points, streaming token tracking, nested for-loops, circular deps, privilege quoting, sub-agent bundling / chat() 交错、工作区边界阻止、扩展点触发、流式 Token 追踪、嵌套循环、循环依赖、提权引用 |
| 🟡 Medium / 中 | 40+ | Server deadlock, API key in logs, Rich crash guard, time.monotonic(), rate limiter leak, semaphore over-release, LLM retry jitter, docker logic, session eviction, atomic writes / 服务器死锁、API 密钥泄露、Rich 崩溃保护、时钟单调化、速率限制泄漏、信号量过度释放、LLM 重试抖动 |
| ⚪ Low / 低 | 10+ | Dead code removal, exception narrowing, cache defense, backspace fix / 死代码移除、异常作用域缩小、缓存防御、退格修复 |

See [CHANGELOG.md](CHANGELOG.md) for the complete list. / 完整列表见 [CHANGELOG.md](CHANGELOG.md)。

---

## Beginner's Guide — From Zero to ATA Coder / 从零开始的 ATA Coder 教程

### 1. Install Python / 安装 Python

ATA Coder requires **Python 3.10 or later**.
ATA Coder 需要 **Python 3.10 或更高版本**。

**Windows / Windows 系统：**

```bash
# Method 1: Microsoft Store (recommended for beginners / 推荐新手)
# Search "Python 3.12" in Microsoft Store → Install
# 在 Microsoft Store 搜索 "Python 3.12" → 安装

# Method 2: Official installer / 官方安装包
# Download from https://www.python.org/downloads/
# ✅ MUST check "Add Python to PATH" during installation!
# ✅ 安装时务必勾选 "Add Python to PATH"！
```

Verify installation / 验证安装：
```bash
python --version
# Expected / 预期输出: Python 3.12.x (or 3.10+)
```

**macOS / macOS 系统：**

```bash
# Method 1: Homebrew (recommended / 推荐)
brew install python@3.12

# Method 2: Official installer from python.org
# Download .pkg from https://www.python.org/downloads/
```

**Linux (Debian/Ubuntu) / Linux 系统：**

```bash
sudo apt update
sudo apt install python3 python3-pip python3-venv
```

---

### 2. Install ATA Coder / 安装 ATA Coder

```bash
# Recommended: install from PyPI / 推荐从 PyPI 安装
pip install ata-coder

# Or install latest from GitHub / 或从 GitHub 安装最新版
pip install git+https://github.com/jiaheng0815/ata-coder.git

# Or install in development mode (for contributors) / 或开发模式安装（贡献者用）
git clone https://github.com/jiaheng0815/ata-coder.git
cd ata-coder
pip install -e .
```

Verify installation / 验证安装：
```bash
ata --help
# Should show the CLI help menu / 应显示 CLI 帮助菜单
```

---

### 3. First-Time Setup / 首次配置

Run the setup wizard to configure your API key and model:
运行配置向导，设置 API Key 和模型：

```bash
ata
# The wizard will guide you through:
#   1. API Base URL (e.g. https://api.deepseek.com)
#   2. API Key (e.g. sk-xxxxxxxx)
#   3. Default Model (e.g. deepseek-v4-pro)
#
# 向导会引导你设置：
#   1. API 地址（如 https://api.deepseek.com）
#   2. API 密钥（如 sk-xxxxxxxx）
#   3. 默认模型（如 deepseek-v4-pro）
```

Configuration is saved to `~/.ata_coder/settings.json`. You can edit it anytime:
配置保存在 `~/.ata_coder/settings.json`，随时可编辑：

```json
{
  "env": {
    "ATA_CODER_BASE_URL": "https://api.deepseek.com",
    "ATA_CODER_API_KEY": "sk-your-key-here",
    "ATA_CODER_DEFAULT_MODEL": "deepseek-v4-pro"
  }
}
```

**Supported API providers / 支持的 API 提供商：**

| Provider / 提供商 | Base URL | Model Example / 模型示例 |
|----------|----------|---------|
| DeepSeek | `https://api.deepseek.com` | `deepseek-v4-pro` |
| OpenAI | `https://api.openai.com/v1` | `gpt-4o` |
| Anthropic | `https://api.anthropic.com` | `claude-sonnet-4-6` (set `ATA_CODER_USE_ANTHROPIC=1`) |
| OpenRouter | `https://openrouter.ai/api/v1` | `openai/gpt-4o` |
| Ollama (local) | `http://localhost:11434/v1` | `llama3` |
| Any OpenAI-compatible endpoint / 任何 OpenAI 兼容端点 | custom / 自定义 | custom / 自定义 |

---

### 4. Daily Usage / 日常使用

```bash
# Interactive REPL — chat with the AI / 交互模式 — 与 AI 对话
ata

# Single task — one-shot, prints result, exits / 单任务 — 一次执行，输出结果后退出
ata run "Add type hints to all functions in src/"

# HTTP API server — for web UI, curl, integrations / API 服务器 — Web 界面、curl、集成调用
ata server --port 8080

# Web GUI — server + auto-open browser / Web 图形界面 — 服务器 + 自动打开浏览器
ata gui

# Force a specific skill / 指定 Skill
ata --skill debugger

# Resume a previous session / 恢复之前的会话
ata --resume <8-char-hash>
```

---

### 5. Troubleshooting / 常见问题

| Problem / 问题 | Solution / 解决 |
|--------|--------|
| `'ata' is not recognized` | Python not in PATH — reinstall Python with "Add to PATH" checked / Python 未加入 PATH — 重装并勾选 "Add to PATH" |
| `pip: command not found` | Run `python -m pip install ata-coder` instead / 改用 `python -m pip install ata-coder` |
| API key error / API 密钥报错 | Double-check `settings.json` — key must be in the `"env"` block / 检查 `settings.json` — 密钥必须在 `"env"` 块中 |
| Connection timeout / 连接超时 | Check your API base URL. If using Ollama, ensure `ollama serve` is running / 检查 API 地址。Ollama 用户确认 `ollama serve` 已启动 |
| Unicode errors on Windows | Set `PYTHONUTF8=1` or use Windows Terminal (not legacy cmd.exe) / 使用 Windows Terminal 而非旧版 cmd.exe |

---

## Contributing — Become an ATA Coder Collaborator / 成为 ATA Coder 协作者

### Quick Start for Contributors / 贡献者快速上手

```bash
# 1. Fork + Clone / Fork 并克隆
git clone https://github.com/YOUR_USERNAME/ata-coder.git
cd ata-coder

# 2. Create a virtual environment / 创建虚拟环境
python -m venv .venv
# Windows:
.venv\Scripts\activate
# macOS/Linux:
source .venv/bin/activate

# 3. Install in development mode with test deps / 开发模式安装 + 测试依赖
pip install -e ".[dev]"

# 4. Run tests to verify everything works / 运行测试确认环境正常
pytest tests/ --ignore=tests/test_server.py -q
# Expected: 484 passed / 预期：484 passed

# 5. Create a branch, make your change, commit, push / 创建分支、修改、提交、推送
git checkout -b my-fix
# ... make changes ...
git add <files>
git commit -m "fix: [problem] -> [expected behavior]
回滚方案：若合并后出现异常，请执行 git revert HEAD 无损回退。"
git push origin my-fix

# 6. Open a Pull Request on GitHub / 在 GitHub 上发起 Pull Request
```

---

### Mandatory Development Rules / 强制性开发规范

**⚠️ ALL contributors (human + AI agents) MUST follow these rules. Violations = rejected.**
**⚠️ 所有贡献者（人类 + AI Agent）必须遵守以下规则。违反 = 直接打回。**

#### Iron Rules / 核心铁律

1. **One problem per change / 单次变更只解决一个问题** — No refactoring alongside bugfixes. Separate PR for separate problems. / 禁止顺手重构，不同问题单独提 PR。
2. **No defensive coding / 禁止防御性编写** — Don't add null-checks "just in case". Only handle reproduced failures. / 除非异常已复现，否则不要写冗余判空。
3. **Never delete comments / 禁止删除注释** — If a comment is outdated, append a new note below it. Never overwrite or delete. / 过时注释只能在下方追加，禁止覆盖删除。

#### Hard Limits / 硬性红线

| Limit / 限制 | Value / 数值 |
|------|-------|
| Files per change / 每次变更文件数 | **≤ 3** |
| Lines added+deleted / 增删行数 | **≤ 200** (including tests / 含测试) |
| McCabe complexity per new function / 新增函数圈复杂度 | **≤ 10** |
| New dependencies / 新增依赖 | **Zero** (unless explicitly approved / 除非特批) |
| Log level for exceptions / 异常日志级别 | `logger.ERROR` or `logger.WARNING` — **never `print()`** |
| Banned in commits / 提交禁止词 | `TODO`, `FIXME`, hardcoded IP/domain / 硬编码 IP/域名 |

#### Commit Message Format / 提交信息格式

```
fix: [problem现象] -> [expected behavior预期行为]

回滚方案：若合并后出现异常，请执行 git revert HEAD 无损回退。

变更列表：
- file.py: function_name — brief description / 简要说明
```

#### Pre-Commit Self-Check / 提交前自检

- [ ] Logic only changed — no indentation or blank-line reformatting / 只改逻辑，未动缩进空行
- [ ] No `os.system()`, `subprocess.call()`, `eval()` / 未使用高危函数
- [ ] If async changed: no new deadlocks or race conditions / 异步修改无不安全的竞态

---

### How We Work / 协作流程

1. **Choose an issue / 选择 Issue** — Pick from [GitHub Issues](https://github.com/jiaheng0815/ata-coder/issues) or open a new one. / 从 Issue 列表选择，或新建一个。
2. **Discuss approach / 讨论方案** — Comment on the issue before coding. / 写代码前先在 Issue 里沟通思路。
3. **Follow the rules / 遵守规范** — Every commit must comply with the mandatory rules above. / 每个提交必须符合上述强制规范。
4. **Run tests / 运行测试** — `pytest tests/ --ignore=tests/test_server.py -q` must pass 100%. / 必须 100% 通过。
5. **Open a PR / 发起 PR** — Link the issue, describe what changed. / 关联 Issue，说明变更内容。
6. **Code review / 代码审查** — At least one maintainer reviews before merge. / 至少一位维护者审查后合并。

---

### Project Anatomy / 项目结构速览

For a deep dive into the architecture, see the [Project Structure](#project-structure--项目结构) section above. Here's the minimum you need to know to start contributing:

想深入了解架构，看上面的[项目结构](#project-structure--项目结构)章节。以下是贡献者必知的最小集合：

| File / 文件 | What to change here / 改什么时来这里 |
|-------|------|
| `agent.py` | Core agent loop, system prompt, message handling / 核心 Agent 循环、系统提示、消息处理 |
| `agent_tools.py` | Tool execution pipeline, self-correction, streaming / 工具执行管线、自校正、流式输出 |
| `tools/executor.py` | Individual tool implementations (read/write/edit/shell/etc.) / 各工具实现 |
| `tools/definitions.py` | Tool schemas — add new tools here first / 工具定义 — 新增工具先改这里 |
| `safety_guard.py` | Pattern-based risk detection (destructive commands, secrets) / 风险模式检测 |
| `permissions.py` | Interactive allow/deny/ask rules / 交互式权限规则 |
| `server.py` | HTTP API + SSE streaming endpoints / HTTP API + SSE 流式端点 |
| `repl_ui.py` | Terminal UI (Rich + prompt_toolkit) / 终端界面 |
| `llm_client.py` | OpenAI-compatible HTTP client / OpenAI 兼容 HTTP 客户端 |
| `anthropic_client.py` | Anthropic Messages API client / Anthropic Messages API 客户端 |
| `skills.py` | Skill discovery, activation, routing / Skill 发现、激活、路由 |
| `system_prompt_builder.py` | System prompt assembly (sections, caching) / 系统提示组装 |
| `memory.py` | Persistent file-based memory store / 持久化文件记忆 |
| `session.py` | Session save/load/search / 会话持久化 |
| `tests/` | **Always add tests** with your change / **改代码必须加测试** |

---

### Testing / 测试

```bash
# Run all tests (Windows-safe) / 运行全部测试（Windows 安全）
pytest tests/ --ignore=tests/test_server.py

# Run a single test file / 运行单个测试文件
pytest tests/test_agent.py -q

# Run tests matching a name pattern / 按名称过滤
pytest -k "compact" -q

# Run with verbose output / 详细输出模式
pytest tests/ --ignore=tests/test_server.py -v

# Server tests (requires no server running on port 9999)
# 服务器测试（需要 9999 端口空闲）
pytest tests/test_server.py -q
```

### Release Process / 发布流程

```bash
# 1. Bump version in 3 files / 在 3 个文件中更新版本号
#    main.py: __version__ = "X.Y.Z"
#    pyproject.toml: version = "X.Y.Z"
#    setup_wizard.py: __version__ = "X.Y.Z"

# 2. Update CHANGELOG + README / 更新 CHANGELOG 和 README

# 3. Run tests / 运行测试
pytest tests/ --ignore=tests/test_server.py -q

# 4. Commit + push / 提交并推送
git commit -m "release: vX.Y.Z — short description"
git push origin master

# 5. Build / 构建
python -m build --sdist --wheel

# 6. Create GitHub release + upload / 创建 GitHub 发布并上传
gh release create vX.Y.Z --title "vX.Y.Z — description" --notes "..."
gh release upload vX.Y.Z dist/ata_coder-X.Y.Z-py3-none-any.whl dist/ata_coder-X.Y.Z.tar.gz

# 7. Publish to PyPI / 发布到 PyPI
python -m twine upload dist/ata_coder-X.Y.Z*
```

---

## License / 许可证

MIT — see [LICENSE](LICENSE) / 详见 [LICENSE](LICENSE)
