使用符号链接组织 AI 编码助手技能的综合指南,以实现更好的项目结构和兼容性。
目录
为什么要使用符号链接?
问题
许多 AI 编码助手(Claude Code, Cursor, GitHub Copilot)会在不同位置查找特定于项目的指令:
- 有的使用
.ai-rules/ - 有的使用
.agent/ - 有的使用
.cursor/ - 有的使用自定义目录
在多个目录中管理相同的技能会导致:
- ❌ 内容重复
- ❌ 同步问题
- ❌ 维护开销
解决方案
使用符号链接来创建单一事实来源 (Single Source of Truth):
project/
├── .ai-rules/ ← 源 (单一事实来源)
│ ├── skill-1.md
│ └── skill-2.md
│
└── .agent/
└── skills/ ← 符号链接 → ../.ai-rules
├── skill-1.md (通过链接访问)
└── skill-2.md (通过链接访问)
优势:
- ✅ 无重复
- ✅ 仅维护一个位置
- ✅ 兼容多种工具
- ✅ 易于更新
项目结构
设置前
my-todo-app/
├── src/
├── tests/
├── package.json
└── .ai-rules/ ← 你的技能目录
├── README.md
├── api-development.md
├── testing-guide.md
└── ui-patterns.md
设置后
my-todo-app/
├── src/
├── tests/
├── package.json
├── .ai-rules/ ← 原始文件
│ ├── README.md
│ ├── api-development.md
│ ├── testing-guide.md
│ └── ui-patterns.md
│
├── .agent/
│ └── skills/ ← 符号链接
│ ├── README.md (链接)
│ ├── api-development.md (链接)
│ ├── testing-guide.md (链接)
│ └── ui-patterns.md (链接)
│
├── setup-skills-link.ps1 ← 设置脚本
└── setup-skills-link.bat ← 替代脚本
设置脚本
PowerShell 脚本 (推荐)
创建 setup-skills-link.ps1:
# AI 技能符号链接设置
Write-Host "正在设置 AI 技能符号链接..." -ForegroundColor Cyan
# 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host "错误: 请以管理员身份运行" -ForegroundColor Red
Read-Host "按回车键退出"
exit 1
}
# 获取路径
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$sourceDir = Join-Path $scriptPath ".ai-rules"
$targetParent = Join-Path $scriptPath ".agent"
$targetLink = Join-Path $targetParent "skills"
# 验证源是否存在
if (-not (Test-Path $sourceDir)) {
Write-Host "错误: 未找到 .ai-rules 目录" -ForegroundColor Red
exit 1
}
# 如果需要,创建 .agent 目录
if (-not (Test-Path $targetParent)) {
New-Item -ItemType Directory -Path $targetParent | Out-Null
}
# 如果存在现有链接则移除
if (Test-Path $targetLink) {
$item = Get-Item $targetLink -Force
if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
Remove-Item $targetLink -Force
} else {
Write-Host "错误: $targetLink 存在但不是符号链接" -ForegroundColor Red
exit 1
}
}
# 创建符号链接
try {
New-Item -ItemType SymbolicLink -Path $targetLink -Target $sourceDir | Out-Null
Write-Host "成功: 符号链接已创建!" -ForegroundColor Green
Write-Host " .agent/skills -> .ai-rules" -ForegroundColor Gray
} catch {
Write-Host "错误: 创建链接失败: $_" -ForegroundColor Red
Write-Host "提示: 请在 Windows 设置中启用开发者模式" -ForegroundColor Yellow
exit 1
}
Read-Host "按回车键退出"
Batch 脚本替代方案
创建 setup-skills-link.bat:
@echo off
echo 正在设置 AI 技能符号链接...
net session >nul 2>&1
if %errorLevel% neq 0 (
echo 错误: 请以管理员身份运行
pause
exit /b 1
)
set "SOURCE_DIR=%~dp0.ai-rules"
set "TARGET_PARENT=%~dp0.agent"
set "TARGET_LINK=%TARGET_PARENT%\skills"
if not exist "%SOURCE_DIR%" (
echo 错误: 未找到 .ai-rules 目录
pause
exit /b 1
)
if not exist "%TARGET_PARENT%" (
mkdir "%TARGET_PARENT%"
)
if exist "%TARGET_LINK%" (
rmdir "%TARGET_LINK%" 2>nul
)
mklink /D "%TARGET_LINK%" "%SOURCE_DIR%"
if %errorLevel% neq 0 (
echo 错误: 创建符号链接失败
echo 提示: 请在 Windows 设置中启用开发者模式
pause
exit /b 1
)
echo 成功: 符号链接已创建!
pause
逐步指南
第 1 步:创建你的技能目录
# 在你的项目根目录中
mkdir .ai-rules
cd .ai-rules
创建示例技能(见下文)。
第 2 步:创建设置脚本
复制上面的脚本之一并保存为:
setup-skills-link.ps1(PowerShell)setup-skills-link.bat(Batch)
第 3 步:启用开发者模式 (Windows)
可选但推荐 - 使创建符号链接更容易:
- 打开 设置 (Settings)
- 转到 更新和安全 (Update & Security) → 开发者选项 (For developers)
- 启用 开发者模式 (Developer Mode)
- 如果提示则重新启动
第 4 步:运行设置脚本
PowerShell (推荐):
# 右键点击 PowerShell → "以管理员身份运行"
cd path\to\your\project
.\setup-skills-link.ps1
Batch:
# 右键点击 setup-skills-link.bat → "以管理员身份运行"
第 5 步:验证设置
# 检查链接是否存在
dir .agent\skills
# 应显示: <SYMLINKD> skills [..\..\.ai-rules]
# 验证文件是否可访问
dir .agent\skills\*.md
第 6 步:更新 .gitignore
添加到 .gitignore:
# 忽略符号链接(源是 .ai-rules/)
.agent/skills
# 保留原始技能
!.ai-rules/
示例技能
最小技能结构
在 .ai-rules/ 中创建这些文件:
1. README.md
# Project Skills
AI coding assistant skills for this project.
## Available Skills
- `api-development.md` - REST API development patterns
- `testing-guide.md` - Testing strategy and examples
- `ui-patterns.md` - UI component patterns
## Usage
Reference in prompts:
```markdown
Follow @.agent/skills/api-development.md
#### 2. `api-development.md`
```markdown
# API Development Skill
## REST Endpoint Pattern
### Structure
```python
@app.route('/api/resource', methods=['POST'])
def create_resource():
try:
data = request.get_json()
# Validate
if not data or 'name' not in data:
return jsonify({'error': 'Invalid data'}), 400
# Process
resource = Resource(name=data['name'])
db.session.add(resource)
db.session.commit()
return jsonify({'id': resource.id, 'name': resource.name}), 201
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
Rules
- Always validate input
- Use try/except with rollback
- Return consistent JSON format
- Include HTTP status codes
Testing
curl -X POST http://localhost:5000/api/resource \
-H "Content-Type: application/json" \
-d '{"name":"Test"}'
#### 3. `testing-guide.md`
```markdown
# Testing Guide
## Test Structure
```python
import pytest
from app import create_app, db
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
yield client
db.drop_all()
def test_create_resource(client):
response = client.post('/api/resource',
json={'name': 'Test Resource'})
assert response.status_code == 201
assert 'id' in response.json
assert response.json['name'] == 'Test Resource'
Running Tests
# All tests
pytest
# Specific file
pytest tests/test_api.py
# With coverage
pytest --cov=app tests/
Test Checklist
- Happy path works
- Invalid input handled
- Edge cases covered
- Error responses correct
#### 4. `ui-patterns.md`
```markdown
# UI Component Patterns
## Standard Button
```jsx
<button className="btn btn-primary">
Submit
</button>
Form Input
<div className="form-group">
<label>Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
Loading State
{isLoading ? (
<div className="spinner">Loading...</div>
) : (
<div className="content">{data}</div>
)}
Color Palette
- Primary:
#007bff - Success:
#28a745 - Danger:
#dc3545 - Warning:
#ffc107
---
## 在 AI 工具中使用技能
### Claude Code
```markdown
Create a new API endpoint following @.agent/skills/api-development.md
Cursor
.agent/ 中的技能不仅限于特定工具。
.agent/skills 中的技能会被索引。直接引用:
Follow the testing patterns in api-development.md
GitHub Copilot
// Follow .agent/skills/testing-guide.md
// Implement test for user creation
通用引用
See: .agent/skills/ui-patterns.md for button styling
故障排除
问题 1: “Permission Denied” (权限被拒绝)
原因: 未以管理员身份运行
解决方案:
- 右键单击脚本 → “以管理员身份运行”
- 或在 Windows 设置中启用开发者模式
问题 2: “Cannot create symbolic link” (无法创建符号链接)
原因: Windows 策略限制
解决方案 1 - 启用开发者模式:
- 设置 → 更新和安全 → 开发者选项 → 开发者模式
解决方案 2 - 修改组策略:
1. 运行: gpedit.msc
2. 导航: 计算机配置 → Windows 设置 → 安全设置 → 本地策略 → 用户权限分配
3. 查找: "创建符号链接"
4. 添加你的用户账户
问题 3: 链接已创建但文件不可访问
验证链接:
dir .agent\skills
# 应显示: <SYMLINKD>
重新创建链接:
# 删除
rmdir .agent\skills
# 重新创建
.\setup-skills-link.ps1
问题 4: 在 Windows 上工作但 Git 上不行
问题: Git 可能无法正确克隆符号链接
解决方案: 在 README 中添加设置说明:
## Setup After Clone
Windows users:
```powershell
.\setup-skills-link.ps1
Linux/Mac users:
ln -s .ai-rules .agent/skills
---
## 平台特定说明
### Windows
**要求**:
- 管理员权限 或
- 启用开发者模式
**命令**:
```cmd
mklink /D target source
Linux / macOS
无特殊要求 - 标准功能
命令:
ln -s source target
在你的项目中:
cd .agent
ln -s ../.ai-rules skills
WSL (Windows Subsystem for Linux)
像 Linux 一样工作:
cd .agent
ln -s ../.ai-rules skills
进阶:多个链接目标
你可以从多个位置创建指向同一源的链接:
project/
├── .ai-rules/ ← 源
│
├── .agent/
│ └── skills/ ← 链接 1
│
├── .cursor/
│ └── skills/ ← 链接 2
│
└── .github/
└── copilot/
└── skills/ ← 链接 3
所有链接都指向同一个源,最大限度的兼容性!
最佳实践
1. 单一事实来源
✅ 做: 编辑 .ai-rules/ 中的文件
❌ 不做: 通过符号链接编辑
2. 版本控制
✅ 做: 提交 .ai-rules/
❌ 不做: 提交 .agent/skills/
3. 文档
✅ 做: 在 README 中记录设置步骤 ❌ 不做: 假设每个人都知道符号链接
4. 团队设置
添加到项目 README:
## First-Time Setup
After cloning, create symbolic links:
```powershell
# Windows (as Administrator)
.\setup-skills-link.ps1
# Linux/Mac
ln -s .ai-rules .agent/skills
---
## 示例项目:Todo App
完整示例结构:
todo-app/ ├── .ai-rules/ │ ├── README.md │ ├── api-endpoints.md ← REST API patterns │ ├── database-models.md ← SQLAlchemy models │ ├── frontend-components.md ← React patterns │ ├── testing-strategy.md ← Pytest patterns │ └── deployment.md ← Docker/CI/CD │ ├── .agent/ │ └── skills/ → symbolic link to .ai-rules │ ├── src/ │ ├── api/ │ ├── components/ │ └── models/ │ ├── tests/ ├── .gitignore ├── setup-skills-link.ps1 └── README.md
**在开发中使用**:
```markdown
# In AI assistant prompt
Create a new Todo model following @.agent/skills/database-models.md
Add a React component for the todo list using patterns from @.agent/skills/frontend-components.md
Write tests following @.agent/skills/testing-strategy.md
快速开始清单
- 创建
.ai-rules/目录 - 添加技能文件 (markdown)
- 创建
setup-skills-link.ps1 - 以管理员身份运行脚本
- 验证链接:
dir .agent\skills - 更新
.gitignore - 提交
.ai-rules/到 git - 在 README 中记录设置
资源
脚本模板
本教程中的所有脚本都是生产就绪的。复制并根据你的项目进行调整。
目录名称
通用约定:
.ai-rules/- 通用 AI 指令.agent/- Agent 特定配置.cursor/- Cursor IDE.github/copilot/- GitHub Copilot
选择适合你工具的名称。
延伸阅读
- Windows Symbolic Links: https://docs.microsoft.com/en-us/windows/win32/fileio/symbolic-links
- Developer Mode: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development
- Git and Symlinks: https://git-scm.com/docs/git-symbolic-ref