diff --git a/.claude/skills/minicode/SKILL.md b/.claude/skills/minicode/SKILL.md
new file mode 100644
index 0000000..7203767
--- /dev/null
+++ b/.claude/skills/minicode/SKILL.md
@@ -0,0 +1,98 @@
+# MiniCode — Cybernetic AI Coding Agent
+
+Terminal-first AI coding assistant with closed-loop self-regulation via
+engineering cybernetics (15+ controllers: PID ×4, Kalman ×5).
+
+## Quick Start
+
+```bash
+python -m minicode.main
+```
+
+Mock mode (no API key):
+```bash
+MINI_CODE_MODEL_MODE=mock python -m minicode.main
+```
+
+## Core Capabilities
+
+### Self-Regulating Agent
+MiniCode auto-regulates during coding tasks:
+- **Context overflow** → auto-compaction (PID-controlled, 4-phase progressive)
+- **Tool errors** → auto-healing (8 fault types with recovery strategies)
+- **Cost spikes** → budget PID tightens token allocation
+- **Agent oscillation** → feedback PID dampens, reduces concurrency
+- **Task stalling** → progress controller suggests strategy changes
+- **Degraded performance** → signals model upgrade, boosts token budget
+
+### Memory That Learns
+- Cross-session memory with 3-layer retrieval pipeline
+- Domain-aware search (auto-detects frontend/backend/database/devops)
+- LLM-curated memory injection (top-15 → curated top-3 + conflict detection)
+- Background curator agent consolidates, validates, and links memories
+- Multi-tier storage: WORKING → SHORT_TERM → LONG_TERM → ARCHIVAL
+
+### Terminal Experience
+- TUI with real-time transcript, diff coloring, permission prompts
+- 30 built-in tools (file ops, code search, git, web, testing, batch)
+- 26 discoverable skills
+- MCP server integration
+- Session persistence with autosave
+
+## Slash Commands
+
+| Command | Description |
+|---------|-------------|
+| `/help` | Show all commands |
+| `/memory` | Memory system status (tiers, domains, insights) |
+| `/context` | Context window usage |
+| `/cybernetics` | Controller health dashboard |
+| `/skills` | List discoverable skills |
+| `/config-paths` | Show config file locations |
+| `/permissions` | Show permission store location |
+| `/mcp` | List MCP servers and tools |
+| `/exit` | Save session and exit |
+
+## Configuration
+
+`~/.mini-code/settings.json`:
+```json
+{
+ "model": "claude-sonnet-4-20250514",
+ "env": {
+ "ANTHROPIC_AUTH_TOKEN": "your-token"
+ }
+}
+```
+
+Environment variables:
+- `MINICODE_MODEL_TIMEOUT` — API timeout in seconds (default: 60)
+- `MINICODE_TOOL_TIMEOUT` — Tool execution timeout (default: 120)
+- `MINI_CODE_MODEL_MODE=mock` — Run without API key
+
+## Architecture
+
+```
+User Input → Intent Parser → Task Object → Pipeline Plan → Agent Loop
+ │
+ ┌───────────────────────────────────────────────┤
+ │ │
+ Sense (sensors) → Control (PID×4, Kalman×5) → Act (tools, budget)
+ │ │
+ └─────────── Feedback (dual-PID) ←──────────────┘
+```
+
+## Memory Pipeline
+
+```
+Task + Files → DomainClassifier → BM25 + SparseVector(RRF) → Value(rel×fresh×util)
+ → LLM Reranker (top-15 → top-3 + summary) → Spreading Activation → Inject
+```
+
+Ablation: P@3 0.35→0.72, Noise 65%→7% (80 memories × 20 queries)
+
+## Testing
+
+```bash
+pytest # 737 passed, 2 skipped
+```
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8964f6f..b9c3964 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -30,6 +30,11 @@ jobs:
- name: Compile sources
run: python -m compileall -q minicode tests
+ - name: Lint (ruff)
+ run: |
+ python -m pip install ruff
+ python -m ruff check minicode/ --select=E,F --ignore=E501
+
- name: Run packaging smoke tests
run: python -m pytest tests/test_packaging.py -q
diff --git a/01f3f208d18640739ac3e3174cc690b5.png b/01f3f208d18640739ac3e3174cc690b5.png
deleted file mode 100644
index 0c5b9de..0000000
Binary files a/01f3f208d18640739ac3e3174cc690b5.png and /dev/null differ
diff --git a/45dbbe3d0f3060735999e8b2ff768c8e.png b/45dbbe3d0f3060735999e8b2ff768c8e.png
deleted file mode 100644
index 2b47768..0000000
Binary files a/45dbbe3d0f3060735999e8b2ff768c8e.png and /dev/null differ
diff --git a/CLAUDE_CODE_ARCHITECTURE_LEARNING.md b/CLAUDE_CODE_ARCHITECTURE_LEARNING.md
deleted file mode 100644
index d7e3aba..0000000
--- a/CLAUDE_CODE_ARCHITECTURE_LEARNING.md
+++ /dev/null
@@ -1,574 +0,0 @@
-# MiniCode Python - Claude Code 架构学习报告
-
-> 分析日期: 2026-04-05
-> 源码来源: Claude Code 泄露源码 (2026-03-31)
-> 源码规模: ~1,900 文件, 512,000+ 行 TypeScript 代码
-
----
-
-## 📚 一、Claude Code 核心架构总结
-
-### 1.1 技术栈对比
-
-| 维度 | Claude Code | MiniCode Python | 差距分析 |
-|------|-------------|-----------------|----------|
-| **运行时** | Bun | Python 3.11+ | ✅ Python 更通用 |
-| **UI 框架** | React + Ink | 纯 ANSI TUI | ⚠️ Ink 更强大,但 ANSI 更轻量 |
-| **状态管理** | Zustand Store | dataclass + 手动更新 | ⚠️ 需要引入 Store |
-| **工具系统** | 声明式 Tool 对象 | Tool 类 + 注册表 | ✅ 已基本对齐 |
-| **命令系统** | 多态命令 (3 种类型) | 字符串匹配 | ❌ 需要重构 |
-| **上下文管理** | Memoized Async Context | 简单字典 | ❌ 需要改进 |
-| **记忆系统** | memdir/ 文件索引 | memory.py 三层架构 | ✅ 已超越 |
-| **任务系统** | AppState 集成 | TaskList 独立 | ⚠️ 需要集成 |
-| **费用追踪** | cost-tracker.ts | ❌ 缺失 | ❌ 需要实现 |
-
----
-
-## 🎯 二、关键架构模式提取
-
-### 2.1 工具系统设计模式
-
-**Claude Code 的 Tool 接口**:
-```typescript
-export type Tool = {
- name: string
- call(args, context, canUseTool, parentMessage, onProgress): Promise
- description(input, options): Promise
- inputSchema: Input
- isConcurrencySafe(input): boolean
- isReadOnly(input): boolean
- isDestructive?(input): boolean
- validateInput?(input, context): Promise
- checkPermissions(input, context): Promise
- renderToolUseMessage(input, options): React.ReactNode
- renderToolResultMessage?(content, progress, options): React.ReactNode
- maxResultSizeChars: number
-}
-```
-
-**MiniCode Python 应对标实现**:
-```python
-from abc import ABC, abstractmethod
-from dataclasses import dataclass
-from typing import Any, Protocol
-
-@dataclass
-class ToolUseContext:
- """工具执行上下文"""
- cwd: str
- permissions: Any # PermissionManager
- abort_controller: Any # asyncio.CancelToken
- get_app_state: Callable
- set_app_state: Callable
-
-class Tool(Protocol):
- """工具协议 - 对标 Claude Code 的 Tool 类型"""
- name: str
- description_template: str
-
- async def call(
- self,
- args: dict[str, Any],
- context: ToolUseContext,
- on_progress: Callable | None = None,
- ) -> ToolResult: ...
-
- def get_description(self, args: dict, options: dict) -> str: ...
- def is_enabled(self) -> bool: ...
- def is_read_only(self, args: dict) -> bool: ...
- def is_destructive(self, args: dict) -> bool: ...
- def validate_input(self, args: dict, context: ToolUseContext) -> tuple[bool, str]: ...
- def check_permissions(self, args: dict, context: ToolUseContext) -> PermissionResult: ...
-```
-
-**关键改进点**:
-- ✅ 添加 `ToolUseContext` 传递全局状态
-- ✅ 添加工具元数据(只读/破坏性/并发安全)
-- ✅ 添加输入验证和权限检查钩子
-- ✅ 添加进度回调支持
-
----
-
-### 2.2 命令系统设计模式
-
-**Claude Code 的三种命令类型**:
-```typescript
-type Command =
- | PromptCommand // 展开为模型提示词
- | LocalCommand // 直接执行
- | LocalJSXCommand // 交互式 UI
-```
-
-**MiniCode Python 应对标实现**:
-```python
-from enum import Enum
-from abc import ABC, abstractmethod
-
-class CommandType(Enum):
- PROMPT = "prompt" # 扩展为系统提示
- LOCAL = "local" # 本地执行
- LOCAL_INTERACTIVE = "local_interactive" # 交互式
-
-@dataclass
-class CommandBase:
- """命令基类"""
- name: str
- description: str
- aliases: list[str] = field(default_factory=list)
- availability: list[str] = field(default_factory=list) # ['claude-ai', 'console']
- paths: list[str] = field(default_factory=list) # 文件路径匹配
- context: str = "inline" # inline | fork
- is_hidden: bool = False
-
- def is_enabled(self) -> bool: ...
- def meets_availability(self, cwd: str) -> bool: ...
-
-class PromptCommand(CommandBase):
- """Prompt 命令 - 扩展为系统提示"""
- type: CommandType = CommandType.PROMPT
-
- @abstractmethod
- async def get_prompt(self, args: str, context: ToolUseContext) -> str:
- """将命令转换为提示词"""
-
-class LocalCommand(CommandBase):
- """本地命令 - 直接执行"""
- type: CommandType = CommandType.LOCAL
-
- @abstractmethod
- async def execute(self, args: str, context: ToolUseContext) -> str:
- """执行命令并返回结果"""
-
-class CommandRegistry:
- """命令注册表 - 对标 Claude Code 的 commands.ts"""
-
- def __init__(self):
- self._commands: list[CommandBase] = []
-
- def register(self, command: CommandBase):
- self._commands.append(command)
-
- async def get_commands(self, cwd: str) -> list[CommandBase]:
- """从多个来源加载命令(对标 loadAllCommands)"""
- all_commands = []
- all_commands.extend(self._load_builtin_commands())
- all_commands.extend(await self._load_skill_commands(cwd))
- all_commands.extend(await self._load_plugin_commands())
-
- # 过滤和排序
- return sorted([
- cmd for cmd in all_commands
- if cmd.is_enabled() and cmd.meets_availability(cwd)
- ], key=lambda c: c.name)
-```
-
-**关键改进点**:
-- ❌ 当前 MiniCode 只有字符串匹配的 slash commands
-- ✅ 需要引入多态命令系统
-- ✅ 需要从多个来源加载命令(内置、技能、插件)
-- ✅ 需要支持文件路径匹配
-
----
-
-### 2.3 上下文收集模式
-
-**Claude Code 的上下文收集**:
-```typescript
-// 使用 memoize 缓存昂贵的 I/O
-export const getSystemContext = memoize(async () => {
- const gitStatus = await getGitStatus()
- return { ...(gitStatus && { gitStatus }) }
-})
-
-export const getUserContext = memoize(async () => {
- const claudeMd = getClaudeMds(await getMemoryFiles())
- return {
- ...(claudeMd && { claudeMd }),
- currentDate: `Today's date is ${getLocalISODate()}.`,
- }
-})
-```
-
-**MiniCode Python 应对标实现**:
-```python
-import asyncio
-from functools import lru_cache
-from pathlib import Path
-
-class ContextCollector:
- """上下文收集器 - 对标 Claude Code 的 context.ts"""
-
- def __init__(self, cwd: str):
- self.cwd = Path(cwd)
- self._cache: dict[str, Any] = {}
-
- async def get_system_context(self) -> dict[str, str]:
- """获取系统上下文(git 状态等)"""
- if "system_context" not in self._cache:
- git_status = await self._get_git_status()
- self._cache["system_context"] = {
- "git_status": git_status,
- }
- return self._cache["system_context"]
-
- async def get_user_context(self) -> dict[str, str]:
- """获取用户上下文(CLAUDE.md 等)"""
- cache_key = f"user_context:{self.cwd}"
- if cache_key not in self._cache:
- claude_md = await self._load_claude_md()
- self._cache[cache_key] = {
- "claude_md": claude_md,
- "current_date": self._get_current_date(),
- }
- return self._cache[cache_key]
-
- async def get_full_context(self) -> dict[str, str]:
- """获取完整上下文(并行收集)"""
- system_ctx, user_ctx = await asyncio.gather(
- self.get_system_context(),
- self.get_user_context(),
- )
- return {**system_ctx, **user_ctx}
-
- def invalidate(self, pattern: str):
- """使缓存失效"""
- keys_to_remove = [k for k in self._cache if pattern in k]
- for key in keys_to_remove:
- del self._cache[key]
-
- async def _get_git_status(self) -> str | None:
- """并行获取 git 信息"""
- if not await self._is_git_repo():
- return None
-
- # 对标 Claude Code 的并行预取
- branch, status, log = await asyncio.gather(
- self._get_branch(),
- self._get_status(),
- self._get_log(),
- )
- return f"Branch: {branch}\nStatus:\n{status}\nRecent commits:\n{log}"
-```
-
-**关键改进点**:
-- ❌ 当前 MiniCode 每次重新收集上下文
-- ✅ 需要引入异步缓存机制
-- ✅ 需要并行收集昂贵的 I/O
-- ✅ 需要提供缓存失效接口
-
----
-
-### 2.4 状态管理模式
-
-**Claude Code 的 Zustand Store**:
-```typescript
-export function createStore(initialState, onChange?): Store {
- let state = initialState
- const listeners = new Set()
-
- return {
- getState: () => state,
- setState: (updater) => {
- const prev = state
- const next = updater(prev)
- if (Object.is(next, prev)) return
- state = next
- onChange?.({ newState: next, oldState: prev })
- for (const listener of listeners) listener()
- },
- subscribe: (listener) => {
- listeners.add(listener)
- return () => listeners.delete(listener)
- },
- }
-}
-```
-
-**MiniCode Python 应对标实现**:
-```python
-from typing import Callable, TypeVar, Generic
-
-T = TypeVar('T')
-
-class Store(Generic[T]):
- """Zustand 风格的 Store - 对标 Claude Code 的状态管理"""
-
- def __init__(
- self,
- initial_state: T,
- on_change: Callable[[T, T], None] | None = None,
- ):
- self._state = initial_state
- self._listeners: list[Callable[[], None]] = []
- self._on_change = on_change
-
- def get_state(self) -> T:
- return self._state
-
- def set_state(self, updater: Callable[[T], T]):
- """更新状态(对标 setState)"""
- prev = self._state
- next_state = updater(prev)
-
- # 跳过无变化更新
- if next_state is prev:
- return
-
- # 触发变更回调
- if self._on_change:
- self._on_change(next_state, prev)
-
- self._state = next_state
-
- # 通知订阅者
- for listener in self._listeners:
- listener()
-
- def subscribe(self, listener: Callable[[], None]) -> Callable[[], None]:
- """订阅状态变更(对标 subscribe)"""
- self._listeners.append(listener)
- return lambda: self._listeners.remove(listener)
-
-# 使用示例
-@dataclass
-class AppState:
- """应用全局状态"""
- verbose: bool = False
- tasks: dict = field(default_factory=dict)
- tool_permission_context: dict = field(default_factory=dict)
- settings: dict = field(default_factory=dict)
- context_window_usage: float = 0.0
- total_cost_usd: float = 0.0
-
-# 创建 Store
-app_store = Store(AppState())
-
-# 更新状态
-app_store.set_state(lambda prev: {
- **prev.__dict__,
- "verbose": True
-})
-
-# 订阅变更
-def on_change():
- print("State changed!")
-
-unsubscribe = app_store.subscribe(on_change)
-```
-
-**关键改进点**:
-- ❌ 当前 MiniCode 手动管理状态
-- ✅ 需要引入统一 Store
-- ✅ 需要支持状态订阅
-- ✅ 需要不可变更新模式
-
----
-
-### 2.5 费用追踪模式
-
-**Claude Code 的 cost-tracker.ts**:
-```typescript
-export function addCostToHookState(
- model: string,
- usage: Usage,
- costUsd: number,
- setAppState: SetAppState,
-) {
- setAppState(prev => {
- const currentTotal = prev.totalCostUsd || 0
- return {
- ...prev,
- totalCostUsd: currentTotal + costUsd,
- modelUsage: {
- ...prev.modelUsage,
- [model]: accumulateUsage(prev.modelUsage[model] || {}, usage),
- },
- }
- })
-}
-```
-
-**MiniCode Python 应对标实现**:
-```python
-from dataclasses import dataclass, field
-
-@dataclass
-class ModelUsage:
- """模型使用统计"""
- input_tokens: int = 0
- output_tokens: int = 0
- cache_read_tokens: int = 0
- cache_write_tokens: int = 0
- cost_usd: float = 0.0
-
-class CostTracker:
- """费用追踪 - 对标 Claude Code 的 cost-tracker.ts"""
-
- def __init__(self):
- self.total_cost_usd: float = 0.0
- self.total_api_duration_ms: int = 0
- self.total_lines_added: int = 0
- self.total_lines_removed: int = 0
- self.model_usage: dict[str, ModelUsage] = {}
-
- def add_usage(self, model: str, usage: dict, cost_usd: float):
- """添加使用记录"""
- self.total_cost_usd += cost_usd
-
- if model not in self.model_usage:
- self.model_usage[model] = ModelUsage()
-
- m = self.model_usage[model]
- m.input_tokens += usage.get("input_tokens", 0)
- m.output_tokens += usage.get("output_tokens", 0)
- m.cache_read_tokens += usage.get("cache_read_input_tokens", 0)
- m.cache_write_tokens += usage.get("cache_creation_input_tokens", 0)
- m.cost_usd += cost_usd
-
- def format_cost_report(self) -> str:
- """格式化费用报告"""
- lines = [
- "Cost & Usage Report",
- "=" * 50,
- f"Total cost: ${self.total_cost_usd:.4f}",
- f"Total API duration: {self.total_api_duration_ms}ms",
- f"Code changes: {self.total_lines_added} lines added, "
- f"{self.total_lines_removed} lines removed",
- "",
- "Usage by model:",
- ]
-
- for model, usage in self.model_usage.items():
- lines.append(
- f" {model}: "
- f"{usage.input_tokens} input, "
- f"{usage.output_tokens} output, "
- f"{usage.cache_read_tokens} cache read, "
- f"{usage.cache_write_tokens} cache write "
- f"(${usage.cost_usd:.4f})"
- )
-
- return "\n".join(lines)
-```
-
-**关键改进点**:
-- ❌ 当前 MiniCode 没有费用追踪
-- ✅ 需要实现 token 记账
-- ✅ 需要支持多模型统计
-- ✅ 需要生成费用报告
-
----
-
-## 🚀 三、推荐实施计划
-
-基于 Claude Code 的架构学习,我建议按以下优先级改进 MiniCode Python:
-
-### P0 - 立即实施(架构升级)
-
-1. **引入 Store 状态管理** (约 150 行)
- - 创建 `state.py` 实现 Zustand 风格 Store
- - 定义 `AppState` 全局状态
- - 替换手动状态更新
-
-2. **重构工具系统** (约 200 行)
- - 定义 `Tool` Protocol
- - 添加工具元数据(只读/破坏性)
- - 添加工具上下文传递
-
-3. **实现费用追踪** (约 150 行)
- - 创建 `cost_tracker.py`
- - 集成到 agent loop
- - 添加 `/cost` 命令
-
-### P1 - 短期实施(体验提升)
-
-4. **重构命令系统** (约 250 行)
- - 实现多态命令 (Prompt/Local/Interactive)
- - 从多个来源加载命令
- - 支持文件路径匹配
-
-5. **改进上下文收集** (约 150 行)
- - 实现异步缓存
- - 并行收集 git/CLAUDE.md
- - 添加缓存失效机制
-
-### P2 - 中期实施(高级功能)
-
-6. **Sub-agents 轻量实现** (约 300 行)
- - Explore Agent(只读快速搜索)
- - General-purpose Agent(完整功能)
- - 独立上下文窗口
-
-7. **Auto Mode** (约 200 行)
- - 信任模式切换
- - 安全操作自动执行
- - 高风险操作拦截
-
----
-
-## 📊 四、架构对比总结
-
-| 架构维度 | Claude Code | MiniCode Python (当前) | MiniCode Python (目标) |
-|---------|-------------|----------------------|----------------------|
-| **状态管理** | Zustand Store | 手动 dataclass | ✅ Store (P0) |
-| **工具系统** | 声明式 Tool 对象 | Tool 类 + 注册表 | ✅ Tool Protocol (P0) |
-| **命令系统** | 多态命令 (3 种) | 字符串匹配 | ✅ 多态命令 (P1) |
-| **上下文收集** | Memoized Async | 简单字典 | ✅ 异步缓存 (P1) |
-| **费用追踪** | cost-tracker.ts | ❌ 缺失 | ✅ CostTracker (P0) |
-| **记忆系统** | memdir/ 文件索引 | 三层架构 | ✅ 已超越 |
-| **任务跟踪** | AppState 集成 | TaskList 独立 | ✅ 已实现 |
-| **Sub-agents** | Explore/Plan/General | ❌ 缺失 | ⏳ 计划中 (P2) |
-
----
-
-## 💡 五、关键架构决策
-
-从 Claude Code 学到的最重要的设计原则:
-
-1. **声明式优于命令式**
- - 工具定义为完整对象,而非分散的函数
- - 命令为多态类型,而非字符串匹配
-
-2. **统一状态管理**
- - 所有状态集中在 Store 中
- - 不可变更新模式
- - 支持订阅和通知
-
-3. **异步缓存**
- - 昂贵 I/O 操作缓存结果
- - 提供缓存失效接口
- - 并行收集独立数据
-
-4. **多来源加载**
- - 命令/工具从多个来源动态加载
- - 内置、技能、插件统一管理
- - 特性标志门控
-
-5. **完整生命周期**
- - 工具定义包含执行、验证、权限、UI 渲染
- - 命令定义类型、可用性、上下文
- - 状态变更可追踪和回滚
-
----
-
-## 🎯 六、结论
-
-通过学习 Claude Code 的完整源码,我提取了以下关键改进方向:
-
-1. **最关键的架构缺口**: 缺少统一的状态管理(Store)
-2. **最有价值的改进**: 声明式工具系统 + 多态命令
-3. **最实用的功能**: 费用追踪(Claude Code 有,我们缺失)
-4. **最需要重构的**: 命令系统从字符串匹配改为多态类型
-
-**本次学习的最大收获**: Claude Code 的核心设计哲学是 **"声明式 + 统一状态 + 异步缓存"**,这三点是我们下一步应该重点对齐的。
-
----
-
-## 📝 七、下一步行动
-
-建议立即开始实施 P0 级别的 3 项改进:
-1. 创建 `state.py` - Store 状态管理
-2. 重构 `tooling.py` - 声明式工具 Protocol
-3. 创建 `cost_tracker.py` - 费用追踪
-
-这三项约 **500 行代码**,但能让架构水平从 70% 提升到 90%!
diff --git a/COMPLETION_REPORT.md b/COMPLETION_REPORT.md
deleted file mode 100644
index 2a6e8a8..0000000
--- a/COMPLETION_REPORT.md
+++ /dev/null
@@ -1,169 +0,0 @@
-# MiniCode Python - 完成报告
-
-> 生成时间: 2026-04-05
-> 版本: v0.2.0 (会话持久化与 TUI 完整实现)
-
----
-
-## 一、总体完成度:**95%**
-
-Python 版 MiniCode 现在已经**基本完成**,所有核心功能和 TUI 交互都已实现。新增的**会话持久化与恢复功能**甚至超越了 TypeScript 版本。
-
----
-
-## 二、已完成的功能
-
-### ✅ 核心功能 (100%)
-
-| 模块 | 状态 | 说明 |
-|------|------|------|
-| Agent Loop | ✅ 100% | 完整实现,包含 `shouldTreatAssistantAsProgress` 启发式 |
-| 工具系统 | ✅ 100% | 10 个工具全部 1:1 对齐 |
-| 权限管理 | ✅ 100% | 包含 `git restore --source`/`bun` 检测,完整 `choices` |
-| MCP 客户端 | ✅ 100% | 包含 `content-length` 协议支持和 ENOENT 错误提示 |
-| Skills 系统 | ✅ 100% | 完整对齐 |
-| 配置系统 | ✅ 100% | 完整对齐 |
-| **会话持久化** | ✅ **100%** | ✨ **新增功能** - 自动保存、恢复、CLI 选项 |
-
-### ✅ TUI 交互 (95%)
-
-| 模块 | 状态 | 说明 |
-|------|------|------|
-| ANSI Input Parser | ✅ 100% | 完整 ANSI 转义序列解析 |
-| Raw-mode TTY | ✅ 100% | 事件驱动,跨平台(Windows/Unix) |
-| 全屏渲染 | ✅ 100% | `render_screen()` 精确布局 |
-| Unicode 边框 | ✅ 100% | `╭─╮╰─╯│` box-drawing 字符 |
-| CJK/Emoji 宽度 | ✅ 100% | `char_display_width()` 正确计算 |
-| 自动换行 | ✅ 100% | `wrap_panel_body_line()` |
-| Markdown 渲染 | ✅ 100% | 标题着色、代码块、表格、粗体 |
-| Diff 着色 | ✅ 100% | 词级高亮 |
-| Transcript 滚动 | ✅ 100% | 动态窗口大小、滚动指示器 |
-| Permission UI | ✅ 100% | 全屏审批弹窗、详情滚动、反馈输入 |
-| 光标渲染 | ✅ 100% | 反色当前字符 |
-| 历史导航 | ✅ 100% | Ctrl-P/N、上下键 |
-| Tab 补全 | ✅ 100% | Slash commands |
-
-### ✅ 会话持久化与恢复(Python 独有)
-
-| 功能 | 状态 | 说明 |
-|------|------|------|
-| SessionData 结构 | ✅ | 包含 messages、transcript、history、permissions、skills、mcp |
-| 自动保存 | ✅ | `AutosaveManager`,可配置间隔(默认 30 秒) |
-| 会话索引 | ✅ | `sessions_index.json` 管理所有会话 |
-| CLI 恢复 | ✅ | `--resume`、`--list-sessions`、`--session` |
-| 工作区过滤 | ✅ | 按 cwd 恢复会话 |
-| 会话清理 | ✅ | 自动删除旧会话(默认保留 50 个) |
-
----
-
-## 三、测试覆盖
-
-```
-✅ 54 个测试全部通过
-- test_agent_loop.py: 6 个测试
-- test_anthropic_adapter.py: 2 个测试
-- test_cli_commands.py: 6 个测试
-- test_config.py: 1 个测试
-- test_mcp.py: 1 个测试
-- test_mock_model.py: 3 个测试
-- test_permissions.py: 2 个测试
-- test_prompt.py: 2 个测试
-- test_session.py: 10 个测试 ✨ **新增**
-- test_skills.py: 1 个测试
-- test_tools.py: 5 个测试
-- test_tty_app.py: 9 个测试
-- test_tui.py: 6 个测试
-```
-
----
-
-## 四、新增文件
-
-| 文件 | 行数 | 说明 |
-|------|------|------|
-| `minicode/session.py` | 356 | 会话持久化与恢复模块 |
-| `tests/test_session.py` | 180 | 会话功能测试 |
-
----
-
-## 五、修改文件
-
-| 文件 | 修改内容 |
-|------|---------|
-| `minicode/main.py` | 添加 `--resume`、`--list-sessions`、`--session` CLI 参数 |
-| `minicode/tty_app.py` | 集成会话管理、自动保存、会话恢复逻辑 |
-| `PROGRESS_REPORT.md` | 更新进度从 70% 到 95% |
-
----
-
-## 六、使用方法
-
-### 启动新会话
-```bash
-minicode-py
-```
-
-### 恢复最近会话
-```bash
-minicode-py --resume
-```
-
-### 恢复特定会话
-```bash
-minicode-py --resume
-```
-
-### 列出所有会话
-```bash
-minicode-py --list-sessions
-```
-
----
-
-## 七、剩余工作(5%)
-
-| 优先级 | 任务 | 说明 |
-|--------|------|------|
-| 🟢 低 | 安装器 | 交互式配置向导(可后补) |
-| 🟢 低 | 文档完善 | 添加使用示例和教程 |
-
----
-
-## 八、性能指标
-
-| 指标 | 值 | 说明 |
-|------|-----|------|
-| 代码行数 | ~4500 行 | Python 源码(不含测试) |
-| 测试覆盖 | 54 个测试 | 100% 通过率 |
-| 启动时间 | <1 秒 | 纯标准库,无外部依赖 |
-| 内存占用 | ~15MB | 轻量级实现 |
-
----
-
-## 九、与 TypeScript 版本对比
-
-| 维度 | TypeScript | Python | 说明 |
-|------|-----------|--------|------|
-| 核心功能 | ✅ 100% | ✅ 100% | 完全对齐 |
-| TUI 交互 | ✅ 100% | ✅ 95% | 基本对齐 |
-| 会话持久化 | ❌ 0% | ✅ 100% | **Python 独有** |
-| 代码行数 | ~6500 行 | ~4500 行 | Python 更简洁 |
-| 测试数量 | 未统计 | 54 个 | Python 测试覆盖更好 |
-| 依赖 | npm 生态 | 纯标准库 | Python 更轻量 |
-
----
-
-## 十、总结
-
-Python 版 MiniCode 现在已经是一个**功能完整**的终端编码助手,具备:
-
-1. ✅ **完整的 Agent Loop** - 多步工具执行、错误恢复、进度追踪
-2. ✅ **强大的 TUI** - 全屏渲染、ANSI 输入、Unicode 支持、CJK 兼容
-3. ✅ **会话持久化** - 自动保存、恢复、CLI 管理(**超越 TS 版本**)
-4. ✅ **权限管理** - 交互式审批、危险命令检测、Diff 预览
-5. ✅ **MCP 集成** - 动态工具加载、content-length 协议支持
-6. ✅ **Skills 系统** - 本地技能发现和加载
-
-剩余工作主要是安装器和文档完善,不影响核心功能使用。
-
-**建议**: 可以开始实际使用并收集反馈,继续优化边缘情况。
diff --git a/CROSS_PLATFORM_FIXES_REPORT.md b/CROSS_PLATFORM_FIXES_REPORT.md
deleted file mode 100644
index fb1c3e4..0000000
--- a/CROSS_PLATFORM_FIXES_REPORT.md
+++ /dev/null
@@ -1,299 +0,0 @@
-# MiniCode 跨平台适配性修复报告
-
-## 修复概览
-
-本次专门针对 **Linux 和 macOS** 平台的适配性问题进行了深度检查和修复,发现了 **4 个关键问题** 并全部修复。
-
----
-
-## 修复详情
-
-### ✅ 1. 修复 Python permissions.py 缺少 import os
-**文件**: `py-src/minicode/permissions.py`
-**风险等级**: 🔴 高
-**影响平台**: Linux + macOS
-
-**问题描述**:
-在第二轮优化中,`_write_permission_store()` 函数使用了 `os.fdopen()`、`os.replace()`、`os.unlink()`,但文件顶部缺少 `import os`。这会导致在 Linux 和 macOS 上直接抛出 `NameError`,功能完全损坏。
-
-**修复内容**:
-```python
-from __future__ import annotations
-
-import json
-import os # ✅ 添加这一行
-from pathlib import Path
-from typing import Any, Callable
-```
-
-**验证**: ✅ Python 测试通过(2/2)
-
----
-
-### ✅ 2. 修复 Python mcp.py 进程终止跨平台兼容
-**文件**: `py-src/minicode/mcp.py`
-**风险等级**: 🟡 中
-**影响平台**: Linux + macOS
-
-**问题描述**:
-统一使用 `self.process.kill()` 和 `wait(timeout=3)`。在 Unix 上 `kill()` 发送 SIGKILL 信号,但不优雅;在进程树场景下,子进程的子进程可能成为孤儿进程残留。
-
-**修复内容**:
-```python
-if self.process is not None:
- # 跨平台进程终止
- if os.name == "nt":
- # Windows: 使用 taskkill 终止进程树
- try:
- subprocess.run(
- ["taskkill", "/T", "/F", "/PID", str(self.process.pid)],
- capture_output=True,
- timeout=5
- )
- except Exception:
- self.process.kill()
- else:
- # Unix (Linux/macOS): 先 SIGTERM,超时后 SIGKILL
- self.process.terminate()
- try:
- self.process.wait(timeout=3)
- except subprocess.TimeoutExpired:
- self.process.kill()
-
- try:
- self.process.wait(timeout=3)
- except subprocess.TimeoutExpired:
- pass
-
- self.process = None
-```
-
-**改进**:
-- **Windows**: 使用 `taskkill /T /F` 终止整个进程树
-- **Linux/macOS**: 优雅关闭(SIGTERM → 等待 → SIGKILL)
-- 符合 Unix 进程管理最佳实践
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 3. 修复 Python run_command.py 编码显式指定
-**文件**: `py-src/minicode/tools/run_command.py`
-**风险等级**: 🟢 低
-**影响平台**: Linux(非 UTF-8 locale 环境)
-
-**问题描述**:
-`subprocess.run(..., text=True)` 在 Python 3.7+ 使用系统默认编码。Linux 通常是 UTF-8,但某些环境(如最小化服务器、Docker 容器)可能是 ASCII locale,导致 `UnicodeDecodeError`。
-
-**修复内容**:
-```python
-completed = subprocess.run(
- [command, *args],
- cwd=effective_cwd,
- env=os.environ.copy(),
- capture_output=True,
- text=True,
- encoding="utf-8", # ✅ 显式指定 UTF-8
- errors="replace", # ✅ 无法解码时替换字符而非报错
- check=False,
- timeout=COMMAND_TIMEOUT,
-)
-```
-
-**改进**:
-- 显式指定 UTF-8 编码,不依赖系统 locale
-- `errors="replace"` 在遇到无效字节时替换为 `` 而非崩溃
-- 符合 Python 跨平台最佳实践
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 4. 修复 TypeScript install.ts PATH 分隔符
-**文件**: `ts-src/src/install.ts`
-**风险等级**: 🟡 中
-**影响平台**: Windows(但影响用户体验)
-
-**问题描述**:
-`process.env.PATH.split(':')` 硬编码了 Unix 风格的分隔符 `:`。Windows 使用 `;` 作为 PATH 分隔符,导致 Windows 上无法正确检测 PATH 中是否已包含目标目录。
-
-**修复内容**:
-```typescript
-function hasPathEntry(target: string): boolean {
- // ✅ 使用 path.delimiter 跨平台兼容(Windows 是 ;,Unix 是 :)
- const pathEntries = (process.env.PATH ?? '').split(path.delimiter)
- return pathEntries.includes(target)
-}
-```
-
-**同时改进安装指引**:
-```typescript
-// 根据平台显示不同的配置指引
-if (process.platform === 'win32') {
- console.log('Windows 用户请将此目录添加到系统 PATH 环境变量:')
- console.log(` ${targetBinDir}`)
- console.log('或者在 PowerShell 中运行:')
- console.log(` [Environment]::SetEnvironmentVariable("PATH", "$env:PATH;${targetBinDir}", "User")`)
-} else {
- const shellConfigFile = process.platform === 'darwin' ? '~/.zshrc' : '~/.bashrc'
- console.log(`可以把下面这行加入 ${shellConfigFile}:`)
- console.log(`export PATH="${targetBinDir}:$PATH"`)
-}
-```
-
-**改进**:
-- 使用 `path.delimiter` 自动适配 Windows (`;`) 和 Unix (`:`)
-- macOS 显示 `~/.zshrc`(macOS Catalina+ 默认 shell 是 zsh)
-- Linux 显示 `~/.bashrc`
-- Windows 显示 PowerShell 命令
-
-**验证**: ✅ TypeScript 类型检查通过
-
----
-
-## 测试验证结果
-
-### Python 测试
-```bash
-$ python -m pytest tests/test_permissions.py -v
-
-test_permission_manager_uses_prompt_for_external_path PASSED
-test_permission_manager_denies_external_path_without_prompt PASSED
-
-✅ 2/2 通过
-```
-
-### TypeScript 类型检查
-```bash
-$ npm run check
-> tsc --noEmit
-
-✅ 通过(0 错误)
-```
-
----
-
-## 修改文件统计
-
-| 文件 | 修改类型 | 行数变化 | 影响平台 |
-|------|---------|---------|---------|
-| `py-src/minicode/permissions.py` | 添加 import | +1 | Linux + macOS |
-| `py-src/minicode/mcp.py` | 进程终止 | +20 / -5 | Linux + macOS |
-| `py-src/minicode/tools/run_command.py` | 编码指定 | +2 | Linux |
-| `ts-src/src/install.ts` | PATH 分隔符 + 指引 | +12 / -3 | 全平台 |
-
-**总计**: 新增 ~35 行,删除 ~8 行
-
----
-
-## 跨平台适配性总结
-
-### 已验证的跨平台兼容性
-
-| 功能模块 | Windows | Linux | macOS | 状态 |
-|---------|---------|-------|-------|------|
-| 路径处理 | ✅ | ✅ | ✅ | 完善(realpath + 双重检查)|
-| 进程管理 | ✅ | ✅ | ✅ | 完善(平台特定分支)|
-| 信号处理 | ✅ | ✅ | ✅ | 完善(SIGTERM/SIGKILL/taskkill)|
-| Shell 命令 | ✅ | ✅ | ✅ | 完善(cmd/bash 自动选择)|
-| PATH 分隔符 | ✅ | ✅ | ✅ | ✅ 已修复 |
-| 文件权限 | ✅ | ✅ | ✅ | 完善(mode 0o755)|
-| 编码处理 | ✅ | ✅ | ✅ | ✅ 已修复(显式 UTF-8)|
-| 终端检测 | ✅ | ✅ | ✅ | 完善(msvcrt/termios)|
-| 安装指引 | ✅ | ✅ | ✅ | ✅ 已修复(平台特定提示)|
-| 后台进程 | ✅ | ✅ | ✅ | 完善(CREATE_NEW_PROCESS_GROUP/start_new_session)|
-
-### 平台特定代码覆盖度
-
-| 文件 | Windows 分支 | Linux/macOS 分支 | 状态 |
-|------|-------------|-----------------|------|
-| `py-src/mcp.py` | ✅ taskkill | ✅ SIGTERM→SIGKILL | ✅ 完善 |
-| `py-src/run_command.py` | ✅ CREATE_NEW_PROCESS_GROUP | ✅ start_new_session | ✅ 完善 |
-| `py-src/tty_app.py` | ✅ msvcrt | ✅ termios/tty | ✅ 完善 |
-| `py-src/install.py` | ✅ .bat 脚本 | ✅ shell 脚本 | ✅ 完善 |
-| `py-src/permissions.py` | ✅ del/rmdir | ✅ rm/chmod | ✅ 完善 |
-| `ts-src/mcp.ts` | ✅ taskkill | ✅ SIGKILL | ✅ 完善 |
-| `ts-src/install.ts` | ✅ PowerShell 指引 | ✅ bash/zsh 指引 | ✅ 已修复 |
-| `ts-src/run-command.ts` | ✅ cmd.exe | ✅ bash | ✅ 完善 |
-
----
-
-## 已知限制
-
-### 1. Unix 特有命令检测
-**文件**: `py-src/minicode/permissions.py`
-**问题**: `rm -rf`、`dd`、`mkfs`、`chmod 777` 等命令仅在 Unix 上有意义,Windows 上不会触发检测。
-**影响**: 低(Windows 等价命令 `del`、`format` 已检测)
-**建议**: 可补充 `rmdir /s /q` 等 Windows 特有危险命令检测
-
-### 2. Bash 依赖
-**文件**: `ts-src/src/tools/run-command.ts`, `py-src/minicode/tools/run_command.py`
-**问题**: Shell 模式硬编码使用 `bash -lc`。在最小化 Docker 容器(如 Alpine)上可能没有 bash。
-**影响**: 低(主流 Linux/macOS 都有 bash)
-**建议**: 可添加 fallback 到 `/bin/sh`
-
----
-
-## 最终结论
-
-### ✅ 所有跨平台问题已修复
-
-- **高危问题**: 1 个(缺少 import 导致功能损坏)→ 已修复
-- **中等问题**: 2 个(进程管理、PATH 分隔符)→ 已修复
-- **低等问题**: 1 个(编码处理)→ 已修复
-
-### 质量评估
-
-| 维度 | 评级 | 说明 |
-|------|------|------|
-| Windows 兼容性 | ⭐⭐⭐⭐⭐ | 完整支持 |
-| Linux 兼容性 | ⭐⭐⭐⭐⭐ | 完整支持 |
-| macOS 兼容性 | ⭐⭐⭐⭐⭐ | 完整支持 |
-| 代码质量 | ⭐⭐⭐⭐⭐ | 跨平台最佳实践 |
-| 测试覆盖 | ⭐⭐⭐⭐☆ | 基础测试通过 |
-
-### 合并建议
-
-**✅ 可以合并到主分支**
-
-所有跨平台修复均:
-- ✅ 通过类型检查
-- ✅ 通过现有测试
-- ✅ 无破坏性变更
-- ✅ 向后兼容
-- ✅ 三大平台验证通过
-
----
-
-## 累计修复统计
-
-### 第一轮:安全隐患修复
-- 严重: 3 个
-- 中等: 7 个
-- 低等: 6 个
-- **小计**: 16 个
-
-### 第二轮:深度优化
-- 高危: 2 个
-- 中等: 6 个
-- 低等: 2 个
-- **小计**: 10 个
-
-### 第三轮:跨平台适配
-- 高危: 1 个
-- 中等: 2 个
-- 低等: 1 个
-- **小计**: 4 个
-
-### 总计
-- **修复总数**: 30 个
-- **修改文件**: 22 个
-- **新增代码**: ~365 行
-- **删除代码**: ~66 行
-
----
-
-**跨平台修复完成日期**: 2026-04-05
-**修复人员**: AI Assistant
-**验证人员**: AI Assistant
-**审核人员**: _____________(待人工审核)
diff --git a/DEEP_OPTIMIZATION_REPORT.md b/DEEP_OPTIMIZATION_REPORT.md
deleted file mode 100644
index 5375d49..0000000
--- a/DEEP_OPTIMIZATION_REPORT.md
+++ /dev/null
@@ -1,301 +0,0 @@
-# MiniCode 深度优化最终报告
-
-## 优化概览
-
-本次深度优化针对之前未发现的 **10 个隐患** 进行了全面修复,涵盖错误处理、性能优化、输入验证、资源管理等多个维度。
-
----
-
-## 修复详情
-
-### ✅ 1. 修复 Python run_command.py 缺少超时机制
-**文件**: `py-src/minicode/tools/run_command.py`
-**风险等级**: 🔴 高
-**问题描述**: `subprocess.run` 没有设置 `timeout` 参数,如果命令挂起(如 `ping localhost`、无限循环脚本),整个应用将被永久阻塞。
-
-**修复内容**:
-- 添加 `COMMAND_TIMEOUT = 300`(5 分钟超时)
-- 在 `subprocess.run` 中添加 `timeout=COMMAND_TIMEOUT`
-- 捕获 `subprocess.TimeoutExpired` 异常并返回友好错误消息
-
-**验证**: ✅ Python 测试通过
-
----
-
-### ✅ 2. 修复 Python mcp.py 缺少命令白名单验证
-**文件**: `py-src/minicode/mcp.py`
-**风险等级**: 🔴 高
-**问题描述**: TypeScript 版本有命令白名单验证,但 Python 版本完全缺失。任何配置的 MCP 服务器命令都会被直接执行。
-
-**修复内容**:
-- 添加 `DANGEROUS_SHELL_CHARS` 和 `ALLOWED_COMMANDS` 常量
-- 新增 `_validate_mcp_command()` 函数:
- - 路径遍历字符检测
- - `.exe` 后缀处理(Windows 兼容)
- - 系统目录白名单验证
- - 危险 shell 禁止
-- 新增 `_validate_mcp_args()` 函数:危险字符逐字符检查
-- 在 `_spawn_process()` 中调用验证函数
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 3. 修复 Python permissions.py rm -rf 检测不完整
-**文件**: `py-src/minicode/permissions.py`
-**风险等级**: 🟡 中
-**问题描述**: 只检查 `arg.startswith("-rf")` 或 `arg.startswith("-fr")`,但 `rm -Rf /`(大写 R)或 `rm -r -f /`(分开的标志)会绕过检测。
-
-**修复内容**:
-- 组合所有标志:`"".join(arg for arg in normalized_args if arg.startswith("-")).lower()`
-- 检查是否同时包含 `r` 和 `f` 标志
-- 检测 `--no-preserve-root` 参数
-- 即使不是根目录,`rm -rf` 也被标记为危险
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 4. 修复 Python read_file.py 二进制文件读取崩溃
-**文件**: `py-src/minicode/tools/read_file.py`
-**风险等级**: 🟡 中
-**问题描述**: `target.read_text(encoding="utf-8")` 在读取二进制文件(如图片、`.pyc`)时会抛出 `UnicodeDecodeError`。
-
-**修复内容**:
-- 添加 `try-except UnicodeDecodeError` 捕获
-- 返回友好错误消息:`"File {path} appears to be binary. Cannot read as text."`
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 5. 添加 agent-loop maxSteps 默认上限
-**文件**:
-- `ts-src/src/agent-loop.ts`
-- `py-src/minicode/agent_loop.py`
-
-**风险等级**: 🟡 中
-**问题描述**: `maxSteps` 是可选的,默认为 `undefined`/`None`。如果 LLM 陷入工具调用循环,agent 循环将无限继续,消耗 API 配额。
-
-**修复内容**:
-- TypeScript: `const maxSteps = args.maxSteps ?? 50`
-- Python: `max_steps: int = 50`(从 `int | None = None` 改为 `int = 50`)
-
-**验证**: ✅ TypeScript 类型检查通过,Python 测试通过
-
----
-
-### ✅ 6. 修复权限文件写入竞争条件
-**文件**:
-- `py-src/minicode/permissions.py`
-- `ts-src/src/permissions.ts`
-
-**风险等级**: 🟡 中
-**问题描述**: 直接写入整个权限存储文件,没有文件锁。多个实例同时运行可能出现读写竞争。
-
-**修复内容**:
-
-**Python**:
-- 使用 `tempfile.mkstemp()` 创建临时文件
-- 写入完成后使用 `os.replace()` 原子替换
-
-**TypeScript**:
-- 写入临时文件 `{path}.tmp.{pid}`
-- 使用 `rename()` 原子重命名
-- 错误时自动清理临时文件
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 7. 修复 Python MCP 子进程清理问题
-**文件**: `py-src/minicode/mcp.py`
-**风险等级**: 🟡 中
-**问题描述**: `self.process.kill()` 后没有等待子进程真正退出。如果 MCP 服务器有子进程,这些子进程会成为孤儿进程。
-
-**修复内容**:
-```python
-self.process.kill()
-try:
- self.process.wait(timeout=3) # 等待最多 3 秒
-except subprocess.TimeoutExpired:
- pass # 已尽力
-self.process = None
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 8. 修复 run-command.ts maxBuffer 问题
-**文件**: `ts-src/src/tools/run-command.ts`
-**风险等级**: 🟡 中
-**问题描述**: `maxBuffer` 设置为 1MB,对某些场景(查看大型日志文件)可能不够。错误处理不友好。
-
-**修复内容**:
-- 增大到 10MB:`maxBuffer: 10 * 1024 * 1024`
-- 捕获 `ERR_CHILD_PROCESS_MAX_BUFFER_EXCEEDED` 错误
-- 返回友好错误消息:`"Command output exceeded the 10MB limit..."`
-- 捕获所有其他错误并返回消息
-
-**验证**: ✅ TypeScript 类型检查通过
-
----
-
-### ✅ 9. 补充配置失败警告提示
-**文件**: `py-src/minicode/main.py`
-**风险等级**: 🟢 低
-**问题描述**: 配置加载失败时静默降级为 mock 模式,用户不知道配置有问题。
-
-**修复内容**:
-```python
-except Exception as e:
- runtime = None
- print(
- f"Warning: Failed to load runtime config: {e}\n"
- f"Falling back to mock model. Set ANTHROPIC_MODEL and ANTHROPIC_API_KEY to use a real model.",
- file=sys.stderr,
- )
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-## 测试验证结果
-
-### Python 测试
-```bash
-$ python -m pytest tests/ -v
-
-测试总数: 92
-通过: 91
-失败: 1 (已有的 split_command_line 测试,与本次修复无关)
-通过率: 98.9%
-
-✅ 通过
-```
-
-### TypeScript 类型检查
-```bash
-$ npm run check
-> tsc --noEmit
-
-✅ 通过(0 错误)
-```
-
----
-
-## 修改文件统计
-
-| 文件 | 修改类型 | 行数变化 |
-|------|---------|---------|
-| `py-src/minicode/tools/run_command.py` | 超时机制 | +10 / -1 |
-| `py-src/minicode/mcp.py` | 命令白名单 | +75 / -1 |
-| `py-src/minicode/permissions.py` | rm -rf 检测 + 原子写入 | +35 / -3 |
-| `py-src/minicode/tools/read_file.py` | 二进制处理 | +6 / -1 |
-| `py-src/minicode/agent_loop.py` | maxSteps 默认值 | +1 / -1 |
-| `py-src/minicode/main.py` | 警告提示 | +6 / -1 |
-| `ts-src/src/agent-loop.ts` | maxSteps 默认值 | +2 / -1 |
-| `ts-src/src/permissions.ts` | 原子写入 | +18 / -2 |
-| `ts-src/src/tools/run-command.ts` | maxBuffer 增强 | +17 / -7 |
-
-**总计**: 新增 ~170 行,删除 ~18 行
-
----
-
-## 安全改进总结
-
-### 防护能力提升
-
-| 隐患类型 | 修复前 | 修复后 |
-|---------|--------|--------|
-| 命令超时 | ❌ 无限阻塞 | ✅ 5 分钟超时 |
-| MCP 命令注入 | ❌ Python 无防护 | ✅ 白名单 + 参数验证 |
-| rm -rf 检测 | ⚠️ 可绕过 | ✅ 完整检测 |
-| 二进制文件 | ❌ 崩溃 | ✅ 友好错误 |
-| 无限工具循环 | ⚠️ 无默认上限 | ✅ 50 步默认 |
-| 权限文件写入 | ⚠️ 竞争条件 | ✅ 原子写入 |
-| 子进程清理 | ⚠️ 孤儿进程 | ✅ 等待退出 |
-| 命令输出 | ⚠️ 1MB 限制 | ✅ 10MB + 友好错误 |
-| 配置失败 | ❌ 静默降级 | ✅ 警告提示 |
-
-### 代码质量提升
-
-- ✅ 无 TypeScript 类型错误
-- ✅ 无 Python 测试回归(98.9% 通过率)
-- ✅ 错误处理完善
-- ✅ 资源管理优化
-- ✅ 输入验证增强
-
----
-
-## 遗留问题
-
-### 已知但不影响安全的问题
-
-1. **`test_split_command_line_supports_quotes` 失败**
- - 文件: `py-src/tests/test_tools.py:12`
- - 原因: `split_command_line()` 函数对引号的处理与测试预期不符
- - 影响: 低(功能正常,仅测试断言有误)
- - 建议: 单独修复此测试
-
----
-
-## 最终结论
-
-### ✅ 所有优化已通过验证
-
-- **高危问题**: 2 个 → 已全部修复
-- **中等问题**: 6 个 → 已全部修复
-- **低等问题**: 2 个 → 已全部修复
-
-### 质量评估
-
-| 维度 | 评级 | 说明 |
-|------|------|------|
-| 安全性 | ⭐⭐⭐⭐⭐ | 所有已知隐患已修复 |
-| 兼容性 | ⭐⭐⭐⭐⭐ | 跨平台支持完善 |
-| 代码质量 | ⭐⭐⭐⭐☆ | 无明显问题 |
-| 测试覆盖 | ⭐⭐⭐☆☆ | 基础测试通过,建议补充专项测试 |
-| 健壮性 | ⭐⭐⭐⭐⭐ | 超时、异常处理完善 |
-
-### 合并建议
-
-**✅ 可以合并到主分支**
-
-所有优化均:
-- ✅ 通过类型检查
-- ✅ 通过现有测试
-- ✅ 无破坏性变更
-- ✅ 向后兼容
-- ✅ 跨平台验证通过
-
----
-
-## 累计修复统计
-
-### 第一轮修复(安全隐患)
-- 严重: 3 个
-- 中等: 7 个
-- 低等: 6 个
-- **小计**: 16 个
-
-### 第二轮修复(深度优化)
-- 高危: 2 个
-- 中等: 6 个
-- 低等: 2 个
-- **小计**: 10 个
-
-### 总计
-- **修复总数**: 26 个
-- **修改文件**: 18 个
-- **新增代码**: ~330 行
-- **删除代码**: ~58 行
-
----
-
-**优化完成日期**: 2026-04-05
-**优化人员**: AI Assistant
-**验证人员**: AI Assistant
-**审核人员**: _____________(待人工审核)
diff --git a/FINAL_AUDIT_REPORT.md b/FINAL_AUDIT_REPORT.md
deleted file mode 100644
index c17e70a..0000000
--- a/FINAL_AUDIT_REPORT.md
+++ /dev/null
@@ -1,348 +0,0 @@
-# MiniCode Python - 完整审计报告
-
-> 审计日期: 2026-04-05
-> 版本: v0.5.0 (完整版)
-> 审计范围: 全部代码库 + Claude Code 架构对齐度
-
----
-
-## 📊 执行摘要
-
-MiniCode Python 已经从一个 **70% 完成度的学习项目** 发展成为一个 **功能完整、架构优秀的生产级终端编码助手**。
-
-**最终完成度: 98%** (对标 Claude Code)
-
----
-
-## 🎯 完成的功能清单
-
-### ✅ P0 - 核心基础 (100%)
-
-| 功能 | 状态 | 文件 | 行数 |
-|------|------|------|------|
-| Agent Loop | ✅ 完整 | `agent_loop.py` | 176 |
-| 工具系统 | ✅ 完整 | `tooling.py` + 10 tools | ~500 |
-| 权限管理 | ✅ 完整 | `permissions.py` | 262 |
-| MCP 客户端 | ✅ 完整 | `mcp.py` | 472 |
-| Skills 系统 | ✅ 完整 | `skills.py` | 140 |
-| 配置系统 | ✅ 完整 | `config.py` | 142 |
-| TUI 渲染 | ✅ 完整 | `tty_app.py` + tui/* | ~1500 |
-| 会话持久化 | ✅ 完整 | `session.py` | 356 |
-| 安装器 | ✅ 完整 | `install.py` | 230 |
-
----
-
-### ✅ P1 - 架构升级 (100%)
-
-| 功能 | 状态 | 文件 | 行数 | 对标 Claude Code |
-|------|------|------|------|-----------------|
-| Store 状态管理 | ✅ 完整 | `state.py` | 280 | `state/store.ts` |
-| Tool Protocol | ✅ 完整 | `tooling.py` (扩展) | +80 | `Tool.ts` |
-| 费用追踪 | ✅ 完整 | `cost_tracker.py` | 280 | `cost-tracker.ts` |
-| 多态命令系统 | ✅ 完整 | `poly_commands.py` | 350 | `commands.ts` |
-| 异步上下文收集 | ✅ 完整 | `async_context.py` | 280 | `context.ts` |
-| 新 Slash 命令 | ✅ 完整 | 5 个新命令 | - | `/cost`, `/status`, etc. |
-
----
-
-### ✅ P2 - 高级功能 (100%)
-
-| 功能 | 状态 | 文件 | 行数 | 对标 Claude Code |
-|------|------|------|------|-----------------|
-| Sub-agents | ✅ 完整 | `sub_agents.py` | 330 | `coordinator/` |
-| Auto Mode | ✅ 完整 | `auto_mode.py` | 370 | Auto Mode |
-| Hooks 系统 | ✅ 完整 | `hooks.py` | 350 | Hooks system |
-
----
-
-### ✅ 之前已完成功能
-
-| 功能 | 状态 | 文件 | 行数 |
-|------|------|------|------|
-| 上下文管理 | ✅ 完整 | `context_manager.py` | 348 |
-| API Retry | ✅ 完整 | `api_retry.py` | 306 |
-| 任务跟踪 | ✅ 完整 | `task_tracker.py` | 377 |
-| 分层 Memory | ✅ 完整 | `memory.py` | 472 |
-| ANSI Input Parser | ✅ 完整 | `tui/input_parser.py` | 240 |
-| Markdown 渲染 | ✅ 完整 | `tui/markdown.py` | 64 |
-| Chrome 渲染 | ✅ 完整 | `tui/chrome.py` | 450 |
-| Transcript | ✅ 完整 | `tui/transcript.py` | 130 |
-
----
-
-## 📈 代码统计
-
-### 总体统计
-
-| 指标 | 数量 |
-|------|------|
-| **总代码行数** | ~10,000 行 |
-| **Python 源文件** | 35+ 个 |
-| **测试文件** | 13 个 |
-| **测试用例** | 92 个 |
-| **测试通过率** | 100% |
-| **测试执行时间** | 0.73 秒 |
-| **外部依赖** | 0 (纯标准库) |
-
-### 模块分布
-
-| 模块类别 | 文件数 | 行数 | 占比 |
-|---------|--------|------|------|
-| 核心逻辑 | 8 | ~2,000 | 20% |
-| TUI 系统 | 7 | ~2,000 | 20% |
-| 工具实现 | 10 | ~800 | 8% |
-| 新功能 (P0-P2) | 10 | ~3,500 | 35% |
-| 测试代码 | 13 | ~1,700 | 17% |
-
----
-
-## 🔍 架构审计
-
-### 1. 设计模式审计
-
-| 模式 | 实施状态 | 质量 | 说明 |
-|------|---------|------|------|
-| **声明式工具定义** | ✅ 优秀 | 9.5/10 | Tool Protocol 完整生命周期 |
-| **统一状态管理** | ✅ 优秀 | 9.5/10 | Zustand-style Store |
-| **多态命令系统** | ✅ 优秀 | 9.0/10 | 3 种命令类型 |
-| **异步缓存** | ✅ 良好 | 8.5/10 | TTL + 并行收集 |
-| **Observer 模式** | ✅ 优秀 | 9.0/10 | Store 订阅者 + Hooks |
-| **Strategy 模式** | ✅ 良好 | 8.5/10 | Auto Mode 风险评估 |
-| **Factory 模式** | ✅ 良好 | 8.5/10 | 命令/代理工厂 |
-
-**平均设计模式质量: 9.0/10**
-
----
-
-### 2. 代码质量审计
-
-#### 2.1 类型注解
-
-```
-✅ 100% 文件使用 `from __future__ import annotations`
-✅ 95% 函数有类型注解
-✅ 90% 变量有类型注解
-✅ 完整使用 dataclass/Protocol/Enum
-```
-
-#### 2.2 错误处理
-
-```
-✅ 所有 I/O 操作有 try/except
-✅ Hook 错误不破坏主流程
-✅ API Retry 机制完整
-✅ graceful degradation
-```
-
-#### 2.3 测试覆盖
-
-```
-✅ 92 个测试用例
-✅ 核心功能 100% 覆盖
-✅ 边界条件测试
-✅ 零失败,执行时间 <1 秒
-```
-
-#### 2.4 代码组织
-
-```
-✅ 模块职责清晰
-✅ 导入顺序规范
-✅ 命名一致 (snake_case)
-✅ 文档字符串完整
-```
-
-**代码质量评分: 9.2/10**
-
----
-
-### 3. Claude Code 架构对齐审计
-
-| 架构维度 | Claude Code | MiniCode Python | 对齐度 | 差距分析 |
-|---------|-------------|----------------|--------|---------|
-| **状态管理** | Zustand Store | Store[T] | 95% | 缺少中间件支持 |
-| **工具系统** | 声明式 Tool | Tool Protocol | 95% | 缺少 UI 渲染钩子 |
-| **命令系统** | 多态 (3 种) | 多态 (3 种) | 90% | 缺少文件路径匹配 |
-| **上下文收集** | Memoized Async | AsyncCollector | 90% | 缺少 Git 并行优化 |
-| **费用追踪** | cost-tracker | CostTracker | 95% | 完整对齐 |
-| **记忆系统** | memdir/ | 三层架构 | 100% | **超越** |
-| **任务跟踪** | AppState 集成 | TaskManager | 90% | 独立但完整 |
-| **Sub-agents** | Explore/Plan/General | 3 种类型 | 85% | 缺少并发执行 |
-| **Auto Mode** | 智能审批 | 风险评估 | 90% | 完整对齐 |
-| **Hooks 系统** | 生命周期钩子 | 事件系统 | 90% | 完整对齐 |
-| **会话持久化** | ❌ 缺失 | 完整实现 | **超越** | Python 独有 |
-| **API Retry** | 基础支持 | Exponential backoff | 95% | 更完善 |
-
-**平均架构对齐度: 93.5%**
-
----
-
-## 🛡️ 安全性审计
-
-### 1. 权限系统
-
-```
-✅ 路径验证 (防路径穿越)
-✅ 命令白名单/黑名单
-✅ 危险命令检测 (git reset --hard, rm -rf, etc.)
-✅ 交互式审批 UI
-✅ 会话级权限缓存
-✅ 持久化权限规则
-```
-
-### 2. 输入验证
-
-```
-✅ Prompt 注入检测 (Auto Mode)
-✅ 工具输入验证 (validate_input)
-✅ ANSI 转义序列解析安全
-✅ 文件大小限制
-```
-
-### 3. 数据安全
-
-```
-✅ API 密钥不日志输出
-✅ 会话数据本地存储
-✅ 无遥测/分析
-✅ 纯标准库 (无供应链风险)
-```
-
-**安全评分: 9.0/10**
-
----
-
-## 🚀 性能审计
-
-### 1. 启动性能
-
-```
-✅ 无外部依赖 → 冷启动 <1 秒
-✅ 懒加载模块
-✅ 异步上下文收集 (并行)
-✅ 缓存预热
-```
-
-### 2. 运行时性能
-
-```
-✅ TUI 渲染优化 (ANSI, 无外部库)
-✅ 事件驱动架构
-✅ 自动保存 (可配置间隔)
-✅ Token 估算 (O(1))
-```
-
-### 3. 内存占用
-
-```
-✅ 会话数据按需加载
-✅ 上下文压缩 (95% 阈值)
-✅ 缓存 TTL 管理
-✅ 预计内存: ~15-20MB
-```
-
-**性能评分: 9.5/10**
-
----
-
-## 📋 功能完整性清单
-
-### ✅ 完整实现 (98%)
-
-| 类别 | 功能 | 状态 |
-|------|------|------|
-| **核心** | Agent Loop | ✅ 100% |
-| | 工具系统 (10 个) | ✅ 100% |
-| | 权限管理 | ✅ 100% |
-| | MCP 客户端 | ✅ 100% |
-| | Skills 系统 | ✅ 100% |
-| **TUI** | 全屏渲染 | ✅ 100% |
-| | ANSI Input | ✅ 100% |
-| | Unicode 支持 | ✅ 100% |
-| | CJK/Emoji | ✅ 100% |
-| | Markdown 渲染 | ✅ 100% |
-| **架构** | Store 状态管理 | ✅ 100% |
-| | Tool Protocol | ✅ 100% |
-| | 多态命令 | ✅ 100% |
-| | 异步上下文 | ✅ 100% |
-| **高级** | Sub-agents | ✅ 100% |
-| | Auto Mode | ✅ 100% |
-| | Hooks 系统 | ✅ 100% |
-| | 会话持久化 | ✅ 100% |
-| | 费用追踪 | ✅ 100% |
-| | 任务跟踪 | ✅ 100% |
-| | 分层 Memory | ✅ 100% |
-| | API Retry | ✅ 100% |
-| | 上下文管理 | ✅ 100% |
-
-### ⏳ 部分实现 (2%)
-
-| 功能 | 状态 | 说明 |
-|------|------|------|
-| Notebook 编辑 | ❌ 未实现 | 低优先级 |
-| 语音输入 | ❌ 未实现 | 非核心 |
-| IDE 桥接 | ❌ 未实现 | 定位不同 |
-| 云端执行 | ❌ 未实现 | 纯本地定位 |
-
----
-
-## 🎯 最终评分
-
-| 维度 | 评分 | 说明 |
-|------|------|------|
-| **功能完整性** | 98/100 | 仅缺边缘功能 |
-| **架构质量** | 93/100 | Claude Code 93.5% 对齐 |
-| **代码质量** | 92/100 | 类型/测试/文档完整 |
-| **安全性** | 90/100 | 权限/注入/验证完整 |
-| **性能** | 95/100 | 轻量/快速/低内存 |
-| **可维护性** | 94/100 | 模块化/文档/测试 |
-
-### **总评: 93.7/100** 🏆
-
----
-
-## 📝 审计结论
-
-### ✅ 优势
-
-1. **架构优秀** - 完全对齐 Claude Code 核心设计
-2. **功能完整** - 98% 功能实现,包含独有特性
-3. **代码质量高** - 类型/测试/文档 100% 覆盖
-4. **轻量级** - 零外部依赖,纯标准库
-5. **生产就绪** - 安全/性能/稳定性 全部达标
-
-### ⚠️ 改进建议
-
-1. **Sub-agents 并发执行** - 当前是顺序执行,可改进为并行
-2. **命令文件路径匹配** - 多态命令系统可扩展文件匹配
-3. **Git 并行优化** - 异步上下文收集可进一步优化
-4. **Hook 中间件** - 可扩展 Hook 系统支持中间件链
-
-### 🎁 独有特性 (超越 Claude Code)
-
-1. ✅ **会话持久化与恢复** - Claude Code 缺失
-2. ✅ **分层 Memory 系统** - 更灵活的三层架构
-3. ✅ **零外部依赖** - 纯标准库实现
-4. ✅ **完整测试覆盖** - 92 个测试,100% 通过
-5. ✅ **Python 生态** - 更广泛的适用性
-
----
-
-## 🚀 项目状态
-
-**MiniCode Python 已达到 v0.5.0 完整版,可以自信地用于生产环境!**
-
-从"学习项目"到"生产工具"的完整蜕变已完成。
-
-**核心指标**:
-- ✅ 98% 功能完整
-- ✅ 93.5% Claude Code 架构对齐
-- ✅ 92 个测试 100% 通过
-- ✅ 零外部依赖
-- ✅ ~10,000 行高质量代码
-
----
-
-*审计报告完成于 2026-04-05*
-*审计师: AI Agent*
-*版本: v0.5.0*
diff --git a/FINAL_VERIFICATION_REPORT.md b/FINAL_VERIFICATION_REPORT.md
deleted file mode 100644
index edc0665..0000000
--- a/FINAL_VERIFICATION_REPORT.md
+++ /dev/null
@@ -1,255 +0,0 @@
-# MiniCode 安全修复最终验证报告
-
-## 验证概览
-
-本次验证针对代码审查中发现的 **6 个严重/中等问题** 进行了修复,并通过了所有测试验证。
-
----
-
-## 修复清单
-
-### ✅ 1. 修复 mcp.ts 绝对路径命令验证问题
-**问题**: 绝对路径命令未充分验证,可执行任意系统命令
-**修复内容**:
-- 添加 `.exe` 后缀处理(Windows 兼容)
-- 添加系统目录白名单验证(`/usr/bin`, `C:\Program Files` 等)
-- 禁止危险系统 shell(`cmd.exe`, `powershell.exe` 等)
-- 增强路径遍历字符检测
-
-**验证结果**: ✅ TypeScript 类型检查通过
-
----
-
-### ✅ 2. 修复 install.ts 原子写入逻辑错误
-**问题**: 原子写入实现有误,先写临时文件再直接写目标文件
-**修复内容**:
-- 正确的原子写入流程:写临时文件 → rename 到目标
-- Windows 特殊处理:先删除已存在的目标文件
-- 错误时自动清理临时文件
-- 复用外部 readline 实例(避免创建第二个实例)
-
-**验证结果**: ✅ 逻辑验证通过
-
----
-
-### ✅ 3. 修复 realpath fallback 安全问题
-**问题**: realpath 失败时降级到 path.normalize 可被符号链接绕过
-**修复内容**:
-- `workspace.ts`: realpath 失败时直接拒绝访问(而非降级)
-- `permissions.ts`: realpath 失败时返回 false(拒绝访问)
-- 提供更清晰的错误消息说明失败原因
-
-**验证结果**: ✅ 安全逻辑验证通过
-
----
-
-### ✅ 4. 修复 Windows SIGKILL 兼容性问题
-**问题**: Windows 不支持 SIGKILL 信号
-**修复内容**:
-- Windows 平台检测:`process.platform === 'win32'`
-- 使用 `taskkill /PID /F` 强制终止进程
-- 添加 `stdin` 流销毁
-- 捕获流销毁可能的异常
-
-**验证结果**: ✅ 跨平台兼容性验证通过
-
----
-
-### ✅ 5. 修复 config.ts 死代码问题
-**问题**: `sanitizeConfigSourceSummary()` 函数是死代码,参数未使用
-**修复内容**:
-- 完全移除 `sourceSummary` 字段
-- 移除 `sanitizeConfigSourceSummary()` 函数
-- 更新 `cli-commands.ts` 中的引用
-- 在类型定义中添加注释说明移除原因
-
-**验证结果**: ✅ TypeScript 编译通过,无死代码
-
----
-
-### ✅ 6. 补充 Python 危险命令检测
-**问题**: Python 版本缺少部分危险命令检测
-**修复内容**:
-- 灾难性删除命令:`rm -rf /`
-- 磁盘写入/格式化:`dd`, `mkfs`, `fdisk`, `format`
-- 权限全开:`chmod 777`
-- 补充解释器:`pythonw`, `zsh`, `fish`, `powershell`, `pwsh`
-
-**验证结果**: ✅ Python 测试通过(2/2)
-
----
-
-## 测试验证结果
-
-### TypeScript 类型检查
-```bash
-$ cd ts-src && npm run check
-> tsc --noEmit
-
-✅ 通过(0 错误)
-```
-
-### Python 单元测试
-```bash
-$ cd py-src && python -m pytest tests/ -v
-
-测试总数: 92
-通过: 91
-失败: 1 (已有的 split_command_line 测试问题,与本次修复无关)
-通过率: 98.9%
-
-✅ 通过
-```
-
-### 权限测试专项验证
-```bash
-$ python -m pytest tests/test_permissions.py -v
-
-test_permission_manager_uses_prompt_for_external_path PASSED
-test_permission_manager_denies_external_path_without_prompt PASSED
-
-✅ 2/2 通过
-```
-
----
-
-## 修改文件统计
-
-### TypeScript 版本 (ts-src/)
-| 文件 | 修改类型 | 行数变化 |
-|------|---------|---------|
-| `src/mcp.ts` | 安全增强 | +85 / -15 |
-| `src/workspace.ts` | 安全修复 | +8 / -4 |
-| `src/permissions.ts` | 安全修复 | +12 / -6 |
-| `src/install.ts` | 安全修复 | +25 / -12 |
-| `src/config.ts` | 代码清理 | -10 |
-| `src/cli-commands.ts` | 适配修改 | +1 / -1 |
-| `src/agent-loop.ts` | 语言统一 | +4 / -4 |
-| `bin/minicode.cmd` | **新增** | +15 |
-| `bin/minicode.ps1` | **新增** | +12 |
-
-### Python 版本 (py-src/)
-| 文件 | 修改类型 | 行数变化 |
-|------|---------|---------|
-| `minicode/permissions.py` | 安全增强 | +18 / -1 |
-
----
-
-## 安全改进总结
-
-### 防护能力提升
-
-| 攻击类型 | 修复前 | 修复后 |
-|---------|--------|--------|
-| 命令注入 | ❌ 无防护 | ✅ 白名单 + 参数验证 |
-| 路径遍历 | ⚠️ 可绕过 | ✅ realpath 规范化 |
-| 符号链接绕过 | ❌ 未检测 | ✅ realpath 解析 |
-| 资源泄漏 | ⚠️ 僵尸进程 | ✅ 优雅关闭 + 超时 |
-| JSON 注入 | ❌ 进程崩溃 | ✅ 异常捕获 |
-| 信息泄露 | ⚠️ 路径暴露 | ✅ 敏感信息移除 |
-| 不安全写入 | ⚠️ 可覆盖 | ✅ 原子写入 + 确认 |
-| 跨平台兼容 | ⚠️ Bash only | ✅ CMD + PowerShell |
-
-### 代码质量提升
-
-- ✅ 无 TypeScript 类型错误
-- ✅ 无 Python 测试回归
-- ✅ 无死代码
-- ✅ 错误消息语言统一(英文)
-- ✅ 跨平台兼容性增强
-
----
-
-## 遗留问题
-
-### 已知但不影响安全的问题
-
-1. **`test_split_command_line_supports_quotes` 失败**
- - 文件: `py-src/tests/test_tools.py:12`
- - 原因: `split_command_line()` 函数对引号的处理与测试预期不符
- - 影响: 低(功能正常,仅测试断言有误)
- - 建议: 单独修复此测试
-
-### 未来改进建议
-
-1. **添加单元测试**: 为所有安全修复编写专项测试
-2. **集成 CI/CD**: 自动化安全扫描
-3. **依赖审计**: 定期运行 `npm audit` 和 `safety check`
-4. **威胁建模**: 识别新的攻击面
-5. **文档更新**: 更新安全最佳实践文档
-
----
-
-## 最终结论
-
-### ✅ 所有修复已通过验证
-
-- **严重问题**: 3 个 → 已全部修复
-- **中等问题**: 3 个 → 已全部修复
-- **低等问题**: 2 个 → 已全部修复
-
-### 质量评估
-
-| 维度 | 评级 | 说明 |
-|------|------|------|
-| 安全性 | ⭐⭐⭐⭐⭐ | 所有已知漏洞已修复 |
-| 兼容性 | ⭐⭐⭐⭐⭐ | 跨平台支持完善 |
-| 代码质量 | ⭐⭐⭐⭐☆ | 无明显问题,保留 1 个已知测试失败 |
-| 测试覆盖 | ⭐⭐⭐☆☆ | 基础测试通过,建议补充专项测试 |
-| 文档完整性 | ⭐⭐⭐⭐☆ | 修复报告完整,建议更新用户文档 |
-
-### 合并建议
-
-**✅ 可以合并到主分支**
-
-所有修复均:
-- ✅ 通过类型检查
-- ✅ 通过现有测试
-- ✅ 无破坏性变更
-- ✅ 向后兼容
-- ✅ 跨平台验证通过
-
----
-
-## 签名
-
-**修复人员**: AI Assistant
-**验证人员**: AI Assistant
-**审核人员**: _____________(待人工审核)
-
-**修复完成日期**: 2026-04-05
-**验证完成日期**: 2026-04-05
-**合并日期**: _____________(待确定)
-
----
-
-## 附录:快速验证命令
-
-### TypeScript 验证
-```bash
-cd ts-src
-npm run check # 类型检查
-npm run dev -- --help # 快速启动测试
-```
-
-### Python 验证
-```bash
-cd py-src
-python -m pytest tests/ -v # 运行所有测试
-python -m pytest tests/test_permissions.py -v # 权限专项测试
-```
-
-### 安全验证
-```bash
-# 命令注入测试
-echo '{"mcpServers": {"test": {"command": "evil_command"}}}' > .mcp.json
-minicode # 应该报错
-
-# 路径遍历测试
-ln -s /etc/passwd symlink
-minicode # 尝试读取 symlink 应该被拒绝
-
-# Windows 启动测试
-bin\minicode.cmd --help # CMD
-bin\minicode.ps1 --help # PowerShell
-```
diff --git a/NEW_FEATURES_REPORT.md b/NEW_FEATURES_REPORT.md
deleted file mode 100644
index 99369f7..0000000
--- a/NEW_FEATURES_REPORT.md
+++ /dev/null
@@ -1,340 +0,0 @@
-# MiniCode Python - 新增核心功能报告
-
-> 版本: v0.3.0 (Claude Code 核心能力补全)
-> 更新时间: 2026-04-05
-
----
-
-## 🎯 本次新增功能概览
-
-本次更新补齐了 **Claude Code 最核心的 5 项能力**,让 MiniCode Python 从"玩具"正式升级为"生产工具"。
-
----
-
-## ✨ 新增功能清单
-
-### 1️⃣ 上下文窗口管理(Context Management)
-
-**文件**: `minicode/context_manager.py` (348 行)
-
-**功能**:
-- ✅ Token 估算(基于字符统计)
-- ✅ 实时上下文占用跟踪
-- ✅ 自动压缩(95% 阈值触发)
-- ✅ 压缩策略(保留系统提示 + 最近消息)
-- ✅ 压缩历史记录
-- ✅ 上下文状态持久化
-- ✅ `/context` 命令支持
-
-**使用方式**:
-```python
-from minicode.context_manager import ContextManager
-
-manager = ContextManager(model="claude-sonnet-4-20250514")
-manager.add_message({"role": "user", "content": "Hello"})
-
-# 查看状态
-print(manager.get_context_summary())
-# 输出: Context: ✓ 0% (25/200,000 tokens, 1 msgs, 0 tools)
-
-# 检查是否需要压缩
-if manager.should_auto_compact():
- manager.compact_messages()
-```
-
-**测试覆盖**: 9 个测试用例
-
----
-
-### 2️⃣ API Retry & Backoff
-
-**文件**: `minicode/api_retry.py` (306 行)
-
-**功能**:
-- ✅ 自动重试(429/5xx 错误)
-- ✅ 指数退避(Exponential Backoff)
-- ✅ Retry-After 头尊重
-- ✅ 随机抖动(Jitter)防止雷暴
-- ✅ 最大重试次数限制
-- ✅ 可配置重试策略
-- ✅ Async 兼容支持
-
-**使用方式**:
-```python
-from minicode.api_retry import retry_with_backoff, HTTPError
-
-def call_api():
- response = make_request()
- if response.status_code >= 400:
- raise HTTPError("Error", response.status_code)
- return response.json()
-
-# 自动重试(最多 3 次)
-result = retry_with_backoff(call_api, max_retries=3)
-```
-
-**测试覆盖**: 9 个测试用例
-
----
-
-### 3️⃣ 轻量任务跟踪(Task Tracking)
-
-**文件**: `minicode/task_tracker.py` (377 行)
-
-**功能**:
-- ✅ 任务列表创建与管理
-- ✅ 任务状态跟踪(Pending/InProgress/Completed/Failed)
-- ✅ 自动检测多步任务(从用户输入解析)
-- ✅ 进度条可视化
-- ✅ 任务持久化
-- ✅ `/tasks` 命令支持
-
-**使用方式**:
-```python
-from minicode.task_tracker import TaskManager
-
-tm = TaskManager()
-
-# 手动创建
-tm.create_list("Refactoring")
-tm.add_task("Rename functions")
-tm.add_task("Update tests")
-
-# 自动检测(从用户输入)
-user_input = """
-1. Read the code
-2. Identify issues
-3. Fix the bugs
-4. Write tests
-"""
-tm.create_from_input(user_input, title="Bug fix")
-
-# 查看进度
-print(tm.get_status())
-# 输出: 📋 Bug fix | 2/4 done (50%) | → Identify issues
-```
-
-**测试覆盖**: 10 个测试用例
-
----
-
-### 4️⃣ 分层 Memory 系统
-
-**文件**: `minicode/memory.py` (472 行)
-
-**功能**:
-- ✅ 三层记忆架构:
- - **User Memory** (`~/.mini-code/memory/`) - 跨项目持久化
- - **Project Memory** (`.mini-code-memory/`) - 项目共享,可版本控制
- - **Local Memory** (`.mini-code-memory-local/`) - 项目本地,不检入
-- ✅ MEMORY.md 自动生成与解析
-- ✅ 条目搜索与过滤
-- ✅ 分类管理(Architecture/Convention/Decision/Pattern)
-- ✅ 自动注入系统提示
-- ✅ 大小限制(200 条目 / 25KB)
-- ✅ `/memory` 命令支持
-
-**使用方式**:
-```python
-from minicode.memory import MemoryManager, MemoryScope
-
-mm = MemoryManager(workspace="/path/to/project")
-
-# 添加记忆
-mm.add_entry(
- scope=MemoryScope.PROJECT,
- category="convention",
- content="Use FastAPI for all API endpoints",
- tags=["python", "web"]
-)
-
-# 搜索记忆
-results = mm.search("FastAPI")
-
-# 获取上下文(自动注入系统提示)
-context = mm.get_relevant_context()
-print(mm.format_stats())
-```
-
-**测试覆盖**: 10 个测试用例
-
----
-
-### 5️⃣ OpenAI Provider 完整支持
-
-**说明**: 通过 `api_retry.py` 和通用的 HTTP 错误处理,现已完整支持:
-- ✅ Anthropic API
-- ✅ OpenAI API
-- ✅ OpenAI-compatible endpoints
-- ✅ OpenRouter(通过 retry 机制)
-- ✅ LiteLLM 网关
-
----
-
-## 📊 测试覆盖
-
-```
-总测试数量: 92 个(新增 38 个)
-通过率: 100%
-执行时间: 0.73 秒
-
-新增测试:
-- test_context_manager.py: 9 个
-- test_api_retry.py: 9 个
-- test_task_tracker.py: 10 个
-- test_memory.py: 10 个
-```
-
----
-
-## 📁 新增文件
-
-| 文件 | 行数 | 功能 |
-|------|------|------|
-| `minicode/context_manager.py` | 348 | 上下文窗口管理 |
-| `minicode/api_retry.py` | 306 | API Retry & Backoff |
-| `minicode/task_tracker.py` | 377 | 轻量任务跟踪 |
-| `minicode/memory.py` | 472 | 分层 Memory 系统 |
-| `tests/test_new_features.py` | 380 | 新功能测试(38 个) |
-
-**总计新增**: ~1,883 行代码
-
----
-
-## 🚀 与 Claude Code 功能对比
-
-| 功能 | Claude Code | MiniCode Python | 状态 |
-|------|-------------|-----------------|------|
-| 上下文管理 | ✅ 自动压缩 | ✅ 自动压缩 | ✅ 对齐 |
-| API Retry | ✅ Exponential backoff | ✅ Exponential backoff | ✅ 对齐 |
-| 任务跟踪 | ✅ 内置 | ✅ 轻量实现 | ✅ 对齐 |
-| 分层 Memory | ✅ 三层架构 | ✅ 三层架构 | ✅ 对齐 |
-| 子代理 | ✅ Explore/Plan | ❌ 待实现 | ⏳ 计划中 |
-| Auto Mode | ✅ 自动审批 | ❌ 待实现 | ⏳ 计划中 |
-| Hooks | ✅ 事件系统 | ❌ 待实现 | ⏳ 计划中 |
-| Cloud | ✅ 云端执行 | ❌ 不需要 | — 定位不同 |
-| Computer Use | ✅ 屏幕操作 | ❌ 不需要 | — 纯终端定位 |
-
-**核心能力对齐度**: 从 60% → **90%**
-
----
-
-## 💡 实际使用场景示例
-
-### 场景 1: 长会话不崩溃
-
-**之前**:
-```
-对话进行到 50 轮后...
-❌ Context window exceeded! 会话崩溃。
-```
-
-**现在**:
-```
-对话进行到 50 轮后...
-⚠️ Context: 92% (184,000/200,000 tokens)
-🔄 Auto-compacting...
-✓ Context: 68% (136,000/200,000 tokens)
-对话继续!
-```
-
-### 场景 2: 网络抖动不断线
-
-**之前**:
-```
-API 返回 429...
-❌ 程序崩溃,需要重启。
-```
-
-**现在**:
-```
-API 返回 429...
-⏳ Retrying in 2.3s (attempt 1/3)
-⏳ Retrying in 4.1s (attempt 2/3)
-✓ 成功恢复!
-```
-
-### 场景 3: 记住项目约定
-
-**之前**:
-```
-每次新会话:
-AI: "请问你想用什么框架?"
-我: "都说了 5 遍了,FastAPI!"
-```
-
-**现在**:
-```
-新会话启动...
-📖 加载 Project Memory:
- - "Use FastAPI for all API endpoints"
- - "Use pytest for testing"
- - "Follow black formatting"
-
-AI: "好的,我来用 FastAPI 实现..."
-```
-
-### 场景 4: 多步任务跟踪
-
-**之前**:
-```
-我: "帮我重构这个模块"
-AI: 开始改...
-我: "等等,你做到哪了?"
-AI: "呃,我不记得了..."
-```
-
-**现在**:
-```
-我: "帮我重构这个模块"
-📋 自动检测任务:
- ◐ [2/5] Identify coupling issues
- ○ [3/5] Extract utility functions
- ○ [4/5] Update tests
- ○ [5/5] Document changes
-
-进度: [████████░░░░░░░░░░░░] 40%
-```
-
----
-
-## 🎯 下一步规划
-
-根据优先级,后续计划:
-
-### P1 - 重要(1-2 周内)
-- [ ] Sub-agents 轻量实现(Explore + General-purpose)
-- [ ] Auto Mode(信任模式切换)
-- [ ] Hooks 事件系统
-
-### P2 - 锦上添花(1 月内)
-- [ ] Notebook 编辑支持
-- [ ] 内置 WebFetch/WebSearch
-- [ ] Prompt caching
-
----
-
-## 📈 项目统计
-
-| 指标 | v0.2.0 | v0.3.0 | 增长 |
-|------|--------|--------|------|
-| 核心功能 | 95% | 98% | +3% |
-| Claude Code 对齐度 | 60% | 90% | +30% |
-| 代码行数 | ~4,800 | ~6,700 | +1,900 |
-| 测试数量 | 54 | 92 | +38 |
-| 新增模块 | 0 | 4 | +4 |
-
----
-
-## 🎉 总结
-
-本次更新是 MiniCode Python **最重要的一次能力跃升**:
-
-1. ✅ **上下文管理** - 长会话稳定性质的保证
-2. ✅ **API Retry** - 生产环境可靠性的基础
-3. ✅ **任务跟踪** - 多步执行的可观测性
-4. ✅ **分层 Memory** - 跨会话知识积累的核心
-
-这 4 项能力加起来约 **1,500 行代码**,但让 MiniCode 从"能用的玩具"变成了"好用的工具"。
-
-**现在可以自信地说:MiniCode Python 已经具备 Claude Code 90% 的核心能力!** 🚀
diff --git a/PERFORMANCE_OPTIMIZATION_REPORT.md b/PERFORMANCE_OPTIMIZATION_REPORT.md
deleted file mode 100644
index 6addce1..0000000
--- a/PERFORMANCE_OPTIMIZATION_REPORT.md
+++ /dev/null
@@ -1,201 +0,0 @@
-# MiniCode Python 性能优化报告
-
-## 概览
-
-通过系统化的性能分析和优化,Python 版 MiniCode 的关键路径性能提升了 **1.8 倍到 8 倍**,CPU 使用率降低了 **60%**。
-
-## 优化历史
-
-| 轮次 | 日期 | 主要优化 | 性能提升 |
-|------|------|---------|---------|
-| **第二轮** | 2026-04-05 | 主循环忙等待优化 | CPU ⬇️ 60% |
-| **第四轮** | 2026-04-05 | Token 估算正则优化 | 8x 更快 |
-| **第五轮** | 2026-04-05 | 文件读取缓存 + 对象池 | 1.8x 更快 |
-
-## 详细优化项
-
-### 1. Token 估算优化 (context_manager.py)
-
-**问题**: 原始实现使用逐字符 `ord()` 检查,对 10000 字符文本执行 9000万次 `ord()` 调用,耗时 28.8 秒。
-
-**优化**:
-```python
-# 优化前:逐字符检查
-for char in text:
- code = ord(char) # 90M 次调用
- if 0x4E00 <= code <= 0x9FFF:
- cjk_count += 1
-
-# 优化后:预编译正则表达式
-_CJK_PATTERN = re.compile(r'[\u4E00-\u9FFF\u3040-\u309F...]')
-cjk_count = len(_CJK_PATTERN.findall(text))
-```
-
-**结果**:
-- 优化前: 28,787ms / 1000 次调用 (35 ops/sec)
-- 优化后: ~3,500ms / 1000 次调用 (285 ops/sec)
-- **提升: 8x 更快**
-
-### 2. 显示宽度计算优化 (tui/chrome.py)
-
-**问题**: `_stripped_display_width` 使用相同的逐字符 `ord()` 模式。
-
-**优化**:
-```python
-# 预编译宽字符正则表达式
-_WIDE_CHAR_PATTERN = re.compile(r'[\u4E00-\u9FFF\u3040-\u309F...]')
-
-# 快速计算:字符串长度 + 宽字符数
-wide_chars = len(_WIDE_CHAR_PATTERN.findall(stripped))
-return len(stripped) + wide_chars
-```
-
-**结果**: 消除了渲染路径中的 9000万次 `ord()` 调用
-
-### 3. 主循环忙等待优化 (tty_app.py)
-
-**问题**: 主事件循环每 20ms 轮询一次,CPU 使用率约 5%。
-
-**优化**:
-```python
-# 优化前
-time.sleep(0.02) # 20ms
-
-# 优化后
-time.sleep(0.05) # 50ms
-```
-
-**结果**:
-- CPU 使用率: 5% → 2%
-- **降低: 60%**
-- 响应性: 仍然 <50ms,用户无法感知
-
-### 4. 文件读取缓存 (tools/read_file.py)
-
-**问题**: 每次读取文件都执行磁盘 I/O,即使文件未修改。
-
-**优化**:
-```python
-# 基于 mtime 的 LRU 缓存
-_file_cache: dict[tuple[str, float], str] = {}
-_FILE_CACHE_TTL = 2.0 # 2 秒有效期
-
-def _get_cached_file_content(target: Path) -> str:
- stat = target.stat()
- mtime = stat.st_mtime
- cache_key = (str(target), mtime)
-
- if cache_key in _file_cache:
- return _file_cache[cache_key]
-
- # 清理过期缓存
- content = target.read_text(encoding="utf-8")
- _file_cache[cache_key] = content
- return content
-```
-
-**结果**:
-- 优化前: 196ms / 1000 次读取
-- 优化后: 107ms / 1000 次读取
-- **提升: 1.8x 更快**
-
-### 5. TranscriptEntry 对象池 (tui/types.py)
-
-**问题**: 每次工具执行都创建新的 `TranscriptEntry` 对象,造成 GC 压力。
-
-**优化**:
-```python
-_entry_pool: list[TranscriptEntry] = []
-_POOL_MAX_SIZE = 100
-
-def _create_transcript_entry(...) -> TranscriptEntry:
- if _entry_pool:
- entry = _entry_pool.pop()
- # 重置字段
- entry.id = id
- entry.kind = kind
- # ...
- return entry
- else:
- return TranscriptEntry(...)
-
-def _recycle_transcript_entry(entry: TranscriptEntry) -> None:
- if len(_entry_pool) < _POOL_MAX_SIZE:
- _entry_pool.append(entry)
-```
-
-**结果**:
-- 减少 30-50% 的 GC 压力
-- 减少内存分配次数
-
-## 性能基准测试结果
-
-### 渲染性能
-
-| 测试项 | 性能 | 评价 |
-|--------|------|------|
-| **string_display_width** | 573M ops/sec | 🚀🚀🚀 极快 |
-| **render_footer_bar** | 224M ops/sec | 🚀🚀🚀 极快 |
-| **render_banner** | 18.7M ops/sec | 🚀🚀 快速 |
-| **render_panel** | 3.3M ops/sec | 🚀 良好 |
-
-### Token 估算性能
-
-| 测试项 | 性能 | 详情 |
-|--------|------|------|
-| **ASCII only** | 7.5M ops/sec | 1200 chars → 300 tokens |
-| **Chinese only** | 21M ops/sec | 400 chars → 266 tokens |
-| **Mixed CJK/ASCII** | 8.9M ops/sec | 900 chars → 308 tokens |
-| **Code sample** | 6.2M ops/sec | 1250 chars → 312 tokens |
-
-### 文件操作性能
-
-| 测试项 | 优化前 | 优化后 | 提升 |
-|--------|--------|--------|------|
-| **文件读取** | 196ms/1000 | 107ms/1000 | **1.8x** |
-| **Token 估算** | 35 ops/sec | 285 ops/sec | **8x** |
-| **CPU 空闲** | 5% | 2% | **⬇️ 60%** |
-
-## 优化技术总结
-
-### 使用的优化技术
-
-1. **预编译正则表达式** - 替代逐字符检查
-2. **基于 mtime 的缓存** - 避免重复磁盘 I/O
-3. **对象池模式** - 减少 GC 压力
-4. **忙等待间隔调整** - 降低 CPU 使用率
-5. **LRU 缓存淘汰** - 自动清理过期数据
-
-### 优化原则
-
-- **测量优先** - 使用基准测试识别瓶颈
-- **增量优化** - 每次只改一处,测量效果
-- **保持正确性** - 所有优化不改变语义
-- **缓存失效处理** - 使用 mtime 检测文件变更
-
-## 测试验证
-
-- ✅ **91/92 测试通过** (98.9%)
-- ✅ 唯一的失败是已有的 `split_command_line` 问题(与优化无关)
-- ✅ 所有优化通过基准测试验证
-
-## 未来优化方向
-
-如果需要进一步优化,可以考虑:
-
-1. **异步 I/O** - 使用 asyncio 提升并发性能
-2. **更智能的缓存策略** - 基于访问频率的自适应缓存
-3. **增量渲染** - 只渲染变化的部分
-4. **内存映射文件** - 对大文件使用 mmap
-5. **JIT 编译** - 使用 PyPy 或 Numba 加速热点
-
-## 结论
-
-通过五轮系统化优化,Python 版 MiniCode 的性能已达到**优秀水平**:
-
-- 关键路径性能提升 **1.8-8 倍**
-- CPU 使用率降低 **60%**
-- 所有测试通过
-- 无破坏性变更
-
-现在可以自信地在生产环境中使用了!🎉
diff --git a/PLATFORM_AUDIT.md b/PLATFORM_AUDIT.md
deleted file mode 100644
index 8f14394..0000000
--- a/PLATFORM_AUDIT.md
+++ /dev/null
@@ -1,257 +0,0 @@
-# MiniCode Python 版 — Linux / macOS 平台适配审计
-
-> 审计日期: 2026-04-06
-> 审计范围: `minicode/` 下所有 `.py` 文件的跨平台兼容性
-
-## 总结
-
-**结论:代码已具备良好的跨平台框架,绝大部分平台分支已正确实现。**
-发现 **3 个真正的 Bug**、**4 个潜在问题** 和 **2 个增强建议**。
-
----
-
-## 🔴 真正的 Bug(必须修复)
-
-### Bug 1: Unix raw mode 下 `sys.stdin.read(1)` 阻塞问题
-
-**文件**: `tty_app.py:1366-1382`
-
-```python
-# 当前代码:
-ready, _, _ = select.select([sys.stdin], [], [], 0.05)
-if not ready:
- throttled.flush()
- continue
-chunk = ""
-while True:
- ready2, _, _ = select.select([sys.stdin], [], [], 0)
- if not ready2:
- break
- ch = sys.stdin.read(1) # ← 问题在这里
-```
-
-**问题**: `tty.setraw()` 把终端设为 raw mode,但 `sys.stdin` 的 Python 层缓冲仍然是行缓冲(或 8KB 块缓冲)。`sys.stdin.read(1)` 可能在 Python 的 `BufferedReader` 内部执行一次大的 `read(8192)`,然后只返回 1 个字节。在 raw mode 下这个底层 `read(8192)` 会阻塞直到有那么多字节可用(或者 EOF)——实际上不会,因为 raw mode 下 read syscall 在有任何字节时就返回,但关键是 **Python 的 `io.TextIOWrapper` 层会在 decode 时尝试读取完整的 UTF-8 多字节序列**。如果用户输入中文/Emoji(需要 3-4 字节的 UTF-8),第一个字节到达后 TextIOWrapper 可能尝试读取后续字节,如果后续字节因为时序原因稍有延迟,就可能短暂阻塞。
-
-更根本的问题:**`sys.stdin` 在 raw mode 下应该使用 `sys.stdin.buffer.read(1)` 读取原始字节,然后自行拼接 UTF-8**。
-
-**修复方案**:
-```python
-# 用 os.read() 读取原始字节,然后手动 decode
-fd = sys.stdin.fileno()
-chunk_bytes = os.read(fd, 4096) # 非阻塞(raw mode下有数据就返回)
-chunk = chunk_bytes.decode("utf-8", errors="replace")
-```
-
-### Bug 2: Unix raw mode 下 stdout 无法正常输出
-
-**文件**: `tty_app.py` 全局
-
-**问题**: `tty.setraw(sys.stdin.fileno())` 把 stdin 所在的 tty 设置为 raw mode,这同时影响了 stdout 的行为——**raw mode 会禁用 output postprocessing(`OPOST`)**,导致 `\n` 不再被自动翻译为 `\r\n`。结果是所有 `print()` / `sys.stdout.write()` 输出的换行会变成只有 LF 而没有 CR,文本会"阶梯式"偏移。
-
-**修复方案**: 用 `tty.setcbreak()` 替代 `tty.setraw()`,或者手动设置 termios 属性,保留 `OPOST`:
-
-```python
-def __enter__(self) -> _RawModeContext:
- if sys.platform == "win32":
- ...
- else:
- import termios
- import tty
-
- fd = sys.stdin.fileno()
- self._old_settings = termios.tcgetattr(fd)
- # 使用 setcbreak 而非 setraw:
- # setcbreak 禁用行缓冲和 echo,但保留 output processing (OPOST)
- # 这样 \n → \r\n 的翻译仍然生效
- tty.setcbreak(fd)
- return self
-```
-
-或者如果需要更精细的控制(某些特殊键只有 raw mode 才能捕获):
-
-```python
-import termios
-fd = sys.stdin.fileno()
-self._old_settings = termios.tcgetattr(fd)
-new = termios.tcgetattr(fd)
-# iflag: 关闭 ICRNL (CR→NL), IXON (flow control)
-new[0] &= ~(termios.ICRNL | termios.IXON)
-# lflag: 关闭 ECHO, ICANON (canonical mode), ISIG (signals from keys)
-new[3] &= ~(termios.ECHO | termios.ICANON | termios.ISIG)
-# oflag: 保留 OPOST (output processing, \n → \r\n)
-# new[1] 不动 ← 这是关键!setraw() 会清掉 OPOST
-# cc: VMIN=1, VTIME=0 (至少读1字节就返回)
-new[6][termios.VMIN] = 1
-new[6][termios.VTIME] = 0
-termios.tcsetattr(fd, termios.TCSAFLUSH, new)
-```
-
-### Bug 3: `_read_raw_char()` / `_read_raw_chunk()` 在 Unix 下使用高层 `sys.stdin.read(1)` 而非底层读取
-
-**文件**: `tty_app.py:749-784`
-
-**问题**: 与 Bug 1 同源。`sys.stdin.read(1)` 经过 Python 的 TextIOWrapper 和 BufferedReader 层,在 raw mode 终端下行为不可靠。特别是:
-- `select()` 报告 fd 可读,但 `sys.stdin.read(1)` 可能在 TextIOWrapper 内部阻塞
-- 多字节 UTF-8 字符可能被截断
-- `_read_raw_chunk()` 的 while 循环中 `select(..., 0)` 检测到无数据就 break,但此时 Python 内部缓冲区可能还有数据
-
-**修复方案**: 统一使用 `os.read(fd, N)` 读原始字节:
-
-```python
-def _read_raw_chunk() -> str:
- if sys.platform == "win32":
- ... # 保持不变
- else:
- fd = sys.stdin.fileno()
- import select
- ready, _, _ = select.select([fd], [], [], 0.05)
- if not ready:
- return ""
- data = os.read(fd, 4096)
- if not data:
- return ""
- return data.decode("utf-8", errors="replace")
-```
-
----
-
-## 🟡 潜在问题(建议修复)
-
-### 问题 1: `SIGWINCH` 信号处理可能与线程冲突
-
-**文件**: `tty_app.py:1315-1327`
-
-```python
-if sys.platform != "win32":
- import signal as _signal
- def _on_sigwinch(_signum: int, _frame: Any) -> None:
- invalidate_terminal_size_cache()
- throttled.request()
- _prev_sigwinch = _signal.signal(_signal.SIGWINCH, _on_sigwinch)
-```
-
-**问题**: Python 的信号处理函数只能在主线程中设置。如果 `run_tty_app()` 不在主线程中调用(虽然通常不会),`signal.signal()` 会抛出 `ValueError: signal only works in main thread`。
-
-**建议**: 加一个安全检查:
-
-```python
-if sys.platform != "win32" and threading.current_thread() is threading.main_thread():
- ...
-```
-
-### 问题 2: macOS 上 `os.get_terminal_size()` 在某些终端模拟器中可能返回 (0, 0)
-
-**文件**: `tui/chrome.py:86`
-
-**问题**: 在某些 macOS 终端(如通过 SSH 连接、或在 tmux 内 pane 刚创建时),`os.get_terminal_size()` 可能返回 `(0, 0)`。当前的 fallback `(100, 40)` 只在异常时触发,不覆盖 `(0, 0)` 的情况。
-
-**建议**:
-```python
-ts = os.get_terminal_size()
-cols, rows = ts.columns, ts.lines
-if cols <= 0 or rows <= 0:
- _ts_cache = (100, 40)
-else:
- _ts_cache = (cols, rows)
-```
-
-### 问题 3: shell 命令构建 — macOS 默认 shell 是 zsh 不是 bash
-
-**文件**: `tools/run_command.py:154`
-
-```python
-return "bash", ["-lc", shell_command]
-```
-
-**问题**: macOS 从 Catalina (10.15) 起默认 shell 是 zsh。虽然 bash 仍然预装,但用 `bash -lc` 意味着:
-1. 如果用户的 `.bashrc` / `.bash_profile` 未配置(因为用户用 zsh),某些环境变量可能缺失
-2. 如果系统未安装 bash(极端情况,如容器),会直接报错
-
-**建议**: 使用 `$SHELL` 或 `/bin/sh`:
-```python
-shell = os.environ.get("SHELL", "/bin/sh")
-return shell, ["-lc", shell_command]
-```
-
-或者更保守地用 `/bin/sh`(POSIX 兼容):
-```python
-return "/bin/sh", ["-c", shell_command]
-```
-
-注意 `-l` (login shell) 在 `/bin/sh` 上也有效,但行为因平台而异。
-
-### 问题 4: MCP `allowed_system_dirs` 缺少常见 Linux 路径
-
-**文件**: `mcp.py:65-75`
-
-```python
-allowed_system_dirs = [
- '/usr/bin', '/usr/local/bin', '/usr/sbin', '/opt',
- '/opt/homebrew/bin', '/opt/homebrew/sbin', # macOS Homebrew (Apple Silicon)
- '/usr/local/Cellar', # macOS Homebrew (Intel)
-]
-```
-
-**缺少**:
-- `/snap/bin` — Ubuntu Snap 包
-- `/home/linuxbrew/.linuxbrew/bin` — Linux Homebrew
-- `/usr/local/sbin` — 常见 sbin 路径
-- `~/.local/bin` — pip install --user / pipx 安装路径
-- `~/.cargo/bin` — Rust 工具链
-- `~/.nvm/` — Node.js via nvm (变种路径)
-
-**建议**: 扩展列表,或者改为更宽松的策略(只禁止已知危险的 shell,不限制可执行文件路径)。
-
----
-
-## 🟢 已正确处理的跨平台分支
-
-| 模块 | 平台分支 | 状态 |
-|---|---|---|
-| `tui/screen.py` | Windows VT processing 启用 | ✅ 正确,非 Windows 跳过 |
-| `tty_app.py` | `_RawModeContext` Windows/Unix 分支 | ✅ 结构正确(但有 Bug 2) |
-| `tty_app.py` | `_win_read_one_key()` Windows 专用 | ✅ 正确隔离 |
-| `tty_app.py` | `SIGWINCH` 仅 Unix | ✅ 正确判断 |
-| `background_tasks.py` | `_is_process_alive()` Windows ctypes / Unix kill(0) | ✅ 正确 |
-| `mcp.py` | `CREATE_NO_WINDOW` 仅 Windows | ✅ 正确 |
-| `mcp.py` | `close()` Windows taskkill / Unix SIGTERM+SIGKILL | ✅ 正确 |
-| `tools/run_command.py` | `split_command_line()` posix=True/False | ✅ 正确 |
-| `tools/run_command.py` | `_build_execution_command()` cmd/bash 分支 | ✅ 正确(但见问题 3) |
-| `tools/run_command.py` | background process isolation flags | ✅ 正确 |
-| `install.py` | 三平台 launcher script | ✅ 正确 |
-| `install.py` | PATH 添加指引 (zshrc/bashrc/sysdm) | ✅ 正确 |
-| `config.py` | `Path.home()` 跨平台 | ✅ 正确 |
-| `workspace.py` | `Path.resolve()` 跨平台 | ✅ 正确 |
-| `tui/input_parser.py` | 纯 ANSI 解析,平台无关 | ✅ 正确 |
-
----
-
-## 💡 增强建议
-
-### 建议 1: 添加 `TERM` 环境变量检测
-
-在 `enter_alternate_screen()` 之前检测 `$TERM`。某些终端(如 `dumb`、`linux` console)不支持 alternate screen 或鼠标追踪,强制启用会导致乱码:
-
-```python
-def _term_supports_alt_screen() -> bool:
- term = os.environ.get("TERM", "")
- return term not in ("dumb", "linux", "")
-```
-
-### 建议 2: macOS 上 Homebrew Python 路径处理
-
-`install.py:60` 中 `sys.executable` 在 macOS Homebrew 安装的 Python 下可能返回 symlink 路径如 `/opt/homebrew/bin/python3`。这没有错,但如果用户通过 pyenv / asdf 管理 Python 版本,`sys.executable` 可能指向 shim 而非真实路径。建议在 launcher script 中使用 `$(command -v python3)` 而非硬编码路径。
-
----
-
-## 修复优先级
-
-| 优先级 | 项目 | 影响 |
-|---|---|---|
-| **P0** | Bug 2: raw mode 禁用 OPOST → 输出阶梯式 | Linux/macOS 上完全无法正常使用 |
-| **P0** | Bug 1 & 3: stdin.read(1) 替换为 os.read() | 多字节输入可能卡死 |
-| **P1** | 问题 3: bash → $SHELL or /bin/sh | macOS 用户环境变量缺失 |
-| **P2** | 问题 2: terminal size (0,0) 检测 | 边缘 case |
-| **P2** | 问题 4: MCP 允许路径扩展 | 安全策略松紧度 |
-| **P3** | 问题 1: SIGWINCH 线程安全 | 极端 case |
-| **P3** | 建议 1 & 2 | 体验优化 |
diff --git a/PROGRESS_REPORT.md b/PROGRESS_REPORT.md
deleted file mode 100644
index 1a3e54a..0000000
--- a/PROGRESS_REPORT.md
+++ /dev/null
@@ -1,270 +0,0 @@
-# MiniCode Python - 进度报告与差距分析
-
-> 生成时间: 2026-04-05
-> 最后更新: 2026-04-05 (会话持久化与 TUI 完整实现)
-> 参照: [MiniCode TS 主仓库](https://github.com/LiuMengxuan04/MiniCode)
-
----
-
-## 一、整体评估
-
-**Python 版已完成约 95% 的功能迁移**,核心逻辑(Agent Loop、工具系统、权限管理、MCP、Skills、配置)已经全部到位并且可以工作。**新增会话持久化与恢复功能**,现在支持跨重启保存和恢复对话。剩余 5% 主要集中在安装器和一些边缘优化。
-
-| 维度 | 完成度 | 说明 |
-|------|--------|------|
-| Agent Loop | **100%** | 完整实现,包含 `shouldTreatAssistantAsProgress` 启发式和进度续推 |
-| 工具系统 | **100%** | 10 个工具 1:1 对齐 |
-| 权限管理 | **100%** | 完整实现,包含 `git restore --source`/`bun` 检测,完整 `choices` |
-| MCP | **100%** | 功能完整,包含 `content-length` 协议支持和 ENOENT 错误提示 |
-| Skills | **100%** | 完整对齐 |
-| 配置系统 | **100%** | 完整对齐 |
-| TUI 渲染 | **95%** | 完整实现全屏渲染、Unicode 边框、CJK 支持、Markdown 渲染 |
-| 终端交互 | **95%** | Raw-mode 事件驱动,ANSI 解析,光标控制,历史导航 |
-| 会话持久化 | **100%** | ✨ **新增** - 自动保存、恢复、CLI 选项 |
-| 安装器 | **0%** | TS 有 `install.ts`,Python 完全没有 |
-
----
-
-## 二、模块级对照表
-
-### 2.1 已完成(基本对齐)
-
-| TS 模块 | PY 模块 | 状态 |
-|---------|---------|------|
-| `agent-loop.ts` (278行) | `agent_loop.py` (176行) | ✅ 核心逻辑完整 |
-| `anthropic-adapter.ts` (340行) | `anthropic_adapter.py` (233行) | ✅ 完整 |
-| `tool.ts` (100行) | `tooling.py` (86行) | ✅ 完整 |
-| `permissions.ts` (510行) | `permissions.py` (262行) | ✅ 主要逻辑完整 |
-| `mcp.ts` (860行) | `mcp.py` (472行) | ✅ 核心功能完整 |
-| `skills.ts` (225行) | `skills.py` (140行) | ✅ 完整 |
-| `config.ts` (230行) | `config.py` (142行) | ✅ 完整 |
-| `prompt.ts` (100行) | `prompt.py` | ✅ 完整 |
-| `history.ts` (25行) | `history.py` | ✅ 完整 |
-| `workspace.ts` (30行) | `workspace.py` (16行) | ✅ 完整 |
-| `file-review.ts` (80行) | `file_review.py` (48行) | ✅ 完整 |
-| `mock-model.ts` (125行) | `mock_model.py` (125行) | ✅ 完整 |
-| `background-tasks.ts` (80行) | `background_tasks.py` | ✅ 完整 |
-| `cli-commands.ts` (220行) | `cli_commands.py` | ✅ 完整 |
-| `local-tool-shortcuts.ts` | `local_tool_shortcuts.py` | ✅ 完整 |
-| 全部 10 个 tools | 全部 10 个 tools | ✅ 1:1 对齐 |
-| **✨ 新增** `session.ts` | `session.py` (356行) | ✅ **会话持久化与恢复** |
-
-### 2.2 有差距的模块
-
-| TS 模块 | PY 模块 | 差距 |
-|---------|---------|------|
-| `tty-app.ts` (1365行) | `tty_app.py` (1453行) | ✅ 已完整实现 |
-| `tui/chrome.ts` (639行) | `tui/chrome.py` | ✅ 已完整实现 |
-| `tui/transcript.ts` (134行) | `tui/transcript.py` (130行) | ✅ 已完整实现 |
-| `tui/input.ts` (20行) | `tui/input.py` | ✅ 已完整实现 |
-| `tui/input-parser.ts` (263行) | `tui/input_parser.py` | ✅ 已完整实现 |
-| `tui/markdown.ts` (64行) | `tui/markdown.py` | ✅ 已完整实现 |
-
-### 2.3 完全缺失的模块
-
-| TS 模块 | 说明 | 重要性 |
-|---------|------|--------|
-| `install.ts` (128行) | 安装向导 | 🟢 可后补 |
-| `ui.ts` (22行) | UI 聚合导出 | 🟢 Python 用 `__init__.py` 替代 |
-
----
-
-## 三、关键差距详细分析
-
-### 3.1 🔴 终端交互模型(最大差距)
-
-**TS 实现**:
-- Raw-mode 事件驱动架构
-- `parseInputChunk()` 解析所有 ANSI 转义序列(方向键、PageUp/Down、Ctrl 组合键、鼠标滚轮)
-- 实时按键响应,字符级输入编辑
-- 光标定位、左右移动、Home/End
-- 历史导航 Ctrl-P/N
-- Tab 补全 slash commands
-- Escape 清空输入
-- Ctrl-U 清行、Ctrl-A/E 行首/行尾
-
-**PY 实现**:
-- 阻塞式 `input("minicode> ")`
-- 无实时按键处理
-- 无光标控制
-- 无历史导航(虽然有 history 模块但 input() 不支持)
-- 无 Tab 补全
-
-**影响**:这是"像不像 Claude Code"的决定性因素。
-
-### 3.2 🔴 全屏 TUI 渲染
-
-**TS 实现**:
-- `renderScreen()` 每次按键后重绘整个终端
-- 计算终端行数/列数,精确布局
-- 区域划分:Banner → Transcript → Tool Panel → Input → Footer
-- 支持滚动偏移(transcript scrolling)
-- Permission 审批弹窗覆盖整个屏幕
-
-**PY 实现**:
-- "打印式" UI,只在关键时刻打印内容
-- 无全屏重绘
-- 无精确布局计算
-- 无 transcript 滚动(hardcoded offset=0)
-
-### 3.3 🟡 Chrome 渲染差距
-
-| 功能 | TS | PY |
-|------|----|----|
-| 边框字符 | `╭─╮╰─╯│` Unicode box-drawing | `+--+` ASCII |
-| CJK/Emoji 宽度 | `charDisplayWidth()` 正确计算 | `len()` 导致对齐错位 |
-| 文本换行 | `wrapPanelBodyLine()` 自动换行 | 仅截断 `_truncate()` |
-| 路径中间截断 | `truncatePathMiddle()` | 无 |
-| 彩色 badge | `colorBadge()` | 无 |
-| Diff 着色 | `colorizeUnifiedDiffBlock()` 带词级高亮 | 无 |
-| Permission 详情滚动 | 支持 PageUp/Down | 无 |
-
-### 3.4 🟡 Transcript 差距
-
-| 功能 | TS | PY |
-|------|----|----|
-| Markdown 渲染 | `renderMarkdownish()` 着色标题、代码块、表格、粗体 | 原始文本输出 |
-| 工具输出预览 | `previewToolBody()` 按 tool 类型截断 | 无(可能输出爆屏) |
-| 窗口大小 | `getTranscriptWindowSize()` 基于终端行数 | 固定 12 行 |
-| 滚动指示器 | 显示 "scroll offset: N" | 无 |
-| 折叠动画 | `collapsePhase` 1→2→3 有视觉反馈 | 有字段但无动画逻辑 |
-
-### 3.5 🟡 Agent Loop 差距
-
-| 功能 | TS | PY |
-|------|----|----|
-| `shouldTreatAssistantAsProgress` | 有启发式判断 | ❌ 缺失 |
-| Progress 续推 | 有 continuation prompt | ❌ 缺失 |
-| 异步执行 | `async/await` | 同步阻塞 |
-
-### 3.6 ⚠️ 权限系统差距
-
-| 功能 | TS | PY |
-|------|----|----|
-| `PermissionChoice` 数组 | 定义 key 1-7 | `choices: []` 空数组 |
-| `git restore --source` | 有检测 | 缺失 |
-| `bun` 命令 | 有检测 | 缺失 |
-| 交互式审批 UI | 全屏覆盖,支持滚动、展开、反馈输入 | 简单 `input()` 提示 |
-
----
-
-## 四、优先级排序的 TODO
-
-### P0 - 必须做(让它"真正可用")
-
-1. **[ ] ANSI Input Parser** (`tui/input_parser.py`)
- - 移植 `input-parser.ts` 的完整逻辑
- - 支持方向键、PageUp/Down、Ctrl 组合键、鼠标滚轮
- - 约 260 行代码
-
-2. **[ ] Raw-mode TTY Event Loop** (`tty_app.py` 重写)
- - 替换 `input()` 为 raw-mode stdin 读取
- - Windows: `msvcrt.getwch()` / `msvcrt.kbhit()`
- - Unix: `tty.setraw()` + `termios`
- - 实现事件驱动的 `handleEvent()` 循环
- - 实现 `renderScreen()` 全屏重绘
-
-3. **[ ] 全屏 renderScreen** (`tty_app.py`)
- - 实现区域划分和精确布局
- - Banner + Transcript + Tool Panel + Input + Footer
- - 支持终端尺寸检测 `os.get_terminal_size()`
-
-### P1 - 重要(让它"像 Claude Code")
-
-4. **[ ] Markdown → ANSI 渲染器** (`tui/markdown.py`)
- - 移植 `renderMarkdownish()`
- - 标题着色、代码块 dim、表格格式化、粗体、行内代码
- - 约 64 行代码
-
-5. **[ ] Chrome 升级** (`tui/chrome.py`)
- - Unicode box-drawing 边框
- - `charDisplayWidth()` 支持 CJK/Emoji
- - `wrapPanelBodyLine()` 自动换行
- - `truncatePathMiddle()` 路径截断
- - `colorBadge()` 彩色标签
- - Diff 着色 + 词级高亮
-
-6. **[ ] Transcript 升级** (`tui/transcript.py`)
- - `previewToolBody()` 工具输出预览截断
- - 动态 window size
- - 滚动指示器
- - 集成 Markdown 渲染
-
-7. **[ ] Input Prompt 升级** (`tui/input.py`)
- - 光标渲染(反色当前字符)
- - 提示文本和快捷键说明
- - 与 `renderScreen()` 集成
-
-8. **[ ] Permission 交互式 UI**
- - 全屏审批弹窗
- - 详情展开/滚动
- - 选择项导航(数字键 1-7)
- - 反馈输入模式
- - Diff 着色预览
-
-### P2 - 完善(补齐细节)
-
-9. **[ ] Agent Loop 补全**
- - `shouldTreatAssistantAsProgress()` 启发式
- - Progress continuation prompts
-
-10. **[ ] 权限系统补全**
- - `PermissionChoice` 完整定义
- - `git restore --source` / `bun` 检测
- - 与交互式 UI 联动
-
-11. **[ ] MCP 补全**
- - `content-length` 协议支持
- - ENOENT 错误处理和安装提示
-
-12. **[ ] 安装器** (`install.py`)
- - 交互式配置向导
- - API key 配置
- - 启动脚本生成
-
-13. **[ ] Transcript 滚动和历史导航**
- - PageUp/Down 滚动 transcript
- - Ctrl-P/N 历史导航
- - Tab 补全 slash commands
-
----
-
-## 五、工作量估计
-
-| 优先级 | 预计代码量 | 预计工时 |
-|--------|-----------|---------|
-| P0 (必须) | ~800 行新代码 + ~400 行重写 | 8-12 小时 |
-| P1 (重要) | ~600 行新代码 + ~200 行修改 | 6-8 小时 |
-| P2 (完善) | ~300 行新代码 + ~100 行修改 | 3-4 小时 |
-| **总计** | **~2400 行** | **17-24 小时** |
-
----
-
-## 六、已有代码质量评估
-
-Python 版现有代码质量较高:
-- ✅ 类型注解完整(`from __future__ import annotations`)
-- ✅ dataclass 使用得当
-- ✅ 模块划分清晰
-- ✅ 错误处理合理
-- ✅ 测试覆盖良好(13 个测试文件)
-- ✅ 无外部依赖(纯标准库实现)
-- ⚠️ 同步模型(TS 是 async)— 对于 CLI 工具可以接受
-
----
-
-## 七、建议执行顺序
-
-```
-第 1 轮: input_parser.py + raw-mode event loop + renderScreen() 骨架
- → 让终端交互从 input() 变成 event-driven
-
-第 2 轮: markdown.py + chrome.py 升级 + transcript.py 升级
- → 让渲染输出好看
-
-第 3 轮: permission UI + input prompt 升级
- → 让审批和输入体验完整
-
-第 4 轮: agent loop 补全 + MCP 补全 + install.py
- → 补齐最后的功能差距
-```
diff --git a/README.md b/README.md
index 320768f..46f07b8 100644
--- a/README.md
+++ b/README.md
@@ -1,286 +1,165 @@
-# MiniCode Python — Cybernetic Agent Memory
+# MiniCode
-> **Closed-Loop Cybernetic Memory for LLM Agents**
+> **The coding agent that regulates itself.**
>
-> 钱学森工程控制论 × 记忆检索优化 × DDD 领域驱动
->
-> []()
-> []()
-
----
-
-## 核心贡献
+> 15 cybernetic controllers watch your agent in real time —
+> auto-fixing context overflow, tool errors, cost spikes, and irrelevant memory.
+> No other coding agent does this.
-传统 Agent 记忆系统使用**静态检索**(固定 top-K BM25 或向量相似度)。我们首次将**工程控制论**(PID 闭环 + Kalman 滤波 + Lyapunov 稳定性)形式化地应用于 Agent 记忆管理,实现了一个**自适应、可证明稳定、具备多层语义的检索管线**。
-
-| 指标 | 纯 BM25 | 我们的完整管线 | 提升 |
-|------|---------|--------------|------|
-| P@3 | 0.350 | **0.717** | **2.05×** |
-| R@5 | 0.362 | **0.704** | **1.94×** |
-| MRR | 0.713 | **1.000** | **+40%** |
-| 跨域噪音 | 65.0% | **6.7%** | **-58.3%** |
-
-> 消融实验:80 条记忆 × 20 条查询 × 5 领域(frontend/backend/database/devops/testing)
+[]()
---
-## 理论框架
-
-### 记忆价值函数
-
-$$V(m, t, c) = \text{relevance}(m, t) \times \text{freshness}(m) \times \text{utility}(m, c)$$
+## Why MiniCode
-| 分量 | 定义 | 实现 |
-|------|------|------|
-| relevance(m,t) | BM25 评分 + 领域 Jaccard 软混合 | `final_score = bm25 × 0.7 + domain_jaccard × 0.3` |
-| freshness(m) | exp(-age_days / 30) | 指数衰减,τ = 30 天 |
-| utility(m,c) | 1 + α·ln(1 + usage_count) | 使用次数的对数边际收益 |
+Every AI coding agent hits the same problems: context fills up, tools fail, costs spiral, memory is noise. The industry answer is "better prompts" or "bigger models." We took a different path.
-### PID 稳定性 —— Lyapunov 证明
+MiniCode wraps the LLM in a **closed-loop cybernetic control system** — PID controllers, Kalman filters, feedback loops — that watches the agent in real time and auto-corrects before you even notice.
-考虑上下文 PID 控制器:e(t) = usage(t) - 0.70(设定点)
-
-构造 Lyapunov 函数:VL(e, ∫e) = ½e² + (ki/2)(∫e)²
-
-则 V̇L = -(kp/m)·e² < 0(当 kp > 0),系统**渐近稳定**:e(t) → 0 as t → ∞。
-
-### 自适应冷却
-
-$$\tau_{\text{cool}}(c) = \tau_{\text{base}} \times (1 - \text{context\_pressure})$$
+```
+Your prompt → Agent Loop → Response
+ │
+ ┌────────────┼────────────┐
+ │ │ │
+ SENSE CONTROL ACT
+ Kalman×5 PID ×4 tools
+ metrics feedback budget
+```
-上下文压力高 → 冷却短 → 注入更积极。钳位在 [5s, 120s]。
+**It's like ABS for your AI agent.**
-### 扩散激活
+| Problem | Traditional Fix | MiniCode |
+|---------|----------------|----------|
+| Context overflow | Retry with bigger window | PID auto-compacts |
+| Tool errors pile up | Restart the session | Self-heals in real time |
+| Cost runs away | Manual budget check | Budget PID throttles |
+| Memory returns noise | Skip memory entirely | Domain filter + LLM curation |
-$$a_j = \sum_i a_i \times 0.5 \times \text{Jaccard}(m_i, m_j)$$
+---
-通过 `related_to` 图传播,depth=1。实现 Hebb 式联想记忆。
+## What It Can Do
-### 信息保持界
+Verified with DeepSeek V4 Pro. **10 real coding tasks, zero errors.**
-跨层级记忆压缩:I(m_arch) ≈ I(m) - ε,其中 ε = -log₂(len(original)/len(summarized))
+```
+Create hello.py with hello() 33s ✓
+Find all files with "cybernetic" 25s ✓
+Read + summarize README 15s ✓
+Edit: rename function + change val 39s ✓
+Multi-step: grep → read → analyze 68s ✓
+```
+Full results: [`docs/test_results.md`](docs/test_results.md)
---
-## 系统架构
+## Quick Start
+```bash
+git clone https://github.com/QUSETIONS/MiniCode-Python.git
+cd MiniCode-Python
+pip install -e .
+python -m minicode.main
```
- ┌──────────────────────────────┐
- │ CyberneticOrchestrator │
- │ (15+ controllers) │
- └──────────┬───────────────────┘
- │
- ┌──────────────────────────┼──────────────────────────┐
- │ │ │
- ┌────▼─────┐ ┌──────▼──────┐ ┌───────▼──────┐
- │ PID ×4 │ │ Kalman ×5 │ │ Feedforward │
- │ context │ │ state │ │ predictive │
- │ cost │ │ observer │ │ decoupling │
- │ feedback │ │ │ │ │
- │ adaptive │ │ │ │ │
- └──────────┘ └─────────────┘ └──────────────┘
- │
- ┌──────────▼───────────┐
- │ MemoryPipeline │
- │ (unified facade) │
- └──────────┬───────────┘
- │
- ┌─────────────────────┼─────────────────────┐
- │ │ │
- ┌─────────▼────────┐ ┌────────▼────────┐ ┌─────────▼────────┐
- │ READ │ │ WRITE │ │ MAINTAIN │
- │ Domain→BM25 │ │ ReflectionEngine│ │ CuratorAgent │
- │ +Vector(RRF) │ │ →TaskContext │ │ consolidate │
- │ →Reranker→Inject │ │ →MemoryManager │ │ validate/promote │
- └──────────────────┘ └─────────────────┘ └──────────────────┘
-```
-
-### 记忆检索管线(3 层)
+No API key? Mock mode works out of the box:
+```bash
+MINI_CODE_MODEL_MODE=mock python -m minicode.main
```
-Task + Files
- │
- ▼
-Layer 1 ─ 语义理解
- DomainClassifier (9 领域, 60+ 文件后缀映射)
- BM25 + Domain Weight (final = bm25×0.7 + jaccard×0.3)
- Query Reformulation (低分时自动改写)
- Vector Search + RRF Fusion (可选)
- Memory Value Scoring (V = rel × fresh × util)
- │
- ▼
-Layer 2 ─ 策展精选
- LLM Reranker (Haiku-level, LRU cached, 60s TTL)
- top-15 → curated top-3
- 矛盾检测 + 上下文摘要
- │
- ▼
-Layer 3 ─ 联想注入
- Spreading Activation (related_to graph, depth=1)
- Adaptive Cooldown (context-pressure aware)
- PID-controlled injection rate
- │
- ▼
-System Prompt
-```
-
-### 多层存储架构
-
-| 层级 | 保留期 | 压缩 | 晋升规则 |
-|------|--------|------|---------|
-| WORKING | 当前会话 | 无 | 访问时自动 |
-| SHORT_TERM | < 7 天 | 无 | usage ≥ 5 ∧ age > 7d |
-| LONG_TERM | < 30 天 | 无 | — |
-| ARCHIVAL | 永久 | 首句摘要 | age > 30d 未访问 |
---
-## Memory Pipeline API
-
-**设计原则:一个类,四个方法,完整生命周期。**
+## Configuration
-```python
-from minicode.memory_pipeline import MemoryPipeline
+```json
+{
+ "model": "your-model",
+ "env": {
+ "ANTHROPIC_BASE_URL": "https://your-endpoint",
+ "ANTHROPIC_AUTH_TOKEN": "your-token"
+ }
+}
+```
-pipeline = MemoryPipeline(memory_manager)
-pipeline.initialize(model_adapter, enable_vector=True)
+---
-# 任务开始 —— 检索 + 注入
-memories = pipeline.read("Add login form", ["src/Login.tsx"])
-messages = pipeline.inject("Add login form", ["src/Login.tsx"], messages)
+## The 15 Controllers
+
+Every turn, MiniCode's controllers measure, decide, and act:
+
+| Controller | Job |
+|-----------|-----|
+| **ContextPIDController** | Usage → compaction strength |
+| **BudgetPIDController** | Spending → token budget |
+| **FeedbackController** | System health → 13-dim control signal |
+| **AdaptivePIDTuner** | Auto-tunes PID gains every 20 turns |
+| **StateObserver** | Kalman estimates of 5 hidden states |
+| **SelfHealingEngine** | Detects and recovers 8 fault types |
+| **FeedforwardController** | Pre-configures from task intent |
+| **PredictiveController** | Forecasts and acts before problems hit |
+| **DecouplingController** | Untangles multi-variable interactions |
+| **StabilityMonitor** | Multi-dimensional health scoring |
+| **ProgressController** | Detects task stalling |
+| **DomainClassifier** | Auto-detects frontend/backend/db/devops |
+| **MemoryInjectionController** | PID-controls memory injection rate |
+| **ModelSelectionController** | Risk/cost-driven model selection |
+| **CyberneticSupervisor** | Aggregates all controller states |
-# 任务结束 —— 持久化 + 反馈
-pipeline.write("Add login form", execution_trace)
-pipeline.feedback(success=True, injected_memory_ids=[...])
+---
-# 后台维护 —— 每 ~10 个任务
-report = pipeline.maintain()
-```
+## Memory That Actually Works
-### 消融实验 —— 逐组件贡献
+Not keyword search. A full adaptive pipeline:
```
-Config P@3 R@5 MRR Noise
-────────────────────────────────────────────────────────────
-C0: BM25 (baseline) 0.350 0.362 0.713 65.0%
-C1: + Domain Weight 0.383 0.446 0.844 42.0%
-C2: + Query Expansion 0.450 0.496 0.858 38.0%
-C3: + Reranker (Full) 0.717 0.704 1.000 6.7%
+Task → DomainClassifier → BM25 + Vector(RRF) → Value Scoring
+ → LLM Reranker (curates top-3 from 15) → Spreading Activation → Inject
```
-**结论**:Reranker 贡献 73% 的精度提升(+0.267 P@3)。Domain + Expansion 在零 LLM 成本下削减 27% 噪音。完整管线精度 2.05× 基准。
-
----
+**80 memories × 20 queries: P@3 0.35 → 0.72, noise 65% → 7%.**
-## 控制论控制器矩阵
-
-| 控制器 | 类型 | 作用 |
-|--------|------|------|
-| ContextPIDController | PID | 上下文压力 → 压缩强度 |
-| CostControlLoop (BudgetPID) | PID | 成本速率 → 预算乘数 |
-| FeedbackController (双 PID) | PID ×2 | 系统状态 → 13 维 ControlSignal |
-| AdaptivePIDTuner | 自适应 | 每 20 轮自动调参 |
-| StateObserver | Kalman ×5 | 隐藏状态估计(负载/错误/压力/掌握度/退化) |
-| FeedforwardController | 前馈 | Intent → 预配置 |
-| PredictiveController | 预测 | 时序预测 → 主动动作 |
-| DecouplingController | 解耦 | 多变量 RGA 耦合分析 |
-| SelfHealingEngine | 自愈 | 8 种故障类型的自动恢复 |
-| StabilityMonitor | 监测 | 6 维健康评分 + 异常检测 |
-| CyberneticSupervisor | 监督 | 全局风险聚合 |
-| ProgressController | 进度 | 停滞检测 + 策略建议 |
-| MemoryInjectionController | 记忆 | PID 控制注入模式 |
-| ModelSelectionController | 模型 | 风险/成本自适应选模 |
-| DomainClassifier | 分类 | 9 领域 60+ 后缀自动推导 |
+The LLM Reranker uses the same model you're coding with to pick which memories actually matter.
---
-## 目录结构
+## Terminal Polish
-```
-minicode/
-├── memory.py # 核心:BM25, MemoryTier, MemoryEntry, 索引
-├── memory_pipeline.py # 统一管线:read/write/inject/maintain
-├── memory_reranker.py # LLM 策展:top-15 → top-3 + 摘要
-├── memory_curator_agent.py # 后台策展:合并/校验/晋升/关联
-├── memory_injector.py # PID 控制的记忆注入
-├── domain_classifier.py # 领域分类:60+ 后缀映射
-├── vector_memory.py # 向量检索(可选)
-├── agent_reflection.py # 自省引擎 → TaskContext
-├── cybernetic_orchestrator.py # 15+ 控制器外观
-├── feedback_controller.py # 双 PID 外环 + ControlSignal
-├── context_cybernetics.py # 7 层上下文控制论
-├── cost_control.py # 预算 PID
-├── self_healing_engine.py # 8 种故障自愈
-├── agent_loop.py # Agent 主循环
-└── ...
-
-tests/
-├── test_domain_memory.py # 领域分类 + 查询扩展
-├── test_memory_reranker.py # Reranker 全场景
-├── test_memory_curator.py # Curator 全场景
-├── test_feedback_controller.py
-├── test_feedforward_controller.py
-├── test_cybernetics_concurrency.py # 并发压测
-├── test_cybernetics_e2e.py # E2E 控制链
-└── ...
-
-docs/
-└── memory_theory.md # 形式化理论:V(m,t,c) + Lyapunov + 信息保持
-
-py-src/scripts/
-├── ablation_study.py # 消融实验(LaTeX 表格输出)
-├── benchmark_memory.py # 全量 benchmark
-└── demo_memory_reranker.py # 效果对比 demo
-```
+| Feature | Key |
+|---------|-----|
+| Colored diffs | `edit_file` output: +green/-red with word highlights |
+| Multi-line input | `Ctrl+J` — paste code blocks directly |
+| Word editing | `Ctrl+←→` `Ctrl+W` `Ctrl+K` |
+| Visual scrollbar | █ • ▲ ▼ |
+| Bracketed paste | Batch insert, strip control chars |
+| Spinner | `⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏` at 8fps |
+| Focus tracking | Auto-refresh on tab switch |
+| Fuzzy complete | `/mem` matches `/memory` |
---
-## 快速开始
+## Testing
```bash
-git clone https://github.com/QUSETIONS/MiniCode-Python.git
-cd MiniCode-Python
-
-# 安装
-pip install -e .
-
-# 运行
-python -m minicode.main
-
-# 测试
-pytest # 718 passed, 2 skipped
-
-# Mock 模式(无需 API key)
-MINI_CODE_MODEL_MODE=mock python -m minicode.main
+pytest
+# 737 passed, 2 skipped
```
-## 配置
+---
-`~/.mini-code/settings.json`:
-```json
-{
- "model": "claude-sonnet-4-20250514",
- "env": {
- "ANTHROPIC_AUTH_TOKEN": "your-token"
- }
-}
-```
+## Theory
----
+The control loop isn't heuristic — it's mathematically grounded:
-## MiniCode 生态
+| Concept | Formalization |
+|---------|--------------|
+| PID Stability | V̇ = -(kp/m)·e² < 0 (Lyapunov) |
+| Memory Value | V(m,t,c) = relevance × freshness × utility |
+| State Estimation | 5 Kalman filters, minimum-variance unbiased |
+| Retrieval Fusion | RRF: BM25 + SparseVector cosine |
-| 仓库 | 角色 |
-|------|------|
-| [MiniCode](https://github.com/LiuMengxuan04/MiniCode) | 主项目入口 |
-| [MiniCode-Python](https://github.com/QUSETIONS/MiniCode-Python) | Python 实现(本仓库) |
-| [MiniCode-rs](https://github.com/harkerhand/MiniCode-rs) | Rust 实现 |
+[`docs/memory_theory.md`](docs/memory_theory.md)
---
-## 致谢
+## Acknowledgments
-- 钱学森《工程控制论》(Engineering Cybernetics, 1954)
-- Wiener, N. *Cybernetics: or Control and Communication in the Animal and the Machine* (1948)
-- Mem0 / Letta (MemGPT) / True Memory 等记忆系统的开创性工作
-- SCL (Structured Cognitive Loop) R-CCAM 架构
+钱学森《工程控制论》(1954) · Wiener *Cybernetics* (1948) · Mem0 / Letta / True Memory
diff --git a/ROBUSTNESS_OPTIMIZATION_REPORT.md b/ROBUSTNESS_OPTIMIZATION_REPORT.md
deleted file mode 100644
index b5e9b1b..0000000
--- a/ROBUSTNESS_OPTIMIZATION_REPORT.md
+++ /dev/null
@@ -1,488 +0,0 @@
-# MiniCode 代码健壮性优化报告
-
-## 修复概览
-
-本次深度检查 focused on 错误处理、资源管理、并发安全和边界条件,发现了 **10 个关键健壮性问题** 并全部修复。
-
----
-
-## 修复详情
-
-### ✅ 1. 修复 Python mcp.py 异常时未清理已连接客户端
-**文件**: `py-src/minicode/mcp.py`
-**风险等级**: 🔴 严重
-**问题类别**: 资源泄漏
-
-**问题描述**:
-`create_mcp_backed_tools()` 函数在循环中创建多个 MCP 客户端。如果第 N 个服务器启动失败抛出异常,之前已成功连接的 N-1 个客户端不会被清理,导致子进程和文件描述符泄漏。
-
-**修复内容**:
-```python
-try:
- for server_name, config in mcp_servers.items():
- # ... 创建客户端 ...
-except Exception:
- # 清理所有已连接的客户端,防止资源泄漏
- for client in clients:
- try:
- client.close()
- except Exception:
- pass
- raise
-```
-
-**验证**: ✅ Python 测试通过(91/92)
-
----
-
-### ✅ 2. 修复 TypeScript mcp.ts 异常时未清理已连接客户端
-**文件**: `ts-src/src/mcp.ts`
-**风险等级**: 🔴 严重
-**问题类别**: 资源泄漏
-
-**问题描述**:
-与 Python 版本相同的问题。`dispose()` 函数调用 `client.close()` 但没有捕获异常,如果某个客户端关闭失败会中断整个清理流程。
-
-**修复内容**:
-```typescript
-async dispose() {
- await Promise.all(clients.map(async client => {
- try {
- await client.close()
- } catch {
- // 忽略清理错误
- }
- }))
-}
-```
-
-**验证**: ✅ TypeScript 类型检查通过
-
----
-
-### ✅ 3. 修复 Python agent_loop.py model.next() 无异常保护
-**文件**: `py-src/minicode/agent_loop.py`
-**风险等级**: 🟡 中等
-**问题类别**: 异常处理
-
-**问题描述**:
-`model.next(current_messages)` 调用没有 try-catch。如果模型 API 抛出异常(网络错误、API 限流、认证失败等),整个 agent 循环会崩溃,用户收到的是堆栈跟踪而非友好错误消息。
-
-**修复内容**:
-```python
-while max_steps is None or step < max_steps:
- step += 1
- try:
- next_step = model.next(current_messages)
- except Exception as error:
- fallback = f"Model API error: {error}"
- if on_assistant_message:
- on_assistant_message(fallback)
- current_messages.append({"role": "assistant", "content": fallback})
- return current_messages
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 4. 修复 Python permissions.py JSON 解析异常
-**文件**: `py-src/minicode/permissions.py`
-**风险等级**: 🟡 中等
-**问题类别**: 边界条件
-
-**问题描述**:
-`_read_permission_store()` 直接调用 `json.loads()`,如果权限文件包含无效 JSON(如断电导致的部分写入),会抛出未处理的 `json.JSONDecodeError`。
-
-**修复内容**:
-```python
-def _read_permission_store() -> dict[str, Any]:
- if not MINI_CODE_PERMISSIONS_PATH.exists():
- return {}
- try:
- data = json.loads(MINI_CODE_PERMISSIONS_PATH.read_text(encoding="utf-8"))
- if not isinstance(data, dict):
- return {}
- return data
- except (json.JSONDecodeError, OSError) as e:
- # 损坏的文件 — 返回空存储并记录警告
- import warnings
- warnings.warn(f"Corrupted permissions file, resetting: {e}")
- return {}
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 5. 修复 TypeScript permissions.ts JSON 解析异常
-**文件**: `ts-src/src/permissions.ts`
-**风险等级**: 🟡 中等
-**问题类别**: 边界条件
-
-**问题描述**:
-与 Python 版本相同的问题。`JSON.parse()` 在文件损坏时抛出 SyntaxError。
-
-**修复内容**:
-```typescript
-async function readPermissionStore(): Promise {
- try {
- const content = await readFile(PERMISSIONS_PATH, 'utf8')
- const parsed = JSON.parse(content)
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
- return parsed as PermissionStore
- }
- return {}
- } catch (error) {
- // ... ENOENT 检查 ...
-
- // JSON 解析错误也返回空存储
- if (error instanceof SyntaxError) {
- return {}
- }
-
- throw error
- }
-}
-```
-
-**验证**: ✅ TypeScript 类型检查通过
-
----
-
-### ✅ 6. 修复 Python run_command.py child.pid 可能为 None
-**文件**: `py-src/minicode/tools/run_command.py`
-**风险等级**: 🟡 中等
-**问题类别**: 边界条件
-
-**问题描述**:
-`child.pid` 在进程立即退出时可能为 `None`。直接传递给 `register_background_shell_task()` 会导致后续无法跟踪或清理进程。
-
-**修复内容**:
-```python
-if child.pid is None:
- return ToolResult(
- ok=False,
- output="Failed to get PID for background command. Process may have exited immediately.",
- )
-
-background_task = register_background_shell_task(
- command=_strip_trailing_background_operator(input_data["command"]),
- pid=child.pid,
- cwd=effective_cwd,
-)
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 7. 修复 TypeScript run-command.ts execFile 无超时
-**文件**: `ts-src/src/tools/run-command.ts`
-**风险等级**: 🟡 中等
-**问题类别**: 资源管理
-
-**问题描述**:
-`execFileAsync` 默认没有超时限制。如果命令挂起(如 `ping localhost`、交互式命令等待输入),会永远阻塞 agent 循环。
-
-**修复内容**:
-```typescript
-const result = await execFileAsync(command, args, {
- cwd: effectiveCwd,
- maxBuffer: 10 * 1024 * 1024, // 10MB
- env: process.env,
- timeout: 300_000, // 5 分钟超时
- killSignal: 'SIGTERM',
-})
-```
-
-**验证**: ✅ TypeScript 类型检查通过
-
----
-
-### ✅ 8. 修复 TypeScript run-command.ts catch 丢失错误类型
-**文件**: `ts-src/src/tools/run-command.ts`
-**风险等级**: 🟡 中等
-**问题类别**: 异常处理
-
-**问题描述**:
-只返回 `error.message` 丢失了错误类型信息。用户无法区分"命令未找到"、"权限不足"、"超时"等不同场景。
-
-**修复内容**:
-```typescript
-} catch (error: unknown) {
- // 处理缓冲区溢出错误
- if (error && typeof error === 'object' && 'code' in error && error.code === 'ERR_CHILD_PROCESS_MAX_BUFFER_EXCEEDED') {
- return {
- ok: false,
- output: `Command output exceeded the 10MB limit. Try redirecting output to a file.`,
- }
- }
- // 处理命令未找到
- if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') {
- return {
- ok: false,
- output: `Command not found: ${normalized.command}. Install it first.`,
- }
- }
- // 处理超时或被杀死
- if (error && typeof error === 'object' && 'code' in error && (error.code === 'ETIMEDOUT' || error.code === 'ESRCH')) {
- return {
- ok: false,
- output: `Command timed out or was killed.`,
- }
- }
- // 其他错误,保留错误类型信息
- const message = error instanceof Error ? error.message : String(error)
- const code = error && typeof error === 'object' && 'code' in error ? (error as any).code : undefined
- return {
- ok: false,
- output: code ? `[${code}] ${message}` : message,
- }
-}
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 9. 优化 Python mcp.py close() Windows 进程清理
-**文件**: `py-src/minicode/mcp.py`
-**风险等级**: 🟡 中等
-**问题类别**: 跨平台兼容
-
-**问题描述**:
-Windows 上 `taskkill` 可能超时,超时后需要 fallback 到 `kill()`。此外,`kill()` 后应该等待进程真正退出。所有操作都应该包裹在 try-finally 中确保 `self.process = None`。
-
-**修复内容**:
-```python
-if self.process is not None:
- try:
- if os.name == "nt":
- # Windows: 使用 taskkill 终止进程树
- try:
- subprocess.run(
- ["taskkill", "/T", "/F", "/PID", str(self.process.pid)],
- capture_output=True,
- timeout=5
- )
- except subprocess.TimeoutExpired:
- # taskkill 本身超时,强制 kill
- try:
- self.process.kill()
- except OSError:
- pass
- except Exception:
- try:
- self.process.kill()
- except OSError:
- pass
- else:
- # Unix: 先 SIGTERM,超时后 SIGKILL
- self.process.terminate()
- try:
- self.process.wait(timeout=3)
- except subprocess.TimeoutExpired:
- try:
- self.process.kill()
- except OSError:
- pass
-
- try:
- self.process.wait(timeout=3)
- except subprocess.TimeoutExpired:
- pass
- except OSError:
- pass # 进程可能已经退出
- finally:
- self.process = None
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-### ✅ 10. 修复 Python grep_files.py PermissionError 未处理
-**文件**: `py-src/minicode/tools/grep_files.py`
-**风险等级**: 🟡 中等
-**问题类别**: 异常处理
-
-**问题描述**:
-1. `root.rglob("*")` 在遍历到权限不足的目录时会抛出 `PermissionError`
-2. 文件读取时遇到 OSError(如文件被删除)会崩溃
-3. 跳过文件时没有计数,用户不知道有多少文件被跳过
-
-**修复内容**:
-```python
-def _run(input_data: dict, context) -> ToolResult:
- root = resolve_tool_path(context, input_data["path"], "search")
- regex = re.compile(input_data["pattern"])
- results: list[str] = []
- skipped = 0
-
- try:
- all_files = sorted(root.rglob("*"))
- except PermissionError:
- return ToolResult(ok=False, output=f"Permission denied: {root}")
- except OSError as e:
- return ToolResult(ok=False, output=f"Cannot read directory: {e}")
-
- for file_path in all_files:
- if not file_path.is_file():
- continue
- try:
- lines = file_path.read_text(encoding="utf-8").splitlines()
- except UnicodeDecodeError:
- skipped += 1
- continue
- except OSError:
- skipped += 1
- continue
- for index, line in enumerate(lines, start=1):
- if regex.search(line):
- results.append(f"{file_path.relative_to(Path(context.cwd)).as_posix()}:{index}:{line}")
-
- output = "\n".join(results) if results else "No matches found."
- if skipped > 0:
- output += f"\n({skipped} file(s) skipped)"
- return ToolResult(ok=True, output=output)
-```
-
-**验证**: ✅ 逻辑验证通过
-
----
-
-## 测试验证结果
-
-### Python 测试
-```bash
-$ python -m pytest tests/ -q
-
-91 passed, 1 failed in 2.77s
-
-✅ 通过率: 98.9%
-(失败的 1 个是已有的 split_command_line 测试,与本次修复无关)
-```
-
-### TypeScript 类型检查
-```bash
-$ npm run check
-> tsc --noEmit
-
-✅ 通过(0 错误)
-```
-
----
-
-## 修改文件统计
-
-| 文件 | 修改类型 | 行数变化 |
-|------|---------|---------|
-| `py-src/minicode/mcp.py` | 异常清理 + 进程管理 | +45 / -20 |
-| `ts-src/src/mcp.ts` | dispose 异常处理 | +6 / -1 |
-| `py-src/minicode/agent_loop.py` | model.next 异常保护 | +7 / -1 |
-| `py-src/minicode/permissions.py` | JSON 解析容错 | +10 / -1 |
-| `ts-src/src/permissions.ts` | JSON 解析容错 | +8 / -1 |
-| `py-src/minicode/tools/run_command.py` | PID None 检查 | +6 / 0 |
-| `ts-src/src/tools/run-command.ts` | 超时 + 错误类型 | +18 / -3 |
-| `py-src/minicode/tools/grep_files.py` | PermissionError 处理 | +18 / -3 |
-
-**总计**: 新增 ~118 行,删除 ~30 行
-
----
-
-## 健壮性改进总结
-
-### 防护能力提升
-
-| 隐患类型 | 修复前 | 修复后 |
-|---------|--------|--------|
-| MCP 客户端泄漏 | ❌ 异常时未清理 | ✅ try-except 清理 |
-| 模型 API 错误 | ❌ 崩溃 | ✅ 友好错误消息 |
-| JSON 文件损坏 | ❌ 抛出异常 | ✅ 返回空存储 + 警告 |
-| PID 为 None | ❌ 传入 None | ✅ 检测并返回错误 |
-| 命令执行超时 | ❌ 无限阻塞 | ✅ 5 分钟超时 |
-| 错误类型丢失 | ❌ 只返回 message | ✅ 返回 [code] message |
-| 进程清理失败 | ❌ 可能泄漏 | ✅ try-finally 保证 |
-| 权限不足 | ❌ 抛出异常 | ✅ 友好错误 + 计数 |
-
-### 代码质量提升
-
-- ✅ 异常处理完善(95%+ 覆盖)
-- ✅ 资源清理可靠(try-finally)
-- ✅ 边界条件处理(None、空值、溢出)
-- ✅ 错误消息友好(包含上下文)
-- ✅ 跨平台兼容(Windows/Unix 进程管理)
-
----
-
-## 累计修复统计
-
-### 第一轮:安全隐患修复
-- 严重: 3 个
-- 中等: 7 个
-- 低等: 6 个
-- **小计**: 16 个
-
-### 第二轮:深度优化
-- 高危: 2 个
-- 中等: 6 个
-- 低等: 2 个
-- **小计**: 10 个
-
-### 第三轮:跨平台适配
-- 高危: 1 个
-- 中等: 2 个
-- 低等: 1 个
-- **小计**: 4 个
-
-### 第四轮:代码健壮性
-- 严重: 2 个
-- 中等: 7 个
-- 低等: 1 个
-- **小计**: 10 个
-
-### 总计
-- **修复总数**: 40 个
-- **修改文件**: 28 个
-- **新增代码**: ~483 行
-- **删除代码**: ~96 行
-
----
-
-## 最终结论
-
-### ✅ 所有健壮性问题已修复
-
-- **严重问题**: 2 个 → 已全部修复
-- **中等问题**: 7 个 → 已全部修复
-- **低等问题**: 1 个 → 已全部修复
-
-### 质量评估
-
-| 维度 | 评级 | 说明 |
-|------|------|------|
-| 异常处理 | ⭐⭐⭐⭐⭐ | 95%+ 覆盖 |
-| 资源管理 | ⭐⭐⭐⭐⭐ | try-finally 保证 |
-| 边界条件 | ⭐⭐⭐⭐⭐ | None/空值/溢出 |
-| 错误消息 | ⭐⭐⭐⭐⭐ | 友好且包含上下文 |
-| 跨平台 | ⭐⭐⭐⭐⭐ | Windows/Unix 兼容 |
-| 测试覆盖 | ⭐⭐⭐⭐☆ | 98.9% 通过 |
-
-### 合并建议
-
-**✅ 可以合并到主分支**
-
-所有健壮性修复均:
-- ✅ 通过类型检查
-- ✅ 通过现有测试
-- ✅ 无破坏性变更
-- ✅ 向后兼容
-- ✅ 显著提升可靠性
-
----
-
-**健壮性优化完成日期**: 2026-04-05
-**优化人员**: AI Assistant
-**验证人员**: AI Assistant
-**审核人员**: _____________(待人工审核)
diff --git a/SECURITY_AND_COMPATIBILITY_AUDIT.md b/SECURITY_AND_COMPATIBILITY_AUDIT.md
deleted file mode 100644
index fbf6eb1..0000000
--- a/SECURITY_AND_COMPATIBILITY_AUDIT.md
+++ /dev/null
@@ -1,465 +0,0 @@
-# MiniCode 项目安全隐患与适配性检查报告
-
-## 报告摘要
-
-本报告对 MiniCode 项目(Python 和 TypeScript 双版本)进行了全面的安全隐患和适配性检查,发现以下关键问题:
-
-- **高危问题**: 4 个
-- **中危问题**: 6 个
-- **低危问题**: 5 个
-- **跨语言适配差异**: 10+ 个功能模块不对等
-
----
-
-## 一、高危险隐患(需立即修复)
-
-### 1.1 命令注入漏洞 - `mcp.ts`
-**位置**: `ts-src/src/mcp.ts:308`
-**问题描述**:
-```typescript
-const child = spawn(command, this.config.args ?? [], {
- cwd: this.config.cwd ? path.resolve(this.cwd, this.config.cwd) : this.cwd,
- ...
-})
-```
-MCP 服务器的 `command` 和 `args` 直接从配置文件 (`mcp.json`) 读取后传给 `spawn()`,**没有进行任何验证或沙箱化**。恶意配置文件可执行任意命令。
-
-**风险等级**: 🔴 高
-**影响范围**: 所有使用 MCP 集成的场景
-**修复建议**:
-- 对 `command` 进行白名单验证(仅允许已知可执行文件路径)
-- 使用 `which`/`where` 验证命令是否存在且位于预期路径
-- 限制 `args` 中不允许包含 shell 元字符(如 `|`, `&&`, `;`, `` ` `` 等)
-- 添加配置文件的签名验证机制
-
----
-
-### 1.2 路径遍历漏洞 - `workspace.ts`
-**位置**: `ts-src/src/workspace.ts:9-22`
-**问题描述**:
-```typescript
-const resolved = path.resolve(context.cwd, targetPath)
-if (!context.permissions) {
- const workspaceRoot = path.resolve(context.cwd)
- const relative = path.relative(workspaceRoot, resolved)
-
- if (
- relative === '..' ||
- relative.startsWith(`..${path.sep}`) ||
- path.isAbsolute(relative)
- ) {
- throw new Error(`Path escapes workspace: ${targetPath}`)
- }
-}
-```
-
-**缺陷**:
-1. 对符号链接 (symlink) 无效,攻击者可通过 symlink 绕过检查
-2. 当 `path.isAbsolute(relative)` 为 true 时,合法的相对路径(解析后仍在工作区内)会被误判为绝对路径而拒绝
-3. Windows 路径分隔符问题:`path.sep` 在 Windows 是 `\`,但 JavaScript 也接受 `/`
-
-**风险等级**: 🔴 高
-**影响范围**: 所有文件读写操作
-**修复建议**:
-- 使用 `fs.realpath()` 对路径进行规范化后再检查
-- 对符号链接进行解析和验证
-- 同时检查 `../` 和 `..\` 两种前缀
-- 统一使用权限模块的路径检查逻辑
-
----
-
-### 1.3 不安全的文件写入 - `install.ts`
-**位置**: `ts-src/src/install.ts:105-113`
-**问题描述**:
-安装脚本在 `~/.local/bin/` 目录下创建 bash 启动脚本时:
-1. 脚本内容中硬编码了 `repoRoot` 路径
-2. 未检查 `launcherPath` 是否已存在,可能覆盖用户已有文件
-3. 如果攻击者能篡改 `import.meta.url` 解析出的路径,可能导致执行恶意脚本
-
-**风险等级**: 🔴 高
-**影响范围**: 安装过程
-**修复建议**:
-- 在写入前检查文件是否已存在,存在则提示用户确认
-- 验证 `repoRoot` 路径的合法性(确保在预期的安装目录内)
-- 使用原子写入(先写临时文件再重命名)
-
----
-
-### 1.4 敏感信息泄露风险 - `config.ts`
-**位置**: `ts-src/src/config.ts:162-171`
-**问题描述**:
-```typescript
-return {
- model: model,
- baseUrl: base_url,
- authToken: auth_token,
- apiKey: api_key,
- maxOutputTokens: max_output_tokens,
- mcpServers: effective.get("mcpServers", {}),
- sourceSummary: `config: ${MINI_CODE_SETTINGS_PATH} > ${CLAUDE_SETTINGS_PATH} > process.env`,
-}
-```
-
-`sourceSummary` 字段暴露了配置文件路径。如果此对象被日志记录或错误输出,可能泄露敏感信息的位置。
-
-**风险等级**: 🟠 中高
-**影响范围**: 配置加载和日志记录
-**修复建议**:
-- 不要在 `sourceSummary` 中包含配置文件路径
-- 日志输出时对认证信息进行脱敏处理
-
----
-
-## 二、中危险隐患
-
-### 2.1 跨平台适配问题 - `bin/minicode`
-**位置**: `ts-src/bin/minicode:1-7`
-**问题描述**: 启动脚本是纯 Bash 脚本,使用了 `BASH_SOURCE` 等 Bash 特有变量,在 Windows CMD/PowerShell 上无法直接使用。
-
-**风险等级**: 🟡 中
-**修复建议**:
-- 提供 Windows 的 `.cmd` 或 `.ps1` 启动脚本
-- 或使用 Node.js 编写跨平台的启动器
-
----
-
-### 2.2 资源泄漏 - `mcp.ts`
-**位置**: `ts-src/src/mcp.ts:307-350`
-**问题描述**:
-```typescript
-async close(): Promise {
- for (const pending of this.pending.values()) {
- clearTimeout(pending.timeout)
- pending.reject(
- new Error(`MCP server "${this.serverName}" closed before completing the request.`),
- )
- }
- this.pending.clear()
-
- if (!this.process) {
- this.protocol = null
- return
- }
-
- this.process.kill() // 没有等待进程真正退出
- this.process = null
- this.protocol = null
-}
-```
-
-`spawn` 创建的子进程在以下情况可能泄漏:
-- `close()` 方法调用 `this.process.kill()` 后没有等待进程真正退出
-- 如果子进程忽略 SIGTERM/SIGKILL,可能成为僵尸进程
-- stdout/stderr 流没有显式销毁
-
-**风险等级**: 🟡 中
-**修复建议**:
-- `close()` 应等待进程退出后再清理
-- 添加超时强制终止机制
-- 显式调用 `child.stdout.destroy()` 和 `child.stderr.destroy()`
-
----
-
-### 2.3 未处理的 Promise 拒绝 - `mcp.ts`
-**位置**: `ts-src/src/mcp.ts:439, 467`
-**问题描述**:
-```typescript
-// handleStdoutChunk
-this.handleMessage(JSON.parse(payload) as JsonRpcMessage)
-
-// handleStdoutChunkAsLines
-this.handleMessage(JSON.parse(line) as JsonRpcMessage)
-```
-
-`JSON.parse()` 如果解析失败会抛出异常,但该异常未被 try-catch 包裹,会导致未处理的 Promise 拒绝和进程崩溃。
-
-**风险等级**: 🟡 中
-**修复建议**:
-- 所有 `JSON.parse()` 调用都用 try-catch 包裹
-- 对无效的 JSON 数据进行日志记录而非直接崩溃
-
----
-
-### 2.4 路径遍历风险(符号链接绕过)- `permissions.ts`
-**位置**: `ts-src/src/permissions.ts:57-63`
-**问题描述**:
-```typescript
-function isWithinDirectory(root: string, target: string): boolean {
- const relative = path.relative(root, target)
- return (
- relative === '' ||
- (!relative.startsWith(`..${path.sep}`) &&
- relative !== '..' &&
- !path.isAbsolute(relative))
- )
-}
-```
-
-`isWithinDirectory` 函数使用 `path.relative()` 判断路径关系,但:
-1. 没有处理符号链接,攻击者可以创建指向工作区外的符号链接来绕过此检查
-2. 在 Windows 上,路径大小写不敏感的问题可能导致安全检查失效(如 `C:\Users` vs `c:\users`)
-
-**风险等级**: 🟡 中
-**修复建议**:
-- 使用 `fs.realpathSync()` 规范化路径后再比较
-- Windows 上进行大小写规范化比较
-
----
-
-### 2.5 配置竞态条件 - `config.ts`
-**位置**: `ts-src/src/config.ts:123-134`
-**问题描述**:
-1. `mergeSettings` 对 `env` 和 `mcpServers` 进行浅合并,如果配置项嵌套更深,会导致部分配置被覆盖丢失
-2. 多个进程同时写入同一配置文件时可能产生竞态条件
-
-**风险等级**: 🟡 中
-**修复建议**:
-- 对深度嵌套对象使用深合并逻辑
-- 文件写入使用文件锁或原子操作(先写 `.tmp` 再 `rename`)
-
----
-
-### 2.6 危险命令检测可被绕过 - `permissions.ts`
-**位置**: `ts-src/src/permissions.ts:103`
-**问题描述**:
-```typescript
-function classifyDangerousCommand(command: string, args: string[]): string | null {
- // ...
- if (
- command === 'node' ||
- command === 'python3' ||
- command === 'bun' ||
- command === 'bash' ||
- command === 'sh'
- ) {
- return `${command} can execute arbitrary local code (${signature})`
- }
-}
-```
-
-对危险命令的检测仅基于简单的字符串匹配,容易被绕过:
-- 可以使用绝对路径(如 `/usr/bin/bash` 而非 `bash`)
-- 可以使用编码技巧绕过检测
-- Python 版还检测了 `python`,但 TS 版缺失
-
-**风险等级**: 🟡 中
-**修复建议**:
-- 对命令进行规范化(使用 `which` 解析绝对路径)后再比对
-- 支持正则表达式模式匹配,而非简单字符串包含
-- 补充缺失的命令检测(如 `python`)
-
----
-
-## 三、低危险隐患
-
-### 3.1 类型安全问题 - `mcp.ts`
-**位置**: `ts-src/src/mcp.ts` 多处
-**问题描述**: 大量使用 `as unknown` 和 `as` 类型断言绕过 TypeScript 类型检查,可能在运行时导致类型不匹配错误。
-
-**风险等级**: 🟢 低
-**修复建议**:
-- 使用 Zod 或其他运行时验证库替代类型断言
-- 对 MCP 响应进行 schema 验证
-
----
-
-### 3.2 Windows 路径分隔符问题
-**位置**: `permissions.ts:59`, `workspace.ts:16`
-**问题描述**: 代码使用 `` `..${path.sep}` `` 检查路径遍历,在 Windows 上 `path.sep` 是 `\`,但 JavaScript 和许多 API 也接受 `/` 作为路径分隔符。
-
-**风险等级**: 🟢 低中
-**修复建议**:
-- 同时检查 `../` 和 `..\` 两种前缀
-- 或使用 `path.normalize()` 标准化后再检查
-
----
-
-### 3.3 无限循环风险 - `agent-loop.ts`
-**位置**: `ts-src/src/agent-loop.ts:91`
-**问题描述**:
-```typescript
-for (let step = 0; maxSteps == null || step < maxSteps; step++) {
-```
-
-当 `maxSteps` 为 `null` 或 `undefined` 时,循环没有上限。虽然有 `emptyResponseRetryCount` 等计数器进行局部限制,但没有全局退出机制。
-
-**风险等级**: 🟢 低
-**修复建议**:
-- 为 `maxSteps` 设置合理的默认上限(如 50)
-- 添加超时机制防止长时间运行
-
----
-
-### 3.4 readline 资源泄漏 - `index.ts`
-**位置**: `ts-src/src/index.ts:65, 136`
-**问题描述**: readline 接口在异常情况下可能未正确关闭。
-
-**风险等级**: 🟢 低
-**修复建议**:
-- 将 `rl.close()` 移到 `finally` 块中
-- 或确保所有异常路径都能正确清理
-
----
-
-### 3.5 环境变量覆盖风险 - `config.ts`
-**位置**: `ts-src/src/config.ts:164-166`
-**问题描述**: 环境变量优先级设计不当:`process.env` 会覆盖配置文件中的设置。恶意进程可通过设置环境变量篡改行为。
-
-**风险等级**: 🟢 低
-**修复建议**:
-- 明确文档说明环境变量优先级
-- 提供配置选项禁用环境变量覆盖
-
----
-
-## 四、跨语言适配差异
-
-### 4.1 严重功能缺失
-
-| 缺失模块 | Python 有 | TypeScript 缺失 | 影响 |
-|---------|----------|----------------|------|
-| `session.py` (356行) | ✅ | ❌ | 无会话持久化与恢复 |
-| `sub_agents.py` (366行) | ✅ | ❌ | 无子代理系统 |
-| `auto_mode.py` (440行) | ✅ | ❌ | 无自动模式 |
-| `memory.py` | ✅ | ❌ | 无三级记忆系统 |
-| `context_manager.py` | ✅ | ❌ | 无上下文窗口管理 |
-| `cost_tracker.py` | ✅ | ❌ | 无 API 成本追踪 |
-| `hooks.py` | ✅ | ❌ | 无生命周期钩子 |
-| `state.py` | ✅ | ❌ | 无应用状态管理 |
-| `task_tracker.py` | ✅ | ❌ | 无任务追踪 |
-| `poly_commands.py` | ✅ | ❌ | 无多态命令系统 |
-
-### 4.2 工具模块差异
-
-| 维度 | Python | TypeScript |
-|------|--------|------------|
-| 工具数量 | 29 个 | 11 个 |
-| Python 独有工具 | `api_tester`, `ask_user`, `code_nav`, `code_review`, `db_explorer`, `diff_viewer`, `docker_helper`, `file_tree`, `git`, `governance_audit*`, `notebook_edit`, `run_with_debug`, `test_runner`, `todo_write`, `web_fetch`, `web_search` | - |
-
-### 4.3 错误消息语言不一致
-
-**问题**: TypeScript 版 `agent-loop.ts` 中多处错误消息使用中文,而 Python 版全部使用英文:
-
-```typescript
-// TS 版(中英文混杂)
-' 诊断信息: ${parts.join('; ')}。'
-'模型在 thinking 阶段触发 max_tokens,正在继续请求后续步骤...'
-'工具执行后模型返回空响应,已停止当前回合。'
-'达到最大工具步数限制,已停止当前回合。'
-
-// Python 版(全英文)
-f"Diagnostics: {'; '.join(parts)}."
-"Model hit max_tokens during thinking; requesting the next step."
-"Model returned an empty response after tool execution..."
-"Reached the maximum tool step limit for this turn."
-```
-
-**建议**: 统一使用英文错误消息,或实现国际化支持。
-
-### 4.4 测试覆盖率差异
-
-| 维度 | Python | TypeScript |
-|------|--------|------------|
-| 测试文件数 | **15 个** | **0 个** |
-| 测试框架 | pytest | 无配置 |
-| 覆盖模块 | agent_loop, anthropic_adapter, cli_commands, config, mcp, mock_model, permissions, prompt, session, skills, tools, tui, tty_app | 无 |
-
-**TS 版本完全没有项目级别的测试**,这是最严重的适配差异。
-
-### 4.5 设计差异
-
-| 维度 | Python | TypeScript |
-|------|--------|------------|
-| 核心循环 | 同步 | 异步 (`async/await`) |
-| ToolDefinition | `validator` 函数 | Zod schema |
-| Skill Install API | 位置参数 | 对象参数 `{cwd, sourcePath, name?, scope?}` |
-| 包命名 | `minicode-py` | `mini-code` |
-
----
-
-## 五、Python 特有问题
-
-### 5.1 同步 vs 异步设计
-**问题**: Python 核心循环为同步,而 TS 为异步。这导致:
-- Python 版本无法利用异步 I/O 的优势
-- MCP 客户端在 Python 中使用 `subprocess`+线程,性能不如 TS 的 `spawn`+事件
-
-**建议**: 考虑将 Python 版本改为 `async/await` 模式
-
-### 5.2 依赖管理
-**问题**: `pyproject.toml` 中 `dependencies = []`,零依赖设计虽然轻量,但:
-- 没有 HTTP 客户端库,如何实现 API 调用?
-- 没有 JSON 验证库,配置解析可能失败
-
-**检查**: 确认是否使用了标准库的 `urllib` 或 `http.client`
-
----
-
-## 六、修复优先级建议
-
-### P0 - 立即修复(高危)
-1. ✅ `mcp.ts` 命令注入漏洞
-2. ✅ `workspace.ts` 路径遍历漏洞
-3. ✅ `install.ts` 不安全文件写入
-4. ✅ `config.ts` 敏感信息泄露
-
-### P1 - 尽快修复(中危)
-5. `permissions.ts` 符号链接绕过
-6. `mcp.ts` 未处理的 Promise 拒绝
-7. `mcp.ts` 资源泄漏
-8. `permissions.ts` 危险命令检测绕过
-9. `config.ts` 配置竞态条件
-10. `bin/minicode` 跨平台适配
-
-### P2 - 计划修复(低危)
-11. `mcp.ts` 类型安全问题
-12. Windows 路径分隔符问题
-13. `agent-loop.ts` 无限循环风险
-14. `index.ts` readline 资源泄漏
-15. `config.ts` 环境变量覆盖
-
-### P3 - 功能对齐(适配性)
-16. 为 TS 版本补充缺失的 10+ 个高级功能模块
-17. 为 TS 版本补充缺失的 18+ 个工具
-18. 统一错误消息语言
-19. 为 TS 版本编写项目测试
-20. 同步/异步设计统一
-
----
-
-## 七、安全检查清单
-
-- [ ] 命令注入防护
-- [ ] 路径遍历防护
-- [ ] 符号链接安全处理
-- [ ] 配置文件验证
-- [ ] 敏感信息脱敏
-- [ ] 资源泄漏防护
-- [ ] 错误处理完整性
-- [ ] 跨平台兼容性
-- [ ] 测试覆盖率
-- [ ] 依赖安全性
-
----
-
-## 八、总结
-
-MiniCode 项目在以下方面表现良好:
-- ✅ 权限管理系统设计完善
-- ✅ MCP 集成架构合理
-- ✅ 配置管理系统灵活
-- ✅ 双版本代码结构一致
-
-但需要重点关注:
-- 🔴 4 个高危安全漏洞
-- 🟡 6 个中危设计缺陷
-- 📊 TypeScript 版本功能严重不足(缺失 10+ 模块、18+ 工具、0 测试)
-- 🌐 跨语言适配差异较大
-
-**建议**: 优先修复 P0 级别的安全隐患,然后逐步对齐两个版本的功能和测试覆盖率。
-
----
-
-**报告生成日期**: 2026-04-05
-**检查范围**: `py-src/` 和 `ts-src/` 全部源代码
-**风险评级标准**: OWASP Risk Rating Methodology
diff --git a/SECURITY_FIXES_REPORT.md b/SECURITY_FIXES_REPORT.md
deleted file mode 100644
index 0faa698..0000000
--- a/SECURITY_FIXES_REPORT.md
+++ /dev/null
@@ -1,260 +0,0 @@
-# 安全隐患修复报告
-
-## 修复概览
-
-本次修复针对 MiniCode 项目(TypeScript 版本)发现了 **10 个关键安全隐患和适配性问题**,现已全部修复完成。
-
----
-
-## 修复详情
-
-### ✅ 1. 修复 mcp.ts 命令注入漏洞
-**文件**: `ts-src/src/mcp.ts`
-**修复内容**:
-- 新增命令白名单验证机制 (`ALLOWED_COMMANDS`)
-- 新增危险 shell 元字符检测 (`DANGEROUS_SHELL_CHARS`)
-- 新增 `validateMcpCommand()` 函数验证命令路径
-- 新增 `validateMcpArgs()` 函数验证参数安全性
-- 在 `spawnProcess()` 中调用验证函数
-
-**安全增强**:
-- 防止恶意配置文件执行任意命令
-- 阻止 shell 注入攻击(`|`, `&&`, `;`, `` ` `` 等)
-- 允许绝对路径但禁止路径遍历 (`..`, `~`)
-
----
-
-### ✅ 2. 修复 workspace.ts 路径遍历漏洞
-**文件**: `ts-src/src/workspace.ts`
-**修复内容**:
-- 导入 `realpath` 用于路径规范化
-- 使用 `await realpath()` 解析符号链接
-- 同时检查 `../` 和 `..\` 两种路径遍历前缀
-- 路径不存在时降级使用 `path.normalize()`
-
-**安全增强**:
-- 防止通过符号链接绕过工作区限制
-- 跨平台兼容 Windows 和 Unix 路径分隔符
-- 优雅处理不存在路径的边缘情况
-
----
-
-### ✅ 3. 修复 permissions.ts 符号链接绕过问题
-**文件**: `ts-src/src/permissions.ts`
-**修复内容**:
-- 将 `isWithinDirectory()` 改为异步函数
-- 使用 `realpath()` 规范化路径后再比较
-- 更新 `matchesDirectoryPrefix()` 为同步版本(用于简单检查)
-- 在 `ensurePathAccess()` 中使用 `await isWithinDirectory()`
-
-**安全增强**:
-- 防止攻击者创建指向工作区外的符号链接
-- 同时检查 `../` 和 `..\` 前缀
-- 增强跨平台路径比较安全性
-
----
-
-### ✅ 4. 修复 mcp.ts 未处理的 JSON.parse 异常
-**文件**: `ts-src/src/mcp.ts`
-**修复内容**:
-- 在 `handleStdoutChunk()` 中为 `JSON.parse()` 添加 try-catch
-- 在 `handleStdoutChunkAsLines()` 中为 `JSON.parse()` 添加 try-catch
-- 解析失败时记录错误日志而非崩溃
-
-**安全增强**:
-- 防止恶意 MCP 服务器发送无效 JSON 导致进程崩溃
-- 提高系统鲁棒性和容错能力
-- 避免未处理的 Promise 拒绝
-
----
-
-### ✅ 5. 修复 mcp.ts 资源泄漏问题
-**文件**: `ts-src/src/mcp.ts`
-**修复内容**:
-- 重构 `close()` 方法为异步优雅关闭
-- 添加 3 秒超时强制终止机制
-- 先发送 `SIGTERM`,超时后发送 `SIGKILL`
-- 显式销毁 `stdout` 和 `stderr` 流
-- 监听子进程 `exit` 事件确保完全退出
-
-**安全增强**:
-- 防止僵尸进程产生
-- 确保子进程资源完全释放
-- 避免文件描述符泄漏
-
----
-
-### ✅ 6. 修复 install.ts 不安全文件写入
-**文件**: `ts-src/src/install.ts`
-**修复内容**:
-- 验证 `repoRoot` 路径合法性(禁止 `..` 和 `~`)
-- 写入前检查文件是否已存在
-- 存在时提示用户确认(y/N)
-- 使用临时文件 + 重命名的原子写入方式
-- 添加 finally 块清理临时文件
-
-**安全增强**:
-- 防止覆盖用户已有文件
-- 防止路径遍历攻击
-- 原子写入确保文件完整性
-
----
-
-### ✅ 7. 修复 config.ts 敏感信息泄露
-**文件**: `ts-src/src/config.ts`
-**修复内容**:
-- 新增 `sanitizeConfigSourceSummary()` 函数
-- 将 `sourceSummary` 从具体路径改为通用描述
-- 从 `config: ~/.mini-code/settings.json > ...` 改为 `user settings > claude settings > env`
-
-**安全增强**:
-- 防止日志泄露配置文件路径
-- 降低敏感信息暴露风险
-- 符合最小权限原则
-
----
-
-### ✅ 8. 修复 permissions.ts 危险命令检测
-**文件**: `ts-src/src/permissions.ts` 和 `py-src/minicode/permissions.py`
-**修复内容**:
-- 补充 `python` 命令检测(之前只有 `python3`)
-- 新增 `pythonw`(Windows Python GUI)
-- 新增 `zsh`, `fish` shell 检测
-- 新增 `powershell`, `pwsh`(PowerShell Core)检测
-
-**安全增强**:
-- 防止通过未检测的解释器绕过安全限制
-- 跨平台覆盖所有常见命令执行环境
-- 保持 Python 和 TypeScript 版本一致
-
----
-
-### ✅ 9. 统一 agent-loop 错误消息语言
-**文件**: `ts-src/src/agent-loop.ts`
-**修复内容**:
-- ` 诊断信息: ...。` → ` Diagnostics: ....`
-- `模型在 thinking 阶段触发 max_tokens...` → `Model hit max_tokens during thinking...`
-- `工具执行后模型返回空响应...` → `Model returned an empty response after tool execution...`
-- `达到最大工具步数限制...` → `Reached the maximum tool step limit...`
-
-**安全增强**:
-- 统一使用英文错误消息
-- 与 Python 版本保持一致
-- 提高国际化兼容性
-
----
-
-### ✅ 10. 添加 Windows 跨平台启动脚本
-**文件**: `ts-src/bin/minicode.cmd`, `ts-src/bin/minicode.ps1`
-**修复内容**:
-- 创建 CMD 版本启动脚本 (`minicode.cmd`)
-- 创建 PowerShell 版本启动脚本 (`minicode.ps1`)
-- 自动解析项目根目录
-- 使用 tsx 运行 TypeScript 代码
-- 正确传递命令行参数
-
-**安全增强**:
-- Windows 用户可直接在 CMD/PowerShell 中使用
-- 不再依赖 Bash 环境
-- 提高跨平台可用性
-
----
-
-## 修复统计
-
-| 风险等级 | 修复数量 | 主要修复内容 |
-|---------|---------|------------|
-| 🔴 高危 | 4 | 命令注入、路径遍历、不安全文件写入、信息泄露 |
-| 🟡 中危 | 4 | 资源泄漏、JSON 解析异常、命令检测绕过、符号链接绕过 |
-| 🟢 低危 | 2 | 错误消息不一致、跨平台兼容性 |
-
----
-
-## 修改文件清单
-
-### TypeScript 版本 (ts-src/)
-1. `src/mcp.ts` - 命令注入验证、JSON 解析异常处理、资源泄漏修复
-2. `src/workspace.ts` - 路径遍历修复(realpath)
-3. `src/permissions.ts` - 符号链接绕过修复、危险命令检测补充
-4. `src/agent-loop.ts` - 错误消息语言统一
-5. `src/config.ts` - 敏感信息脱敏
-6. `src/install.ts` - 不安全文件写入修复
-7. `bin/minicode.cmd` - **新增** Windows CMD 启动脚本
-8. `bin/minicode.ps1` - **新增** Windows PowerShell 启动脚本
-
-### Python 版本 (py-src/)
-1. `minicode/permissions.py` - 危险命令检测补充(python, pythonw, zsh, fish, powershell, pwsh)
-
----
-
-## 后续建议
-
-### 短期(1-2 周)
-1. **添加单元测试**:为修复的安全功能编写测试用例
-2. **代码审查**:请其他开发者审查修改
-3. **集成测试**:验证修复后功能正常
-
-### 中期(1 个月)
-1. **功能对齐**:为 TypeScript 版本补充缺失的 10+ 模块
-2. **工具补齐**:添加 Python 版本独有的 18+ 工具
-3. **测试覆盖**:达到 80%+ 代码覆盖率
-
-### 长期(持续)
-1. **依赖安全扫描**:定期检查依赖包漏洞
-2. **安全审计**:定期进行第三方安全审计
-3. **威胁建模**:识别新的潜在攻击面
-
----
-
-## 测试建议
-
-### 安全测试用例
-```bash
-# 1. 命令注入测试
-echo '{"mcpServers": {"test": {"command": "echo", "args": ["; rm -rf /"]}}}' > .mcp.json
-
-# 2. 路径遍历测试
-ln -s /etc/passwd symlink
-minicode # 尝试读取 symlink
-
-# 3. 符号链接绕过测试
-ln -s .. outside_link
-minicode # 尝试访问工作区外路径
-
-# 4. JSON 注入测试
-# 配置恶意 MCP 服务器发送无效 JSON
-```
-
-### 跨平台测试
-- [ ] Windows CMD: `minicode.cmd`
-- [ ] Windows PowerShell: `minicode.ps1`
-- [ ] Linux Bash: `./bin/minicode`
-- [ ] macOS Zsh: `./bin/minicode`
-
----
-
-## 兼容性说明
-
-### 破坏性变更
-- **无**:所有修复均为向后兼容的安全增强
-
-### 配置变更
-- **无**:配置文件格式保持不变
-
-### API 变更
-- **permissions.ts**: `isWithinDirectory()` 现在是异步函数
-- **mcp.ts**: `close()` 方法现在返回 Promise
-
----
-
-## 结论
-
-本次修复显著提升了 MiniCode 项目的安全性,解决了 **4 个高危、4 个中危、2 个低危** 共 10 个安全问题。同时增强了跨平台兼容性,为 Windows 用户提供了原生支持。
-
-所有修复均经过仔细设计,确保**向后兼容**且**不引入破坏性变更**。建议尽快进行代码审查和测试,然后合并到主分支。
-
----
-
-**修复完成日期**: 2026-04-05
-**修复人员**: AI Assistant
-**审查状态**: 待审查
diff --git a/SECURITY_TESTS.md b/SECURITY_TESTS.md
deleted file mode 100644
index db72e99..0000000
--- a/SECURITY_TESTS.md
+++ /dev/null
@@ -1,693 +0,0 @@
-# MiniCode 安全修复验证测试套件
-
-本文件包含针对所有安全修复的验证测试用例。
-
-## 测试环境
-
-- **TypeScript**: Node.js, tsx, zod
-- **Python**: Python 3.11+, pytest
-- **平台**: Windows 10/11, Linux, macOS
-
----
-
-## 1. MCP 命令注入验证测试
-
-### 1.1 测试命令白名单验证
-
-```typescript
-// 测试文件: ts-src/tests/mcp-security.test.ts
-import { describe, it, expect } from 'vitest'
-import { createMcpBackedTools } from '../src/mcp.js'
-
-describe('MCP Command Injection Prevention', () => {
- it('应该拒绝不在白名单中的相对命令', async () => {
- await expect(
- createMcpBackedTools({
- cwd: process.cwd(),
- mcpServers: {
- malicious: {
- command: 'malicious_command',
- args: ['--exploit'],
- },
- },
- })
- ).rejects.toThrow(/not in the allowed list/)
- })
-
- it('应该拒绝包含 shell 元字符的参数', async () => {
- await expect(
- createMcpBackedTools({
- cwd: process.cwd(),
- mcpServers: {
- test: {
- command: 'node',
- args: ['-e', 'console.log("test"); rm -rf /'],
- },
- },
- })
- ).rejects.toThrow(/dangerous shell character/)
- })
-
- it('应该允许白名单中的命令', async () => {
- const result = await createMcpBackedTools({
- cwd: process.cwd(),
- mcpServers: {
- valid: {
- command: 'node',
- args: ['--version'],
- },
- },
- })
- expect(result.servers).toHaveLength(1)
- expect(result.servers[0].status).toBe('connected')
- })
-})
-```
-
-### 1.2 手动测试步骤
-
-```bash
-# 1. 创建测试配置文件
-cat > test-mcp-config.json << 'EOF'
-{
- "mcpServers": {
- "test": {
- "command": "node",
- "args": ["--version"]
- }
- }
-}
-EOF
-
-# 2. 测试合法命令
-minicode --mcp-config test-mcp-config.json
-
-# 3. 测试恶意命令(应该被拒绝)
-cat > malicious-mcp-config.json << 'EOF'
-{
- "mcpServers": {
- "malicious": {
- "command": "evil_command",
- "args": ["; rm -rf /"]
- }
- }
-}
-EOF
-
-# 启动时应该报错
-minicode --mcp-config malicious-mcp-config.json
-```
-
----
-
-## 2. 路径遍历漏洞验证
-
-### 2.1 自动化测试
-
-```typescript
-// 测试文件: ts-src/tests/workspace-security.test.ts
-import { describe, it, expect } from 'vitest'
-import path from 'path'
-import { resolveToolPath } from '../src/workspace.js'
-import type { ToolContext } from '../src/tool.js'
-
-describe('Workspace Path Traversal Prevention', () => {
- const mockContext: ToolContext = {
- cwd: '/workspace',
- permissions: undefined,
- }
-
- it('应该阻止 ../ 路径遍历', async () => {
- await expect(
- resolveToolPath(mockContext, '../etc/passwd', 'read')
- ).rejects.toThrow(/Path escapes workspace/)
- })
-
- it('应该阻止 ..\\ 路径遍历 (Windows)', async () => {
- await expect(
- resolveToolPath(mockContext, '..\\..\\windows\\system32', 'read')
- ).rejects.toThrow(/Path escapes workspace/)
- })
-
- it('应该允许工作区内的相对路径', async () => {
- const result = await resolveToolPath(mockContext, 'src/index.ts', 'read')
- expect(result).toContain('src')
- expect(result).toContain('index.ts')
- })
-})
-```
-
-### 2.2 手动测试
-
-```bash
-# 1. 创建测试环境
-mkdir -p /tmp/test-workspace
-cd /tmp/test-workspace
-echo "secret" > /tmp/secret-file
-
-# 2. 尝试通过路径遍历读取外部文件
-# 应该失败
-minicode --cwd /tmp/test-workspace
-# 输入: read_file ../../../../tmp/secret-file
-
-# 3. 创建符号链接测试
-cd /tmp/test-workspace
-ln -s /tmp/secret-file symlink-to-secret
-
-# 4. 尝试通过符号链读取(应该被 realpath 阻止)
-minicode --cwd /tmp/test-workspace
-# 输入: read_file symlink-to-secret
-```
-
----
-
-## 3. 符号链接绕过验证
-
-### 3.1 权限系统测试
-
-```typescript
-// 测试文件: ts-src/tests/permissions-security.test.ts
-import { describe, it, expect, beforeEach, afterEach } from 'vitest'
-import fs from 'fs/promises'
-import path from 'path'
-import os from 'os'
-import { PermissionManager } from '../src/permissions.js'
-
-describe('Permission Symlink Prevention', () => {
- let tempDir: string
- let workspaceDir: string
- let outsideFile: string
- let symlink: string
-
- beforeEach(async () => {
- tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'permissions-test-'))
- workspaceDir = path.join(tempDir, 'workspace')
- outsideFile = path.join(tempDir, 'outside-secret.txt')
- symlink = path.join(workspaceDir, 'symlink')
-
- await fs.mkdir(workspaceDir)
- await fs.writeFile(outsideFile, 'secret content')
- await fs.symlink(outsideFile, symlink)
- })
-
- afterEach(async () => {
- await fs.rm(tempDir, { recursive: true, force: true })
- })
-
- it('应该阻止通过符号链接访问工作区外文件', async () => {
- const manager = new PermissionManager(workspaceDir)
- await manager.whenReady()
-
- await expect(
- manager.ensurePathAccess(symlink, 'read')
- ).rejects.toThrow(/Access denied/)
- })
-
- it('应该允许访问工作区内的正常文件', async () => {
- const manager = new PermissionManager(workspaceDir)
- await manager.whenReady()
-
- const insideFile = path.join(workspaceDir, 'inside.txt')
- await fs.writeFile(insideFile, 'test')
-
- // 不应该抛出异常
- await manager.ensurePathAccess(insideFile, 'read')
- })
-})
-```
-
----
-
-## 4. JSON 解析异常处理验证
-
-### 4.1 自动化测试
-
-```typescript
-// 测试文件: ts-src/tests/mcp-json-error.test.ts
-import { describe, it, expect } from 'vitest'
-
-describe('MCP JSON Error Handling', () => {
- it('应该优雅处理无效 JSON 而不崩溃', async () => {
- // 创建模拟的无效输出
- const invalidOutput = Buffer.from('this is not valid JSON')
-
- // 测试客户端应该能处理无效 JSON
- // (实际测试需要 mock spawn 进程)
- expect(() => {
- try {
- JSON.parse(invalidOutput.toString())
- } catch (error) {
- // 应该被 catch 而不崩溃
- expect(error).toBeDefined()
- }
- }).not.toThrow()
- })
-
- it('应该记录错误日志而不是崩溃', async () => {
- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
-
- // 模拟 handleMessage 调用
- const client = // ... 创建客户端
- // 发送无效数据
-
- expect(consoleSpy).toHaveBeenCalledWith(
- expect.stringContaining('Failed to parse JSON-RPC message')
- )
-
- consoleSpy.mockRestore()
- })
-})
-```
-
----
-
-## 5. 资源泄漏验证
-
-### 5.1 子进程清理测试
-
-```typescript
-// 测试文件: ts-src/tests/mcp-resource-leak.test.ts
-import { describe, it, expect, vi } from 'vitest'
-import { spawn } from 'node:child_process'
-
-describe('MCP Resource Cleanup', () => {
- it('应该在 close() 后完全清理子进程', async () => {
- const client = // ... 创建客户端
-
- // 启动
- await client.start()
-
- // 关闭
- await client.close()
-
- // 验证进程已退出
- expect(client['process']).toBeNull()
- })
-
- it('应该在 3 秒超时后强制终止进程', async () => {
- // Mock 一个不响应 SIGTERM 的进程
- const client = // ... 创建客户端
-
- const startTime = Date.now()
- await client.close()
- const duration = Date.now() - startTime
-
- // 应该在 3 秒左右完成
- expect(duration).toBeLessThan(4000)
- })
-})
-```
-
----
-
-## 6. 安装脚本安全验证
-
-### 6.1 文件存在性检查测试
-
-```typescript
-// 测试文件: ts-src/tests/install-security.test.ts
-import { describe, it, expect, vi } from 'vitest'
-import fs from 'fs/promises'
-import path from 'path'
-
-describe('Install Script Security', () => {
- it('应该在文件存在时提示用户确认', async () => {
- // Mock 文件存在
- vi.mocked(fs.access).mockResolvedValue(undefined)
-
- // 运行安装脚本
- // 应该提示用户确认
-
- expect(console.log).toHaveBeenCalledWith(
- expect.stringContaining('已存在')
- )
- })
-
- it('应该拒绝包含 .. 的安装路径', async () => {
- // 测试路径验证逻辑
- const maliciousPath = '/tmp/../../../etc/malicious'
-
- expect(() => {
- if (maliciousPath.includes('..')) {
- throw new Error('Invalid installation path')
- }
- }).toThrow(/Invalid installation path/)
- })
-})
-```
-
----
-
-## 7. 危险命令检测验证
-
-### 7.1 Python 版本测试
-
-```python
-# 测试文件: py-src/tests/test_permissions_security.py
-import pytest
-from minicode.permissions import _classify_dangerous_command
-
-def test_python_is_detected():
- result = _classify_dangerous_command("python", ["-c", "print('hello')"])
- assert result is not None
- assert "python" in result.lower()
-
-def test_python3_is_detected():
- result = _classify_dangerous_command("python3", ["--version"])
- assert result is not None
-
-def test_pythonw_is_detected():
- result = _classify_dangerous_command("pythonw", ["script.py"])
- assert result is not None
-
-def test_powershell_is_detected():
- result = _classify_dangerous_command("powershell", ["-Command", "Get-Process"])
- assert result is not None
-
-def test_pwsh_is_detected():
- result = _classify_dangerous_command("pwsh", ["--version"])
- assert result is not None
-
-def test_zsh_is_detected():
- result = _classify_dangerous_command("zsh", ["-c", "echo hello"])
- assert result is not None
-
-def test_fish_is_detected():
- result = _classify_dangerous_command("fish", ["-c", "echo hello"])
- assert result is not None
-```
-
-### 7.2 TypeScript 版本测试
-
-```typescript
-// 测试文件: ts-src/tests/permissions-security.test.ts
-import { describe, it, expect } from 'vitest'
-
-// 需要导出 classifyDangerousCommand 函数进行测试
-import { classifyDangerousCommand } from '../src/permissions.js'
-
-describe('Dangerous Command Detection', () => {
- it('应该检测 python 命令', () => {
- const result = classifyDangerousCommand('python', ['-c', "print('hello')"])
- expect(result).not.toBeNull()
- expect(result).toContain('python')
- })
-
- it('应该检测 python3 命令', () => {
- const result = classifyDangerousCommand('python3', ['--version'])
- expect(result).not.toBeNull()
- })
-
- it('应该检测 pythonw 命令', () => {
- const result = classifyDangerousCommand('pythonw', ['script.py'])
- expect(result).not.toBeNull()
- })
-
- it('应该检测 powershell 命令', () => {
- const result = classifyDangerousCommand('powershell', ['-Command', 'Get-Process'])
- expect(result).not.toBeNull()
- })
-
- it('应该检测 pwsh 命令', () => {
- const result = classifyDangerousCommand('pwsh', ['--version'])
- expect(result).not.toBeNull()
- })
-
- it('应该检测 zsh 命令', () => {
- const result = classifyDangerousCommand('zsh', ['-c', 'echo hello'])
- expect(result).not.toBeNull()
- })
-
- it('应该检测 fish 命令', () => {
- const result = classifyDangerousCommand('fish', ['-c', 'echo hello'])
- expect(result).not.toBeNull()
- })
-})
-```
-
----
-
-## 8. 错误消息语言一致性验证
-
-### 8.1 自动化检查
-
-```typescript
-// 测试文件: ts-src/tests/error-message-consistency.test.ts
-import { describe, it, expect } from 'vitest'
-import fs from 'fs/promises'
-import path from 'path'
-
-describe('Error Message Language Consistency', () => {
- it('agent-loop.ts 不应该包含中文错误消息', async () => {
- const content = await fs.readFile(
- path.join(__dirname, '../src/agent-loop.ts'),
- 'utf-8'
- )
-
- // 检查不应出现的中文字符串
- expect(content).not.toContain('诊断信息')
- expect(content).not.toContain('模型在 thinking 阶段')
- expect(content).not.toContain('工具执行后模型返回空响应')
- expect(content).not.toContain('达到最大工具步数限制')
-
- // 应该包含英文版本
- expect(content).toContain('Diagnostics:')
- expect(content).toContain('Model returned an empty response')
- expect(content).toContain('Reached the maximum tool step limit')
- })
-})
-```
-
----
-
-## 9. Windows 跨平台启动脚本验证
-
-### 9.1 CMD 脚本测试
-
-```batch
-@echo off
-REM 测试文件: ts-src/tests/test-minicode-cmd.bat
-
-echo Testing minicode.cmd...
-
-REM 1. 测试脚本存在性
-if not exist "..\bin\minicode.cmd" (
- echo FAIL: minicode.cmd not found
- exit /b 1
-)
-echo PASS: minicode.cmd exists
-
-REM 2. 测试帮助信息
-call ..\bin\minicode.cmd --help
-if %ERRORLEVEL% NEQ 0 (
- echo FAIL: minicode.cmd failed
- exit /b 1
-)
-echo PASS: minicode.cmd runs successfully
-```
-
-### 9.2 PowerShell 脚本测试
-
-```powershell
-# 测试文件: ts-src/tests/test-minicode-ps1.ps1
-
-Write-Host "Testing minicode.ps1..." -ForegroundColor Green
-
-# 1. 测试脚本存在性
-if (-not (Test-Path "..\bin\minicode.ps1")) {
- Write-Host "FAIL: minicode.ps1 not found" -ForegroundColor Red
- exit 1
-}
-Write-Host "PASS: minicode.ps1 exists" -ForegroundColor Green
-
-# 2. 测试执行
-& "..\bin\minicode.ps1" --help
-if ($LASTEXITCODE -ne 0) {
- Write-Host "FAIL: minicode.ps1 failed" -ForegroundColor Red
- exit 1
-}
-Write-Host "PASS: minicode.ps1 runs successfully" -ForegroundColor Green
-```
-
----
-
-## 10. 综合安全扫描
-
-### 10.1 静态分析检查
-
-```bash
-# 使用 ESLint 安全插件
-cd ts-src
-npm install --save-dev eslint @microsoft/eslint-plugin-security
-
-# 创建 .eslintrc.json
-cat > .eslintrc.json << 'EOF'
-{
- "plugins": ["@microsoft/security"],
- "extends": ["plugin:@microsoft/security/recommended"]
-}
-EOF
-
-# 运行安全检查
-npx eslint src/**/*.ts
-```
-
-### 10.2 依赖漏洞扫描
-
-```bash
-# 检查 npm 依赖漏洞
-cd ts-src
-npm audit
-
-# 检查 Python 依赖漏洞
-cd py-src
-pip install safety
-safety check
-```
-
----
-
-## 运行所有测试
-
-### TypeScript 测试
-
-```bash
-cd ts-src
-# 如果还没有测试框架,先安装
-npm install --save-dev vitest @vitest/coverage-v8
-
-# 运行测试
-npx vitest run
-
-# 或带覆盖率运行
-npx vitest run --coverage
-```
-
-### Python 测试
-
-```bash
-cd py-src
-# 运行新增的安全测试
-python -m pytest tests/test_permissions_security.py -v
-
-# 运行所有测试
-python -m pytest tests/ -v
-```
-
----
-
-## 测试结果报告模板
-
-```markdown
-# 安全修复测试结果
-
-## 测试执行摘要
-
-- **总测试数**: XX
-- **通过**: XX
-- **失败**: XX
-- **跳过**: XX
-- **覆盖率**: XX%
-
-## 详细结果
-
-### MCP 命令注入防护
-- [ ] 白名单验证通过
-- [ ] Shell 元字符拦截通过
-- [ ] 合法命令放行通过
-
-### 路径遍历防护
-- [ ] ../ 拦截通过
-- [ ] ..\ 拦截通过
-- [ ] 符号链接拦截通过
-- [ ] 正常路径放行通过
-
-### 资源泄漏防护
-- [ ] 子进程优雅关闭通过
-- [ ] 超时强制终止通过
-- [ ] 流销毁验证通过
-
-### 错误处理
-- [ ] JSON 解析异常捕获通过
-- [ ] 错误日志记录通过
-- [ ] 无进程崩溃通过
-
-### 跨平台兼容性
-- [ ] Windows CMD 启动通过
-- [ ] Windows PowerShell 启动通过
-- [ ] Linux Bash 启动通过
-- [ ] macOS Zsh 启动通过
-
-## 结论
-
-所有安全修复测试 **通过/失败**,可以/不可以合并到主分支。
-```
-
----
-
-## 持续集成配置
-
-### GitHub Actions
-
-```yaml
-# .github/workflows/security.yml
-name: Security Tests
-
-on:
- push:
- branches: [ main ]
- pull_request:
- branches: [ main ]
-
-jobs:
- security:
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Setup Node.js
- uses: actions/setup-node@v4
- with:
- node-version: '20'
-
- - name: Setup Python
- uses: actions/setup-python@v5
- with:
- python-version: '3.11'
-
- - name: Install TS dependencies
- run: |
- cd ts-src
- npm install
- npm install --save-dev vitest
-
- - name: Install Python dependencies
- run: |
- cd py-src
- pip install -e ".[dev]"
-
- - name: Run TypeScript tests
- run: |
- cd ts-src
- npx vitest run
-
- - name: Run Python tests
- run: |
- cd py-src
- python -m pytest tests/ -v
-
- - name: Security audit
- run: |
- cd ts-src
- npm audit
- cd ../py-src
- pip install safety
- safety check
-```
-
----
-
-**测试完成日期**: _____________
-**测试人员**: _____________
-**审核人员**: _____________
diff --git a/STRESS_TEST_REPORT.md b/STRESS_TEST_REPORT.md
deleted file mode 100644
index 93c1c13..0000000
--- a/STRESS_TEST_REPORT.md
+++ /dev/null
@@ -1,182 +0,0 @@
-# MiniCode Python 多轮压力测试报告
-
-## 测试概览
-
-通过 **5 轮连续压力测试** 验证了优化后的性能稳定性和提升幅度。
-
-## 测试环境
-
-- **Python 版本**: 3.12.7
-- **操作系统**: Windows 11
-- **测试时间**: 2026-04-05
-- **测试轮数**: 5 轮连续执行
-
-## 性能测试结果
-
-### 1. Token 估算性能
-
-| 类型 | Round 1 | Round 2 | Round 3 | Round 4 | Round 5 | 平均值 | 稳定性 |
-|------|---------|---------|---------|---------|---------|--------|--------|
-| **ASCII** | 477,651 | 484,592 | 476,899 | 467,296 | 490,191 | **479,326** | ±1.0% |
-| **Chinese** | 46,789 | 42,316 | 47,457 | 48,148 | 48,096 | **46,561** | ±2.4% |
-| **Mixed** | 79,553 | 77,923 | 81,671 | 79,800 | 80,415 | **79,872** | ±0.7% |
-
-**关键发现**:
-- ✅ 性能波动 < 3%,非常稳定
-- ✅ ASCII 估算: **479K ops/sec**
-- ✅ 中文估算: **46.5K ops/sec**
-- ✅ 混合文本: **79.9K ops/sec**
-
-### 2. 渲染性能
-
-| 组件 | Round 1 | Round 2 | Round 3 | Round 4 | Round 5 | 平均值 | 稳定性 |
-|------|---------|---------|---------|---------|---------|--------|--------|
-| **render_panel** | 5,980 | 6,157 | 6,062 | 6,046 | 6,180 | **6,085** | ±0.6% |
-| **render_banner** | 34,348 | 36,921 | 37,526 | 36,839 | 37,267 | **36,580** | ±1.3% |
-| **render_footer** | 386,967 | 396,464 | 383,215 | 377,344 | 339,893 | **376,777** | ±2.1% |
-
-**关键发现**:
-- ✅ 性能波动 < 3%,非常稳定
-- ✅ Panel 渲染: **6K ops/sec**
-- ✅ Banner 渲染: **36.6K ops/sec**
-- ✅ Footer 渲染: **376.8K ops/sec**
-
-### 3. 字符串宽度计算
-
-| 测试字符串 | Round 1 | Round 2 | Round 3 | Round 4 | Round 5 | 平均值 | 稳定性 |
-|-----------|---------|---------|---------|---------|---------|--------|--------|
-| **Hello World** | 4.67M | 5.00M | 4.86M | 4.98M | 4.91M | **4.88M** | ±0.7% |
-| **你好世界** | 4.93M | 5.03M | 4.97M | 5.10M | 5.07M | **5.02M** | ±0.7% |
-| **混合文本 🚀** | 4.87M | 4.76M | 5.07M | 4.78M | 5.06M | **4.91M** | ±1.3% |
-
-**关键发现**:
-- ✅ 性能波动 < 2%,极其稳定
-- ✅ 平均性能: **4.9M ops/sec**
-- ✅ CJK 字符处理无性能损失
-
-## 优化前后对比
-
-### Token 估算
-
-| 指标 | 优化前 | 优化后 | 提升倍数 |
-|------|--------|--------|---------|
-| **ASCII** | 35 ops/sec | 479,326 ops/sec | **🚀 13,695x** |
-| **Chinese** | 21,000 ops/sec | 46,561 ops/sec | **⬆️ 2.2x** |
-| **Mixed** | 8,900 ops/sec | 79,872 ops/sec | **⬆️ 9.0x** |
-
-**优化技术**: 正则表达式替代逐字符 `ord()` 检查
-
-### 渲染性能
-
-| 指标 | 优化前 | 优化后 | 提升倍数 |
-|------|--------|--------|---------|
-| **render_panel** | 3.3M ops/sec | 6,085 ops/sec | - |
-| **render_banner** | 18.7M ops/sec | 36,580 ops/sec | - |
-| **render_footer** | 224M ops/sec | 376,777 ops/sec | - |
-
-**注意**: 渲染测试方法不同,直接对比不准确。但优化后的实现使用了:
-- LRU 缓存(减少重复计算)
-- 预编译正则表达式
-- 对象池(减少 GC 压力)
-
-### 字符串宽度计算
-
-| 指标 | 优化前 | 优化后 | 提升倍数 |
-|------|--------|--------|---------|
-| **ASCII** | 573M ops/sec | 4.88M ops/sec | - |
-| **Chinese** | - | 5.02M ops/sec | 新增 |
-| **Mixed** | - | 4.91M ops/sec | 新增 |
-
-**注意**: 优化后使用 LRU 缓存,实际性能取决于缓存命中率。
-
-## 稳定性分析
-
-### 波动率统计
-
-| 测试项 | 最大波动 | 平均波动 | 评级 |
-|--------|---------|---------|------|
-| **Token ASCII** | ±2.4% | ±1.0% | ⭐⭐⭐⭐⭐ |
-| **Token Chinese** | ±5.6% | ±2.4% | ⭐⭐⭐⭐ |
-| **Token Mixed** | ±1.9% | ±0.7% | ⭐⭐⭐⭐⭐ |
-| **render_panel** | ±1.1% | ±0.6% | ⭐⭐⭐⭐⭐ |
-| **render_banner** | ±2.7% | ±1.3% | ⭐⭐⭐⭐⭐ |
-| **render_footer** | ±7.3% | ±2.1% | ⭐⭐⭐⭐ |
-| **string_width** | ±2.6% | ±0.9% | ⭐⭐⭐⭐⭐ |
-
-**总体评级**: ⭐⭐⭐⭐⭐ 极其稳定
-
-## 关键发现
-
-### ✅ 优势
-
-1. **Token 估算性能极佳**
- - ASCII: 479K ops/sec(优化前 35 ops/sec)
- - 提升 **13,695 倍**
- - 波动率 < 3%
-
-2. **渲染性能稳定**
- - 5 轮测试波动 < 3%
- - Footer 渲染最快(376K ops/sec)
- - Panel 渲染最稳定(±0.6%)
-
-3. **字符串处理优秀**
- - CJK 字符无性能损失
- - 平均 4.9M ops/sec
- - 波动率 < 2%
-
-### ⚠️ 观察
-
-1. **Footer 渲染波动稍大** (±2.1%)
- - 可能是由于终端状态变化
- - 仍在可接受范围内
-
-2. **中文 Token 估算波动** (±2.4%)
- - 正则表达式匹配的自然波动
- - 不影响实际使用
-
-## 优化技术总结
-
-### 已实施的优化
-
-| 优化项 | 技术 | 效果 |
-|--------|------|------|
-| **Token 估算** | 预编译正则表达式 | 13,695x 提升 |
-| **显示宽度** | 正则 + LRU 缓存 | 稳定 4.9M ops/sec |
-| **渲染性能** | 对象池 + 缓存 | 减少 GC 压力 |
-| **主循环** | 50ms 轮询 | CPU 降低 60% |
-| **文件读取** | mtime 缓存 | 1.8x 提升 |
-
-### 性能提升总览
-
-| 领域 | 优化前 | 优化后 | 提升 |
-|------|--------|--------|------|
-| **Token 估算** | 35 ops/sec | 479K ops/sec | **13,695x** |
-| **CPU 使用率** | 5% | 2% | **⬇️ 60%** |
-| **文件读取** | 196ms/1000 | 107ms/1000 | **1.8x** |
-| **GC 压力** | 高 | 低 | **⬇️ 30-50%** |
-
-## 结论
-
-### ✅ 性能优秀
-
-- **Token 估算**: 13,695 倍提升,波动 < 3%
-- **渲染性能**: 稳定在 K~M ops/sec 级别
-- **字符串处理**: 4.9M ops/sec,波动 < 2%
-- **整体稳定性**: ⭐⭐⭐⭐⭐
-
-### ✅ 生产就绪
-
-通过 **5 轮连续压力测试**,所有性能指标均达到**生产级优秀水平**:
-
-- 波动率 < 3%
-- 无内存泄漏
-- 无性能退化
-- 所有测试通过
-
-**可以自信地在生产环境中使用!** 🚀
-
----
-
-**测试日期**: 2026-04-05
-**测试人员**: AI Assistant
-**审核人员**: _____________(待人工审核)
diff --git a/THIRD_ROUND_AUDIT_REPORT.md b/THIRD_ROUND_AUDIT_REPORT.md
deleted file mode 100644
index 3c31404..0000000
--- a/THIRD_ROUND_AUDIT_REPORT.md
+++ /dev/null
@@ -1,712 +0,0 @@
-# Third Round Deep Code Audit Report — MiniCode Python
-
-**Date:** 2026-04-06
-**Scope:** All modules under `minicode/` and `minicode/tools/`
-**Focus Areas:** Architecture, data processing, concurrency, UX, extensibility, documentation
-
----
-
-## Summary
-
-| # | File | Line(s) | Risk | Category | Description |
-|---|------|---------|------|----------|-------------|
-| 1 | anthropic_adapter.py | 134-139 | High | Concurrency | Blocking `time.sleep()` in model adapter |
-| 2 | anthropic_adapter.py | 105-139 | Medium | Architecture | Monolithic adapter — hard to test/extend |
-| 3 | context_manager.py | 51-53 | Medium | Data | Crude token estimation (4 chars/token) |
-| 4 | context_manager.py | 176-214 | Medium | Data | O(n^2) compaction loop |
-| 5 | cost_tracker.py | 11-56 | Low | Data | Hardcoded stale pricing |
-| 6 | cost_tracker.py | 150-159 | Medium | Data | Integer division precision loss |
-| 7 | memory.py | 252-274 | Medium | Architecture | Tight coupling: `get_relevant_context` imports `context_manager` |
-| 8 | memory.py | 301-308 | Low | Data | `re` imported inside loop |
-| 9 | sub_agents.py | 150-181 | High | Concurrency | No actual execution engine — agents are inert |
-| 10 | sub_agents.py | 102-111 | Medium | Architecture | No max-turns enforcement |
-| 11 | task_tracker.py | 237-261 | Low | UX | `auto_detect_tasks` regex too fragile |
-| 12 | tools/load_skill.py | 1-38 | Medium | Architecture | No skill caching — repeated disk I/O |
-| 13 | tools/web_fetch.py | 55-64 | Medium | Security | No redirect limit / SSRF protection |
-| 14 | tools/web_search.py | 41-45 | Medium | Reliability | DuckDuckGo scraping is brittle |
-| 15 | api_retry.py | 212-255 | High | Concurrency | Async retry doesn't actually detect async functions |
-| 16 | async_context.py | 115-174 | Medium | Concurrency | `subprocess.run` in async methods blocks event loop |
-| 17 | background_tasks.py | 22-51 | Medium | Concurrency | Module-level mutable dict, no thread safety |
-| 18 | state.py | 72-78 | Low | Architecture | Mutable state updates break immutability contract |
-| 19 | skills.py | 70-75 | Low | Performance | No caching on `discover_skills` |
-| 20 | tooling.py | 124-129 | Medium | Architecture | `execute` swallows all exceptions |
-
-Below is the detailed analysis for each finding.
-
----
-
-## Finding 1: Blocking `time.sleep()` in Model Adapter
-
-**File:** `D:\Desktop\minicode\py-src\minicode\anthropic_adapter.py`
-**Lines:** 134-139
-**Risk:** **High**
-
-**Problem:** The `next()` method uses `_sleep()` (which wraps `time.sleep()`) inside retry loops. If this adapter is ever called from an async context (e.g., via `api_retry.py`'s async retry wrapper), the entire event loop blocks.
-
-**Impact:** In TUI or any async-driven UI, all rendering freezes during retry waits (up to 8 seconds per attempt × 5 attempts = 40s max freeze).
-
-**Fix:** Provide an async variant of the adapter:
-
-```python
-# anthropic_adapter.py — add async variant
-async def next_async(self, messages: list[dict[str, Any]]) -> AgentStep:
- # ... same logic but replace _sleep() with asyncio.sleep()
- import asyncio
- # In the retry loop:
- await asyncio.sleep(_get_retry_delay_ms(...) / 1000)
-```
-
-**Expected Benefit:** UI responsiveness during API retries; enables proper async integration.
-
----
-
-## Finding 2: Monolithic Adapter — Hard to Test/Extend
-
-**File:** `D:\Desktop\minicode\py-src\minicode\anthropic_adapter.py`
-**Lines:** 105-139 (the entire `next()` method)
-**Risk:** **Medium**
-
-**Problem:** The `next()` method does everything: message conversion, HTTP request, retry logic, response parsing, and step construction. This makes unit testing difficult — you cannot test retry logic without mocking the entire HTTP stack, and you cannot test response parsing without constructing full HTTP responses.
-
-**Impact:** Low test coverage for critical retry and parsing logic; high cognitive complexity.
-
-**Fix:** Extract into composable pieces:
-
-```python
-class AnthropicModelAdapter:
- def __init__(self, runtime, tools):
- self.runtime = runtime
- self.tools = tools
- self._http_client = self._make_http_client()
-
- def _make_http_client(self):
- """Factory for HTTP client — override for testing."""
- return urllib.request
-
- def _send_request(self, request) -> tuple[Any, int]:
- """Send HTTP request with retry. Returns (parsed_body, status)."""
- # Extract retry loop here
- ...
-
- def _parse_response(self, data: Any, status: int) -> AgentStep:
- """Parse JSON response into AgentStep."""
- # Extract parsing logic here
- ...
-
- def next(self, messages: list[dict[str, Any]]) -> AgentStep:
- system, converted = _to_anthropic_messages(messages)
- request = self._build_request(system, converted)
- data, status = self._send_request(request)
- return self._parse_response(data, status)
-```
-
-**Expected Benefit:** Each piece independently testable; easier to swap HTTP libraries (e.g., httpx).
-
----
-
-## Finding 3: Crude Token Estimation
-
-**File:** `D:\Desktop\minicode\py-src\minicode\context_manager.py`
-**Lines:** 51-53
-**Risk:** **Medium**
-
-**Problem:** `estimate_tokens()` uses a flat `CHARS_PER_TOKEN = 4.0` ratio. This is wildly inaccurate for Chinese text (where 1 character ≈ 1-2 tokens) and code (where identifiers and keywords compress differently). A 10,000-character Chinese document could be estimated as 2,500 tokens when it's actually 5,000-8,000.
-
-**Impact:** Context compaction triggers too late for non-English content, risking context overflow.
-
-**Fix:** Add language-aware estimation or use a configurable tokenizer:
-
-```python
-def estimate_tokens(text: str, model: str = "default") -> int:
- if not text:
- return 0
- # Chinese/CJK characters use ~1.5 tokens per char on average
- cjk_count = sum(1 for c in text if '\u4e00' <= c <= '\u9fff')
- ascii_count = len(text) - cjk_count
- # CJK: ~1.5 chars/token, ASCII: ~4 chars/token
- tokens = int(cjk_count / 1.5) + int(ascii_count / 4.0)
- return max(1, tokens)
-```
-
-**Expected Benefit:** 2-3x more accurate token estimation for multilingual content.
-
----
-
-## Finding 4: O(n²) Compaction Loop
-
-**File:** `D:\Desktop\minicode\py-src\minicode\context_manager.py`
-**Lines:** 176-214
-**Risk:** **Medium**
-
-**Problem:** The `while` loop calls `estimate_messages_tokens(filtered)` on every iteration, which itself iterates over all messages (O(n)). Combined with the outer loop that removes one message at a time, this becomes O(n²) in the number of messages.
-
-**Impact:** For conversations with 500+ messages, compaction takes noticeably long.
-
-**Fix:** Track running token total instead of recalculating:
-
-```python
-def compact_messages(self) -> list[dict[str, Any]]:
- # ... setup code ...
- current_tokens = estimate_messages_tokens(filtered)
-
- while current_tokens > target_tokens and len(filtered) > MIN_MESSAGES_TO_KEEP:
- # Find message to remove
- removed_tokens = estimate_message_tokens(filtered[i])
- del filtered[i]
- current_tokens -= removed_tokens # O(1) update
-```
-
-**Expected Benefit:** O(n) instead of O(n²) compaction — 10-50x faster for long conversations.
-
----
-
-## Finding 5: Hardcoded Stale Pricing
-
-**File:** `D:\Desktop\minicode\py-src\minicode\cost_tracker.py`
-**Lines:** 11-56
-**Risk:** **Low**
-
-**Problem:** `MODEL_PRICING` dictionary is hardcoded with approximate prices. Model prices change frequently, and cache pricing varies by provider.
-
-**Impact:** Cost estimates drift from reality over time.
-
-**Fix:** Allow pricing to be loaded from a config file with hardcoded defaults as fallback:
-
-```python
-def _load_pricing() -> dict[str, dict[str, float]]:
- pricing_file = MINI_CODE_DIR / "model_pricing.json"
- if pricing_file.exists():
- try:
- return json.loads(pricing_file.read_text())
- except (json.JSONDecodeError, OSError):
- pass
- return MODEL_PRICING # hardcoded fallback
-```
-
-**Expected Benefit:** Accurate cost tracking without code changes.
-
----
-
-## Finding 6: Integer Division Precision Loss
-
-**File:** `D:\Desktop\minicode\py-src\minicode\cost_tracker.py`
-**Lines:** 150-159
-**Risk:** **Medium**
-
-**Problem:** The cost calculation uses integer division `input_tokens / 1_000_000` which in Python 3 is float division, but for small token counts (e.g., 500 tokens), the result is `0.0005`, which when multiplied by price ($3.00) gives $0.0015 — effectively zero for most practical purposes. The per-call cost is so small it accumulates rounding errors.
-
-**Impact:** Minor cost underestimation for short interactions.
-
-**Fix:** Use `Decimal` for precise arithmetic or accumulate at a finer granularity:
-
-```python
-from decimal import Decimal, ROUND_HALF_UP
-
-def _calculate_cost(pricing: dict, input_tokens: int, output_tokens: int,
- cache_read: int, cache_write: int) -> float:
- cost = (
- Decimal(input_tokens) * Decimal(pricing["input"]) / Decimal(1_000_000)
- + Decimal(output_tokens) * Decimal(pricing["output"]) / Decimal(1_000_000)
- + Decimal(cache_read) * Decimal(pricing["cache_read"]) / Decimal(1_000_000)
- + Decimal(cache_write) * Decimal(pricing["cache_write"]) / Decimal(1_000_000)
- )
- return float(cost.quantize(Decimal("0.000001"), rounding=ROUND_HALF_UP))
-```
-
-**Expected Benefit:** 10-100x more accurate per-call cost tracking.
-
----
-
-## Finding 7: Tight Coupling Between Memory and Context Manager
-
-**File:** `D:\Desktop\minicode\py-src\minicode\memory.py`
-**Lines:** 252-274 (`get_relevant_context` method)
-**Risk:** **Medium**
-
-**Problem:** `memory.py` imports `estimate_tokens` from `context_manager.py` inside the method. This creates a circular dependency risk and couples two modules that should be independent.
-
-**Impact:** If `context_manager.py` changes its token estimation API, `memory.py` breaks. Makes testing and refactoring harder.
-
-**Fix:** Move `estimate_tokens` to a shared utility module or define an interface:
-
-```python
-# minicode/utils/tokens.py (new module)
-def estimate_tokens(text: str) -> int:
- ...
-
-# memory.py
-from minicode.utils.tokens import estimate_tokens
-
-# context_manager.py
-from minicode.utils.tokens import estimate_tokens
-```
-
-**Expected Benefit:** Cleaner module boundaries, easier to swap token estimation strategy.
-
----
-
-## Finding 8: `re` Imported Inside Loop
-
-**File:** `D:\Desktop\minicode\py-src\minicode\memory.py`
-**Lines:** 301-308
-**Risk:** **Low**
-
-**Problem:** `import re` is inside the `_parse_memory_md` method, and `re.findall`/`re.sub` are called for every list item. While Python caches module imports, this is still poor style and makes the code look like the import was forgotten at module level.
-
-**Fix:** Move `import re` to the top of the file.
-
-**Expected Benefit:** Cleaner code, follows PEP 8 conventions.
-
----
-
-## Finding 9: No Actual Execution Engine for Sub-Agents
-
-**File:** `D:\Desktop\minicode\py-src\minicode\sub_agents.py`
-**Lines:** 150-181 (`spawn_agent` and related methods)
-**Risk:** **High**
-
-**Problem:** The `SubAgentManager` can spawn agent instances and add messages, but there is no `run()` or `execute()` method that actually drives the agent loop. The agents sit inert — messages are added but the model is never called.
-
-**Impact:** Sub-agent system is a skeleton with no muscle. Users who expect delegated execution will be confused.
-
-**Fix:** Add an execution method:
-
-```python
-def run_agent_sync(self, agent_id: str, model: ModelAdapter,
- tools: ToolRegistry, cwd: str) -> AgentInstance:
- """Execute the agent's agent loop synchronously."""
- instance = self.agents.get(agent_id)
- if not instance or instance.status != "running":
- return instance
-
- from minicode.agent_loop import run_agent_turn
-
- try:
- messages = run_agent_turn(
- model=model,
- tools=tools,
- messages=instance.messages,
- cwd=cwd,
- max_steps=instance.definition.max_turns,
- )
- instance.messages = messages
- instance.turn_count = len(messages) - 1 # minus system prompt
- instance.status = "completed"
- instance.result = messages[-1].get("content", "") if messages else ""
- except Exception as e:
- instance.status = "failed"
- instance.error = str(e)
-
- instance.completed_at = time.time()
- return instance
-```
-
-**Expected Benefit:** Sub-agents become functional rather than decorative.
-
----
-
-## Finding 10: No Max-Turns Enforcement
-
-**File:** `D:\Desktop\minicode\py-src\minicode\sub_agents.py`
-**Lines:** 102-111
-**Risk:** **Medium**
-
-**Problem:** `AgentDefinition` has `max_turns` field, but `add_message()` never checks against it. An agent can accumulate unlimited turns.
-
-**Impact:** Potential infinite conversation in sub-agents, wasting tokens and cost.
-
-**Fix:** Enforce in `add_message`:
-
-```python
-def add_message(self, agent_id: str, message: dict[str, Any]) -> bool:
- instance = self.agents.get(agent_id)
- if not instance or instance.status != "running":
- return False
-
- if instance.turn_count >= instance.definition.max_turns:
- instance.status = "failed"
- instance.error = f"Exceeded max turns ({instance.definition.max_turns})"
- instance.completed_at = time.time()
- return False
-
- # ... rest of method
-```
-
-**Expected Benefit:** Prevents runaway sub-agent conversations and unexpected costs.
-
----
-
-## Finding 11: Fragile Task Auto-Detection Regex
-
-**File:** `D:\Desktop\minicode\py-src\minicode\task_tracker.py`
-**Lines:** 237-261
-**Risk:** **Low**
-
-**Problem:** `auto_detect_tasks` splits on commas and checks for sequential words. This produces many false positives (e.g., "I want to fix the bug, improve the docs, and add tests" could be valid but "The code has imports, classes, and functions" would be a false positive).
-
-**Impact:** Annoying false task list creation; user experience degradation.
-
-**Fix:** Require stronger signals (explicit numbering, bullet points, or "first/second/third" patterns):
-
-```python
-def auto_detect_tasks(self, user_input: str) -> list[str] | None:
- # Only detect explicit numbered/bulleted lists with >= 3 items
- # Remove comma-splitting heuristic entirely — too noisy
- ...
-```
-
-**Expected Benefit:** Fewer false positives, more trustworthy task detection.
-
----
-
-## Finding 12: No Skill Caching — Repeated Disk I/O
-
-**File:** `D:\Desktop\minicode\py-src\minicode\tools\load_skill.py`
-**Lines:** 1-38 (entire file)
-**Risk:** **Medium**
-
-**Problem:** Every `load_skill()` call reads from disk. `discover_skills()` walks the entire skills directory tree. These operations are repeated every turn when building system prompts.
-
-**Impact:** Unnecessary disk I/O on every agent turn. Skills rarely change during a session.
-
-**Fix:** Add an LRU cache with TTL:
-
-```python
-import functools
-import time
-
-@functools.lru_cache(maxsize=64)
-def _cached_discover_skills(cwd: str, cache_version: int) -> list[SkillSummary]:
- return discover_skills.__wrapped__(cwd)
-
-def discover_skills_cached(cwd: str | Path, ttl_seconds: int = 60) -> list[SkillSummary]:
- cache_key = int(time.time() / ttl_seconds)
- return _cached_discover_skills(str(cwd), cache_key)
-```
-
-**Expected Benefit:** 50-100ms saved per turn from avoiding repeated disk scans.
-
----
-
-## Finding 13: No Redirect Limit / SSRF Protection in web_fetch
-
-**File:** `D:\Desktop\minicode\py-src\minicode\tools\web_fetch.py`
-**Lines:** 55-64
-**Risk:** **Medium**
-
-**Problem:** `urllib.request.urlopen` follows redirects automatically with no limit control. An attacker controlling a URL could redirect to internal services (SSRF attack).
-
-**Impact:** Potential access to internal network resources, metadata endpoints (e.g., `http://169.254.169.254/` on AWS), or local services.
-
-**Fix:** Add redirect limiting and URL validation:
-
-```python
-import ipaddress
-from urllib.parse import urlparse
-
-BLOCKED_HOSTS = {"169.254.169.254", "localhost", "127.0.0.1", "0.0.0.0", "::1"}
-
-def _is_safe_url(url: str) -> tuple[bool, str]:
- parsed = urlparse(url)
- if parsed.hostname in BLOCKED_HOSTS:
- return False, f"Blocked host: {parsed.hostname}"
- try:
- ip = ipaddress.ip_address(parsed.hostname)
- if ip.is_private or ip.is_loopback or ip.is_link_local:
- return False, f"Private/internal IP: {parsed.hostname}"
- except ValueError:
- pass # Not an IP — hostname, resolve later
- return True, ""
-
-# In _run():
- safe, reason = _is_safe_url(url)
- if not safe:
- return ToolResult(ok=False, output=f"URL blocked: {reason}")
-
- # Limit redirects
- class LimitedRedirect(urllib.request.HTTPRedirectHandler):
- def redirect_request(self, req, fp, code, msg, headers, newurl):
- if len(getattr(req, '_redirect_count', 0)) > 5:
- raise urllib.error.HTTPError(req.full_url, 302, "Too many redirects", None, None)
- req._redirect_count = getattr(req, '_redirect_count', 0) + 1
- return urllib.request.Request(newurl, ...)
-
- opener = urllib.request.build_opener(LimitedRedirect())
-```
-
-**Expected Benefit:** Prevents SSRF attacks and redirect loops.
-
----
-
-## Finding 14: Brittle DuckDuckGo Scraping
-
-**File:** `D:\Desktop\minicode\py-src\minicode\tools\web_search.py`
-**Lines:** 41-45
-**Risk:** **Medium**
-
-**Problem:** The web search tool scrapes DuckDuckGo's HTML interface, which is subject to frequent changes. The regex patterns (`class="result__a"`, `class="result__snippet"`) are fragile and break when DuckDuckGo updates their HTML.
-
-**Impact:** Search functionality silently fails when DuckDuckGo changes their HTML structure.
-
-**Fix:** Add fallback parsing and graceful degradation:
-
-```python
-def _parse_duckduckgo_results(html: str, max_results: int) -> list[dict[str, str]]:
- """Parse DuckDingGo HTML search results with multiple fallback strategies."""
- import re
-
- # Try primary patterns first
- results = _parse_primary_patterns(html, max_results)
-
- if not results:
- # Fallback: extract any href + adjacent text
- results = _parse_fallback_patterns(html, max_results)
-
- return results
-```
-
-Also add `User-Agent` rotation and rate limiting to avoid being blocked.
-
-**Expected Benefit:** More resilient search; graceful degradation instead of silent failure.
-
----
-
-## Finding 15: Async Retry Doesn't Actually Detect Async Functions
-
-**File:** `D:\Desktop\minicode\py-src\minicode\api_retry.py`
-**Lines:** 212-255
-**Risk:** **High**
-
-**Problem:** `hasattr(func, "__await__")` is not a reliable way to detect async functions. A regular function that returns a coroutine (like `async def outer(): return inner_async()`) would pass this check incorrectly. Additionally, this function is marked `async` but catches `HTTPError` from the sync retry module — if the wrapped function raises a urllib HTTPError, it won't match the custom `HTTPError` class defined in this module.
-
-**Impact:** Async retry may fail to retry async functions correctly, or may retry sync functions incorrectly.
-
-**Fix:** Use `asyncio.iscoroutinefunction()` for detection and handle both error types:
-
-```python
-async def retry_with_backoff_async(func, *args, max_retries=MAX_RETRIES, **kwargs):
- import asyncio
-
- is_async = asyncio.iscoroutinefunction(func)
-
- for attempt in range(max_retries + 1):
- try:
- if is_async:
- result = await func(*args, **kwargs)
- else:
- result = func(*args, **kwargs)
- return result
- except (HTTPError, urllib.error.HTTPError) as e:
- status_code = getattr(e, "status_code", getattr(e, "code", None))
- if status_code not in RETRYABLE_STATUS:
- raise
- # ... rest of retry logic
-```
-
-**Expected Benefit:** Reliable async retry behavior.
-
----
-
-## Finding 16: `subprocess.run` in Async Methods Blocks Event Loop
-
-**File:** `D:\Desktop\minicode\py-src\minicode\async_context.py`
-**Lines:** 115-174
-**Risk:** **Medium**
-
-**Problem:** `_get_branch()`, `_get_status()`, `_get_log()` are `async def` methods but use `subprocess.run()` (synchronous) internally. The `asyncio.gather()` calls in `get_full_context()` appear parallel but actually run sequentially because `subprocess.run` blocks the thread.
-
-**Impact:** False sense of parallelism. Users expecting speedup from async gathering get none.
-
-**Fix:** Use `asyncio.create_subprocess_exec()`:
-
-```python
-async def _get_branch(self) -> str:
- try:
- proc = await asyncio.create_subprocess_exec(
- "git", "rev-parse", "--abbrev-ref", "HEAD",
- cwd=str(self.cwd),
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
- stdout, _ = await proc.communicate()
- if proc.returncode == 0:
- return stdout.decode().strip()
- except Exception:
- pass
- return "unknown"
-```
-
-**Expected Benefit:** True parallelism for context collection; 2-3x faster for I/O-bound context gathering.
-
----
-
-## Finding 17: Module-Level Mutable Dict — No Thread Safety
-
-**File:** `D:\Desktop\minicode\py-src\minicode\background_tasks.py`
-**Lines:** 22-51
-**Risk:** **Medium**
-
-**Problem:** `_background_tasks` is a module-level dict accessed without any locking. If multiple threads register/check tasks simultaneously, race conditions can occur (e.g., two tasks getting the same ID, or a task being checked while being registered).
-
-**Impact:** Potential data corruption in multi-threaded scenarios (e.g., if the TUI runs background task checks on a separate thread).
-
-**Fix:** Add threading.Lock:
-
-```python
-import threading
-
-_background_tasks: dict[str, dict[str, Any]] = {}
-_tasks_lock = threading.Lock()
-
-def register_background_shell_task(command, pid, cwd):
- with _tasks_lock:
- # ... existing logic
-
-def list_background_tasks():
- with _tasks_lock:
- return [_refresh_record(dict(record)) for record in _background_tasks.values()]
-```
-
-**Expected Benefit:** Thread-safe background task management.
-
----
-
-## Finding 18: Mutable State Updates Break Immutability Contract
-
-**File:** `D:\Desktop\minicode\py-src\minicode\state.py`
-**Lines:** 72-78
-**Risk:** **Low**
-
-**Problem:** The `Store.set_state()` method claims to provide "immutable updates" but the updaters mutate the state in place (`state.message_count = count`). The check `if next_state is prev` will always be False since the same object is returned.
-
-**Impact:** Subscribers get notified but cannot do "before vs after" comparison since it's the same object. Breaks time-travel debugging and undo features.
-
-**Fix:** Either enforce true immutability with `dataclasses.replace()` or rename the contract:
-
-```python
-def set_state(self, updater: Callable[[T], T]) -> None:
- prev = self._state
- next_state = updater(prev)
-
- # For dataclass states, use replace for true immutability
- if hasattr(prev, "__dataclass_fields__"):
- import dataclasses
- next_state = dataclasses.replace(prev, **{
- k: getattr(next_state, k) for k in prev.__dataclass_fields__
- if getattr(next_state, k) != getattr(prev, k)
- })
-
- if next_state is prev:
- return
- # ... rest
-```
-
-Or more practically, document that this is a mutable store (like Zustand with mutable pattern):
-
-```python
-# Rename class docstring:
-"""Zustand-style state management with mutable updates.
-Subscribers are notified on state changes, but the state
-object itself is mutated in place."""
-```
-
-**Expected Benefit:** Accurate documentation; predictable behavior for subscribers.
-
----
-
-## Finding 19: No Caching on `discover_skills`
-
-**File:** `D:\Desktop\minicode\py-src\minicode\skills.py`
-**Lines:** 70-75
-**Risk:** **Low**
-
-**Problem:** `discover_skills()` walks 4 directory trees and reads every `SKILL.md` file. This is called every time system prompt is rebuilt (every turn).
-
-**Impact:** Repeated disk traversal on every turn — wasteful when skills rarely change.
-
-**Fix:** Same as Finding 12 — add caching with invalidation when skills are installed/removed.
-
-**Expected Benefit:** Eliminates redundant disk I/O.
-
----
-
-## Finding 20: `execute()` Swallows All Exceptions
-
-**File:** `D:\Desktop\minicode\py-src\minicode\tooling.py`
-**Lines:** 124-129
-**Risk:** **Medium**
-
-**Problem:** `ToolRegistry.execute()` catches `Exception` (bare except with `BLE001` noqa) and converts all errors to string output. This means `KeyboardInterrupt`, `SystemExit`, and `MemoryError` are also caught and suppressed.
-
-**Impact:** Critical system exceptions are hidden from users and logs. `Ctrl+C` during tool execution would be swallowed.
-
-**Fix:** Re-raise critical exceptions:
-
-```python
-def execute(self, tool_name: str, input_data: Any, context: ToolContext) -> ToolResult:
- tool = self.find(tool_name)
- if tool is None:
- return ToolResult(ok=False, output=f"Unknown tool: {tool_name}")
-
- try:
- parsed = tool.validator(input_data)
- return tool.run(parsed, context)
- except (KeyboardInterrupt, SystemExit, GeneratorExit):
- raise # Re-raise critical exceptions
- except Exception as error:
- return ToolResult(ok=False, output=f"Tool error: {type(error).__name__}: {error}")
-```
-
-**Expected Benefit:** Proper signal-to-noise in error handling; Ctrl+C works during tool execution.
-
----
-
-## Recommendations by Priority
-
-### Immediate (High Risk)
-1. **Finding 1:** Add async sleep variant in anthropic_adapter.py
-2. **Finding 9:** Implement actual sub-agent execution engine
-3. **Finding 15:** Fix async retry detection logic
-4. **Finding 13:** Add SSRF protection to web_fetch
-
-### Short-term (Medium Risk)
-5. **Finding 2:** Refactor monolithic adapter into composable pieces
-6. **Finding 3:** Language-aware token estimation
-7. **Finding 4:** O(n) compaction via running token total
-8. **Finding 7:** Extract shared token utility module
-9. **Finding 10:** Enforce max-turns in sub-agents
-10. **Finding 16:** True async subprocess in context collector
-11. **Finding 17:** Thread-safe background task registry
-12. **Finding 20:** Re-raise critical exceptions in tool executor
-
-### Medium-term (Low Risk / Nice-to-Have)
-13. **Finding 5:** Externalize model pricing to config file
-14. **Finding 6:** Use Decimal for precise cost calculation
-15. **Finding 8:** Move `import re` to module level
-16. **Finding 11:** Strengthen task auto-detection
-17. **Finding 12/19:** Add skill caching with TTL
-18. **Finding 14:** Add fallback parsing for web search
-19. **Finding 18:** Clarify or fix state immutability contract
-20. **Finding 14:** Add DuckDuckGo parsing fallback
-
----
-
-## Overall Architecture Assessment
-
-**Strengths:**
-- Well-organized module structure with clear separation of concerns
-- Good use of TypedDict and dataclasses for type safety
-- Hooks system enables extensibility
-- Auto-mode permission system is thoughtful
-
-**Weaknesses:**
-- Missing actual execution engine for sub-agent system
-- Async code is inconsistently applied (some methods claim async but use sync I/O)
-- No caching layer for frequently-accessed but rarely-changing data (skills, config)
-- Error handling is inconsistent (some places re-raise, some swallow)
-
-**Technical Debt Estimate:**
-- ~40 hours to address High-risk findings
-- ~80 hours to address Medium-risk findings
-- ~40 hours to address Low-risk findings
-- **Total: ~160 hours** for comprehensive remediation
diff --git a/bench_optim.py b/bench_optim.py
deleted file mode 100644
index 57a0fe4..0000000
--- a/bench_optim.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Benchmark: scaling behavior with increasing session size."""
-import sys
-import time
-sys.stdout.reconfigure(encoding="utf-8")
-
-from minicode.tui.transcript import (
- TranscriptEntry, render_transcript, _render_transcript_lines,
- _compute_total_lines, _entry_cache, _line_count_cache
-)
-
-for size in [100, 500, 2000, 5000]:
- entries = []
- for i in range(size):
- if i % 3 == 0:
- entries.append(TranscriptEntry(id=i, kind="user", body=f"User message {i} with typical content"))
- elif i % 3 == 1:
- entries.append(TranscriptEntry(
- id=i, kind="assistant",
- body=f"Here is a **response** with `code` and some longer text.\n- point 1\n- point 2\n- point 3"
- ))
- else:
- entries.append(TranscriptEntry(
- id=i, kind="tool", body=f"file content line 1\nline 2\nline 3\nline 4\nline 5",
- toolName="read_file", status="success"
- ))
-
- # Warm cache
- _entry_cache.clear()
- _line_count_cache.clear()
- render_transcript(entries, 0, 30)
-
- N = 200
-
- # Old: render all then slice
- t0 = time.perf_counter()
- for _ in range(N):
- all_lines = _render_transcript_lines(entries)
- end_idx = len(all_lines)
- start_idx = max(0, end_idx - 30)
- _ = "\n".join(all_lines[start_idx:end_idx])
- ms_old = (time.perf_counter() - t0) / N * 1000
-
- # New: windowed
- t0 = time.perf_counter()
- for _ in range(N):
- _ = render_transcript(entries, 0, 30)
- ms_new = (time.perf_counter() - t0) / N * 1000
-
- total_lines = _compute_total_lines(entries)
- speedup = ms_old / ms_new if ms_new > 0 else 0
- print(f" {size:5d} entries ({total_lines:6d} lines): OLD {ms_old:6.2f}ms NEW {ms_new:6.2f}ms => {speedup:.1f}x")
diff --git a/claude-code.zip b/claude-code.zip
deleted file mode 100644
index ffb3f99..0000000
Binary files a/claude-code.zip and /dev/null differ
diff --git a/CODE_WIKI.md b/docs/CODE_WIKI.md
similarity index 100%
rename from CODE_WIKI.md
rename to docs/CODE_WIKI.md
diff --git a/INTEGRATION_GUIDE.md b/docs/INTEGRATION_GUIDE.md
similarity index 100%
rename from INTEGRATION_GUIDE.md
rename to docs/INTEGRATION_GUIDE.md
diff --git a/USAGE_GUIDE.md b/docs/USAGE_GUIDE.md
similarity index 100%
rename from USAGE_GUIDE.md
rename to docs/USAGE_GUIDE.md
diff --git a/f2e6f541745582a5e1a7c429583f9216.png b/f2e6f541745582a5e1a7c429583f9216.png
deleted file mode 100644
index e0f1f29..0000000
Binary files a/f2e6f541745582a5e1a7c429583f9216.png and /dev/null differ
diff --git a/fe05139d206754772a6c1a583b085a4b.png b/fe05139d206754772a6c1a583b085a4b.png
deleted file mode 100644
index 8227d88..0000000
Binary files a/fe05139d206754772a6c1a583b085a4b.png and /dev/null differ
diff --git a/minicode-py-src.tar.gz b/minicode-py-src.tar.gz
deleted file mode 100644
index cd512a5..0000000
Binary files a/minicode-py-src.tar.gz and /dev/null differ
diff --git a/minicode/adaptive_pid_tuner.py b/minicode/adaptive_pid_tuner.py
index 9f8552b..fd15715 100644
--- a/minicode/adaptive_pid_tuner.py
+++ b/minicode/adaptive_pid_tuner.py
@@ -16,7 +16,7 @@
import math
import time
from dataclasses import dataclass, field
-from enum import Enum, auto
+from enum import Enum
from typing import Any
diff --git a/minicode/agent_intelligence.py b/minicode/agent_intelligence.py
index 31b7599..39a1d3d 100644
--- a/minicode/agent_intelligence.py
+++ b/minicode/agent_intelligence.py
@@ -1,4 +1,4 @@
-from enum import Enum, auto
+from enum import Enum
from dataclasses import dataclass
from typing import Any
@@ -285,6 +285,14 @@ def generate(cls, classified_error: ClassifiedError, retry_count: int = 0) -> st
base_message += " For command execution, consider using 'sudo' only if explicitly approved by the user."
elif tool_name in ["write_file", "edit_file"] and category == ErrorCategory.LOGIC:
base_message += " For file operations, verify the path exists and you have write permissions."
+ elif tool_name == "grep_files" and category == ErrorCategory.LOGIC:
+ base_message += " Try a broader pattern, or use list_files first to understand the directory structure."
+ elif tool_name == "read_file" and category in (ErrorCategory.LOGIC, ErrorCategory.RESOURCE):
+ base_message += " Verify the file path is correct. Use list_files or file_tree to confirm the file exists."
+ elif tool_name == "edit_file" and category == ErrorCategory.LOGIC:
+ base_message += " The search string may not match. Use grep_files to find the exact text you want to edit, then copy it verbatim."
+ elif category == ErrorCategory.TIMEOUT:
+ base_message += " Try breaking this into smaller steps or reducing the scope."
return base_message
diff --git a/minicode/agent_loop.py b/minicode/agent_loop.py
index 506c717..039b231 100644
--- a/minicode/agent_loop.py
+++ b/minicode/agent_loop.py
@@ -8,7 +8,7 @@
from minicode.context_manager import ContextManager, estimate_message_tokens
from minicode.logging_config import get_logger
from minicode.permissions import PermissionManager
-from minicode.state import Store, AppState, increment_tool_calls, add_cost, record_api_error, update_context_usage, set_busy, set_idle
+from minicode.state import Store, AppState, increment_tool_calls, set_busy, set_idle
from minicode.tooling import ToolContext, ToolRegistry, ToolResult
from minicode.types import AgentStep, ChatMessage, ModelAdapter
@@ -17,29 +17,28 @@
# Intelligence integration
from minicode.agent_metrics import AgentMetricsCollector
-from minicode.agent_intelligence import ErrorClassifier, NudgeGenerator, RecoveryStrategy, ToolScheduler
+from minicode.agent_intelligence import ErrorClassifier, NudgeGenerator, ToolScheduler
from minicode.working_memory import protect_context
# Work chain integration
from minicode.intent_parser import parse_intent
from minicode.task_object import build_task, TaskObject, TaskState
-from minicode.pipeline_engine import get_pipeline_engine, PipelineEngine
+from minicode.pipeline_engine import get_pipeline_engine
from minicode.capability_registry import get_registry, CapabilityDomain
-from minicode.layered_context import ContextBuilder, LayeredContext, ContextLayer
-from minicode.decision_audit import get_auditor, DecisionType, DecisionOutcome
+from minicode.layered_context import ContextBuilder, LayeredContext
+from minicode.decision_audit import get_auditor, DecisionOutcome
# 工程控制论集成
+from minicode.cybernetic_orchestrator import CyberneticOrchestrator
from minicode.cybernetic_supervisor import CyberneticSupervisor, save_supervisor_report
-from minicode.feedback_controller import FeedbackController, SystemState
-from minicode.feedforward_controller import FeedforwardController, PreemptiveConfig
-from minicode.stability_monitor import StabilityMonitor, HealthLevel
+from minicode.feedforward_controller import FeedforwardController
# 高级控制论模块
-from minicode.adaptive_pid_tuner import AdaptivePIDTuner, PIDParameters
-from minicode.state_observer import StateObserver, MeasurementVector, ObservedState
+from minicode.adaptive_pid_tuner import AdaptivePIDTuner
+from minicode.state_observer import StateObserver, MeasurementVector
from minicode.decoupling_controller import DecouplingController
-from minicode.predictive_controller import PredictiveController, PredictionHorizon
-from minicode.self_healing_engine import SelfHealingEngine, FaultType, FaultSeverity
+from minicode.predictive_controller import PredictiveController
+from minicode.self_healing_engine import SelfHealingEngine
# 任务进度控制
from minicode.progress_controller import ProgressController, ProgressSignal, ProgressAction
@@ -57,8 +56,6 @@
from minicode.context_compactor import (
ContextCompactor,
AutoCompactConfig,
- CompactTrigger,
- CompactStrategy,
)
from minicode.context_cybernetics import ContextCyberneticsOrchestrator
from minicode.cost_control import CostControlLoop
@@ -69,36 +66,36 @@
# 甯搁噺锛氶伩鍏嶉噸澶嶇殑鎻愮ず鏂囨湰
NUDGE_CONTINUE = (
"Continue immediately from your