[optional body]
[optional footer(s)]
```
## Commit Types
### Required Types
- **`feat:`** - A new feature (correlates with MINOR in Semantic Versioning)
- **`fix:`** - A bug fix (correlates with PATCH in Semantic Versioning)
### Common Additional Types
- **`docs:`** - Documentation only changes
- **`style:`** - Code style changes (formatting, missing semicolons, etc.)
- **`refactor:`** - Code refactoring without bug fixes or new features
- **`perf:`** - Performance improvements
- **`test:`** - Adding or updating tests
- **`build:`** - Build system or external dependencies changes
- **`ci:`** - CI/CD configuration changes
- **`chore:`** - Other changes that don't modify src or test files
- **`revert:`** - Reverts a previous commit
## Scope
An optional scope provides additional contextual information about the section of the codebase:
```
feat(parser): add ability to parse arrays
fix(auth): resolve token expiration issue
docs(readme): update installation instructions
```
## Description
- Must immediately follow the colon and space after the type/scope
- Use imperative mood ("add feature" not "added feature" or "adds feature")
- Don't capitalize the first letter
- No period at the end
- Keep it concise (typically 50-72 characters)
## Body
- Optional longer description providing additional context
- Must begin one blank line after the description
- Can consist of multiple paragraphs
- Explain the "what" and "why" of the change, not the "how"
## Breaking Changes
Breaking changes can be indicated in two ways:
### 1. Using `!` in the type/scope
```
feat!: send an email to the customer when a product is shipped
feat(api)!: send an email to the customer when a product is shipped
```
### 2. Using BREAKING CHANGE footer
```
feat: allow provided config object to extend other configs
BREAKING CHANGE: `extends` key in config file is now used for extending other config files
```
### 3. Both methods
```
chore!: drop support for Node 6
BREAKING CHANGE: use JavaScript features not available in Node 6.
```
## Examples
### Simple feature
```
feat: add user authentication
```
### Feature with scope
```
feat(auth): add OAuth2 support
```
### Bug fix with body
```
fix: prevent racing of requests
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
Remove timeouts which were used to mitigate the racing issue but are
obsolete now.
```
### Breaking change
```
feat!: migrate to new API client
BREAKING CHANGE: The API client interface has changed. All methods now
return Promises instead of using callbacks.
```
### Documentation update
```
docs: correct spelling of CHANGELOG
```
### Multi-paragraph body with footers
```
fix: prevent racing of requests
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
Remove timeouts which were used to mitigate the racing issue but are
obsolete now.
Reviewed-by: Z
Refs: #123
```
## Guidelines
1. **Always use a type** - Every commit must start with a type followed by a colon and space
2. **Use imperative mood** - Write as if completing the sentence "If applied, this commit will..."
3. **Be specific** - The description should clearly communicate what changed
4. **Keep it focused** - One logical change per commit
5. **Use scopes when helpful** - Scopes help categorize changes within a codebase
6. **Document breaking changes** - Always indicate breaking changes clearly
## Semantic Versioning Correlation
- **`fix:`** → PATCH version bump (1.0.0 → 1.0.1)
- **`feat:`** → MINOR version bump (1.0.0 → 1.1.0)
- **BREAKING CHANGE** → MAJOR version bump (1.0.0 → 2.0.0)
## When to Use
Use this format for:
- All git commits
- Commit message generation
- Pull request merge commits
- When the user asks about commit messages or git commits
## Common Mistakes to Avoid
❌ `Added new feature` (past tense, capitalized)
✅ `feat: add new feature` (imperative, lowercase)
❌ `fix: bug` (too vague)
✅ `fix: resolve null pointer exception in user service`
❌ `feat: add feature` (redundant)
✅ `feat: add user profile page`
❌ `feat: Added OAuth support.` (past tense, period)
✅ `feat: add OAuth support`
---
## 改动前的耦合分析 Coupling Analysis
- id: `coupling-analysis`
- category: 软件工程 (Software Engineering)
- path: `skills/coupling-analysis/SKILL.md`
- original: no
- tags: PE
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/coupling-analysis.json
# 改动前的耦合分析 | Coupling Analysis
**核心铁律:改参数前,先把参数之间的"约束图"画出来。互斥的约束,动手前就该发现,而不是动手后发现。**
## 为什么存在这个 Skill
真实事故:把止盈(TP)从"固定 2.2R"改成"最近分形高点"后,原规格
(SL 上界 3.0 ATR + RR ≥ 1.5)**首跑 0 个信号**。根因是数学互斥:
- SL 顶格 3.0 ATR(分母锁死),最近分形仅 1.25 ATR(分子上限)
- → 理论 RR 天花板 = 1.25,永远过不了 rr ≥ 1.5
这不是代码 bug,是**动手前没画约束图**。三个约束(TP/SL/RR)是耦合的,
动一个必然连锁。这就是蝴蝶效应。
## 执行流程(任何耦合改动之前)
### 第 1 步:识别耦合面
改这个之前,先问四件事:
1. **谁共享这个值?** —— `grep` 出所有引用点(常量 / 函数 / schema / 配置)
2. **谁是输入,谁是输出?** —— 画出数据流向
3. **有没有数学/逻辑约束关系?** —— 如 RR = reward/risk,A+B=C 之类
4. **谁依赖它的历史口径?** —— 回测、报表、已发布结论
### 第 2 步:画约束图
把相关参数写成约束列表,标出**可行域**和**互斥区间**:
```
示例(TP/SL/RR):
约束1: sl ≤ entry - 1.2*ATR (风控下限)
约束2: sl ≥ entry - 3.0*ATR (风控上限)
约束3: rr = (tp - entry)/(entry - sl) ≥ 1.5
约束4: tp = 最近分形高点, 通常 ≈ entry + 1.25*ATR
→
由约束2+4: rr_max ≈ 1.25/3.0 ≈ 0.42~1.25 → 与约束3 互斥 ❌
```
**互斥约束必须在动手前暴露。** 暴露不了,就先做第 3 步。
### 第 3 步:零改动扫描(不确定时)
**不要一上来就改代码。** 先在旧代码上做**只读参数扫描**:
- 枚举候选组合(如 rr ∈ [1.0,1.2,1.5,2.0] × sl上限 ∈ [2.0,2.5,3.0])
- 看哪些组合**输出量合理**、哪些**归零**
- 用真实数据跑,得到可行域
扫描成本 << 改动成本,且**无副作用**。
### 第 4 步:定义不变量(红线)
明确哪些是**用户红线,不可擅动**,哪些是**可调参数**:
| 类型 | 处理 |
|---|---|
| 用户明确的风控参数 | **不可擅自改**,要改必须先问 |
| 结构逻辑(如"SL 优先看支撑位") | 保留,只调常数 |
| 内部实现细节 | 可自由改 |
### 第 5 步:影响面枚举(改后回归)
列出所有下游:
- 依赖这个值的**测试**会不会红?
- 依赖这个口径的**历史结论**是否失效?
- **报表/回测**口径是否变了、是否可比?
## 高内聚低耦合的设计准则
新代码/重构时优先:
| 准则 | 做法 |
|---|---|
| **高内聚** | 一个模块只干一件事;相关逻辑就近放,不散落 |
| **低耦合** | 参数单一来源(single source of truth),不硬编码在多处 |
| **显式依赖** | 需要的值**传进来**,不要在函数内部偷偷读全局 |
| **可替换** | 改一个策略(如 TP 算法)不影响 SL/RR 模块 |
| **约束可测** | 把互斥约束写成**断言或测试**,违反时报错而非静默 |
**反例**:把 `1.5` / `2.0` 硬编码在计算式里 → 赔率变成常数,与标的无关(真实事故)。
**正解**:常数提取为具名参数,且与其它参数的关系有测试守护。
## 关键决策必须交还用户
**遇到影响关键决策的互斥约束 / 风控参数变更 / 不可逆选择:**
1. **停下来**,不要"为了让它跑起来"自行放宽
2. **把取舍摊开**:A 选项代价 vs B 选项代价,各是什么
3. **给推荐但标明**:"我倾向 X,理由是……,但这是你的风控参数,你拍"
4. **等用户明确回答**再继续
> 擅自替用户放宽风控参数 = 越权。哪怕动机是"让它能跑"。
## 交付前自检清单
- [ ] 我画的约束图里,有没有互斥区间?
- [ ] 有没有我偷偷改了用户没授权的参数?
- [ ] 下游影响面(测试/历史口径/报表)我列全了吗?
- [ ] 这个改动有没有新的单一数据源,还是又硬编码了一处?
- [ ] 涉及关键决策时,我是停下来问了,还是自己拍了?
**动手前 10 分钟的约束图,能省掉动手后 10 小时的连锁 bug。**
---
## CSS Ninja
- id: `css-ninja`
- category: 软件工程 (Software Engineering)
- path: `skills/css-ninja/SKILL.md`
- original: no
- tags: —
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/css-ninja.json
# CSS Ninja
Modern CSS mastery with Tailwind, CSS-in-JS, and responsive design patterns.
## Tailwind CSS
### Setup
```bash
# Install
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
# Configure
# tailwind.config.js
export default {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
theme: {
extend: {
colors: {
brand: {
50: '#f0f9ff',
500: '#3b82f6',
900: '#1e3a8a'
}
}
}
},
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography')
]
}
```
### Responsive Design
```html
```
### Common Patterns
```html
Gradient Heading
```
## CSS-in-JS
### Styled Components
```tsx
import styled from 'styled-components';
const Button = styled.button<{ $variant?: 'primary' | 'secondary' }>`
padding: 0.5rem 1rem;
border-radius: 0.5rem;
font-weight: 500;
transition: all 0.2s;
${props => props.$variant === 'primary' && `
background: #3b82f6;
color: white;
&:hover { background: #2563eb; }
`}
${props => props.$variant === 'secondary' && `
background: transparent;
border: 1px solid #3b82f6;
color: #3b82f6;
&:hover { background: #eff6ff; }
`}
`;
// Usage
```
### Emotion
```tsx
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const buttonStyles = css`
padding: 0.5rem 1rem;
border-radius: 0.5rem;
`;
function Button({ children }) {
return ;
}
```
## Layouts
### Flexbox Patterns
```css
/* Center everything */
.center { display: flex; align-items: center; justify-content: center; }
/* Space between */
.header { display: flex; justify-content: space-between; align-items: center; }
/* Equal spacing */
.nav { display: flex; gap: 1rem; }
/* Sticky footer */
.page { display: flex; flex-direction: column; min-height: 100vh; }
.content { flex: 1; }
```
### Grid Patterns
```css
/* Auto-fit responsive grid */
.grid-auto {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}
/* Holy grail layout */
.layout {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
```
## Animations
### Tailwind Animations
```html
Content fades in
Loading...
↓
```
### Custom Animations
```css
/* tailwind.config.js */
module.exports = {
theme: {
extend: {
animation: {
'fade-in': 'fadeIn 0.5s ease-in',
'slide-up': 'slideUp 0.3s ease-out',
'scale-in': 'scaleIn 0.2s ease'
},
keyframes: {
fadeIn: {
'0%': { opacity: '0' },
'100%': { opacity: '1' }
},
slideUp: {
'0%': { transform: 'translateY(10px)', opacity: '0' },
'100%': { transform: 'translateY(0)', opacity: '1' }
},
scaleIn: {
'0%': { transform: 'scale(0.95)', opacity: '0' },
'100%': { transform: 'scale(1)', opacity: '1' }
}
}
}
}
}
```
## Dark Mode
```tsx
// tailwind.config.js
module.exports = {
darkMode: 'class', // or 'media'
// ...
}
// Toggle implementation
function ThemeToggle() {
const [dark, setDark] = useState(() =>
localStorage.theme === 'dark'
);
useEffect(() => {
document.documentElement.classList.toggle('dark', dark);
localStorage.theme = dark ? 'dark' : 'light';
}, [dark]);
return (
);
}
```
```html
Hello
```
## Responsive Breakpoints
```css
/* Standard breakpoints */
/* sm: 640px */
/* md: 768px */
/* lg: 1024px */
/* xl: 1280px */
/* 2xl: 1536px */
/* Tailwind usage */
```
## References
- `references/tailwind_cheatsheet.md` - Complete Tailwind reference
- `references/css_patterns.md` - Common CSS layout patterns
- `references/animation_library.md` - Framer Motion / GSAP patterns
---
## Database Migrator
- id: `db-migrator`
- category: 软件工程 (Software Engineering)
- path: `skills/db-migrator/SKILL.md`
- original: no
- tags: —
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/db-migrator.json
# Database Migrator
Professional database schema migration and version control for production systems.
## Core Workflow
### 1. Create Migration
```bash
# Generate migration file
npm run migrate:make create_users_table
# or
npx prisma migrate dev --name add_user_email
# or
python -m alembic revision -m "add_user_email"
```
### 2. Write Migration
```javascript
// Knex.js example
exports.up = function(knex) {
return knex.schema.createTable('users', table => {
table.increments('id').primary();
table.string('email').notNullable().unique();
table.string('password_hash').notNullable();
table.timestamp('created_at').defaultTo(knex.fn.now());
table.timestamp('updated_at').defaultTo(knex.fn.now());
// Indexes
table.index('email');
});
};
exports.down = function(knex) {
return knex.schema.dropTable('users');
};
```
### 3. Run Migration
```bash
# Apply pending migrations
npm run migrate:up
# Rollback last migration
npm run migrate:down
# Rollback all
npm run migrate:reset
# Refresh (rollback + re-run)
npm run migrate:refresh
```
## Migration Best Practices
### Always Include Down Migration
```javascript
// ✅ Good - Reversible
exports.up = (knex) => knex.schema.alterTable('users', t => {
t.string('phone').nullable();
});
exports.down = (knex) => knex.schema.alterTable('users', t => {
t.dropColumn('phone');
});
// ❌ Bad - Irreversible
exports.up = (knex) => knex.schema.alterTable('users', t => {
t.string('phone').nullable();
});
exports.down = () => {}; // Empty rollback!
```
### Atomic Migrations
```javascript
// ✅ Good - Single responsibility
// Migration 1: Add column
exports.up = (knex) => knex.schema.alterTable('users', t => {
t.string('phone');
});
// Migration 2: Populate data
exports.up = (knex) => knex.raw(`
UPDATE users SET phone = '000-000-0000' WHERE phone IS NULL
`);
// ❌ Bad - Mixed concerns
exports.up = async (knex) => {
await knex.schema.alterTable('users', t => t.string('phone'));
await knex.raw('UPDATE users SET phone = ...');
await knex.schema.createTable('audit_log', ...);
};
```
### Safe Column Operations
```javascript
// Add column with default (avoid locking)
exports.up = (knex) => knex.raw(`
ALTER TABLE users
ADD COLUMN phone VARCHAR(20) DEFAULT ''
`);
// Remove column safely
exports.down = (knex) => knex.raw(`
ALTER TABLE users
DROP COLUMN phone
`);
// Rename column (data preserved)
exports.up = (knex) => knex.schema.alterTable('users', t => {
t.renameColumn('phone', 'phone_number');
});
```
## Framework-Specific Patterns
### Prisma (Node.js)
```prisma
// schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
posts Post[]
createdAt DateTime @default(now())
}
// Run migration
npx prisma migrate dev --name init
npx prisma migrate deploy // Production
```
### Alembic (Python)
```python
# migrations/versions/abc123_add_email.py
def upgrade():
op.add_column('users', sa.Column('email', sa.String(255)))
def downgrade():
op.drop_column('users', 'email')
# Commands
alembic upgrade head
alembic downgrade -1
```
### Flyway (Java/General)
```sql
-- V1__create_users_table.sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT NOW()
);
-- V2__add_phone_column.sql
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
```
## Data Migrations
```javascript
// Transform data safely
exports.up = async (knex) => {
const users = await knex('users').whereNull('full_name');
for (const user of users) {
await knex('users')
.where({ id: user.id })
.update({
full_name: `${user.first_name} ${user.last_name}`
});
}
};
```
## Production Safety
```javascript
// Add timeout for large tables
exports.up = (knex) => knex.raw(`
SET statement_timeout = '300s';
ALTER TABLE large_table ADD COLUMN new_field TEXT;
`);
// Create index concurrently (PostgreSQL)
exports.up = (knex) => knex.raw(`
CREATE INDEX CONCURRENTLY idx_users_email
ON users(email)
`);
```
## Scripts
- `scripts/create_migration.sh` - Generate migration file with timestamp
- `scripts/check_migrations.js` - Compare local vs remote migration status
- `scripts/seed_data.js` - Load seed data from JSON/CSV
## References
- `references/postgres_types.md` - PostgreSQL data types reference
- `references/mysql_types.md` - MySQL data types reference
- `references/migration_templates/` - Framework-specific templates
---
## v3
- id: `digital-human-api`
- category: 软件工程 (Software Engineering)
- path: `skills/digital-human-api/SKILL.md`
- original: no
- tags: —
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/digital-human-api.json
# digital-human-api v3
基于青云API的通用数字人口播视频生成 Skill。
**v3核心改进:每shot生成专属场景图(Daniel真脸 + 个性化场景),视频自然不抽象。**
## 触发条件
- `数字人视频`、`口播视频`、`digital human`
- 基于剧本生成分镜头数字人视频
## v3 新流程(4步/shot)
```
剧本JSON → [Scene Image] → [TTS] → [Kling Video] → [Lip Sync] → FFmpeg合并
↑ 新增:每个shot独立生成贴合场景的图片
```
**每shot独立流程:**
1. 🖼️ **场景图生成** — Grok依据参考脸生成贴合场景的图片(保持Daniel的脸)
2. 📝 **TTS语音** — Gemini生成口播音频
3. 🎬 **Kling视频** — 场景图 + 动作提示词 → 动态视频
4. 👄 **对口型** — Kling LipSync音画同步
5. 🔗 **FFmpeg合并** — 所有shot + BGM → 最终视频
## v3 剧本格式
```json
{
"title": "视频标题",
"avatar_image": "/path/to/daniel-headshot.jpg",
"shots": [
{
"id": 1,
"text": "口播文案",
"emotion": "sarcastic",
"scene_description": "(可选)场景图详细描述",
"duration": 5
}
]
}
```
### emotion 可选值
| emotion | 动作风格 |
|---------|---------|
| `serious` | 严肃直视镜头 |
| `friendly` | 友好微笑 |
| `excited` | 兴奋手势多 |
| `sarcastic` | 讽刺挑眉 |
| `storytelling` | 讲故事手势 |
| `humorous` | 幽默轻松 |
| `intense` | 紧张/激动 |
| `confident` | 自信权威 |
| `questioning` | 疑惑歪头 |
| `casual` | 日常对话 |
### scene_description 写法
描述越具体,场景图越贴合。建议格式:
- 人物表情+动作(如:raised eyebrow, holding coffee cup)
- 场景(如:modern cafe, restaurant table)
- 光线(如:warm natural lighting)
- 风格(如:realistic photo, shot on iPhone)
## 使用方式
```bash
export QINGYUN_API_KEY=$(pass show api/qingyun)
# 完整流水线
python3 scripts/generate.py --script script.json --concurrent 1
# 分步执行
python3 scripts/generate.py --script script.json --step image # 场景图
python3 scripts/generate.py --script script.json --step tts # TTS语音
python3 scripts/generate.py --script script.json --step video # Kling视频
python3 scripts/generate.py --script script.json --step lipsync # 对口型
python3 scripts/generate.py --script script.json --step merge # 合并
```
## 输出结构
```
output_dir/
├── shot_01_scene.jpg # 场景原图
├── shot_01_scene_768.jpg # 适配Kling的尺寸
├── shot_01_audio.mp3 # TTS语音
├── shot_01_video.mp4 # Kling视频
├── shot_01_lipsync.mp4 # 对口型完成
├── ...
└── final.mp4 # 最终视频
```
## 已知限制
| 问题 | 解决 |
|------|------|
| 视频太抽象 | v3改用场景图,每个shot独立生成 |
| 429限流 | 并发=1,轮询间隔15s |
| 图片像素无效 | 自动resize到768px宽 |
| Grok场景图失败 | 自动降级到无ref生成 |
## 文件清单
```
digital-human-api/
├── SKILL.md # 本文件
├── scripts/
│ ├── generate.py # 主脚本 v3(~800行)
│ └── config.yaml # 配置 v3
```
---
## E2E Testing Patterns
- id: `e2e-testing`
- category: 软件工程 (Software Engineering)
- path: `skills/e2e-testing/SKILL.md`
- original: no
- tags: PE
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/e2e-testing.json
# E2E Testing Patterns
Comprehensive Playwright patterns for building stable, fast, and maintainable E2E test suites.
## Test File Organization
```
tests/
├── e2e/
│ ├── auth/
│ │ ├── login.spec.ts
│ │ ├── logout.spec.ts
│ │ └── register.spec.ts
│ ├── features/
│ │ ├── browse.spec.ts
│ │ ├── search.spec.ts
│ │ └── create.spec.ts
│ └── api/
│ └── endpoints.spec.ts
├── fixtures/
│ ├── auth.ts
│ └── data.ts
└── playwright.config.ts
```
## Page Object Model (POM)
```typescript
import { Page, Locator } from '@playwright/test'
export class ItemsPage {
readonly page: Page
readonly searchInput: Locator
readonly itemCards: Locator
readonly createButton: Locator
constructor(page: Page) {
this.page = page
this.searchInput = page.locator('[data-testid="search-input"]')
this.itemCards = page.locator('[data-testid="item-card"]')
this.createButton = page.locator('[data-testid="create-btn"]')
}
async goto() {
await this.page.goto('/items')
await this.page.waitForLoadState('networkidle')
}
async search(query: string) {
await this.searchInput.fill(query)
await this.page.waitForResponse(resp => resp.url().includes('/api/search'))
await this.page.waitForLoadState('networkidle')
}
async getItemCount() {
return await this.itemCards.count()
}
}
```
## Test Structure
```typescript
import { test, expect } from '@playwright/test'
import { ItemsPage } from '../../pages/ItemsPage'
test.describe('Item Search', () => {
let itemsPage: ItemsPage
test.beforeEach(async ({ page }) => {
itemsPage = new ItemsPage(page)
await itemsPage.goto()
})
test('should search by keyword', async ({ page }) => {
await itemsPage.search('test')
const count = await itemsPage.getItemCount()
expect(count).toBeGreaterThan(0)
await expect(itemsPage.itemCards.first()).toContainText(/test/i)
await page.screenshot({ path: 'artifacts/search-results.png' })
})
test('should handle no results', async ({ page }) => {
await itemsPage.search('xyznonexistent123')
await expect(page.locator('[data-testid="no-results"]')).toBeVisible()
expect(await itemsPage.getItemCount()).toBe(0)
})
})
```
## Playwright Configuration
```typescript
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
testDir: './tests/e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
['html', { outputFolder: 'playwright-report' }],
['junit', { outputFile: 'playwright-results.xml' }],
['json', { outputFile: 'playwright-results.json' }]
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
actionTimeout: 10000,
navigationTimeout: 30000,
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120000,
},
})
```
## Flaky Test Patterns
### Quarantine
```typescript
test('flaky: complex search', async ({ page }) => {
test.fixme(true, 'Flaky - Issue #123')
// test code...
})
test('conditional skip', async ({ page }) => {
test.skip(process.env.CI, 'Flaky in CI - Issue #123')
// test code...
})
```
### Identify Flakiness
```bash
npx playwright test tests/search.spec.ts --repeat-each=10
npx playwright test tests/search.spec.ts --retries=3
```
### Common Causes & Fixes
**Race conditions:**
```typescript
// Bad: assumes element is ready
await page.click('[data-testid="button"]')
// Good: auto-wait locator
await page.locator('[data-testid="button"]').click()
```
**Network timing:**
```typescript
// Bad: arbitrary timeout
await page.waitForTimeout(5000)
// Good: wait for specific condition
await page.waitForResponse(resp => resp.url().includes('/api/data'))
```
**Animation timing:**
```typescript
// Bad: click during animation
await page.click('[data-testid="menu-item"]')
// Good: wait for stability
await page.locator('[data-testid="menu-item"]').waitFor({ state: 'visible' })
await page.waitForLoadState('networkidle')
await page.locator('[data-testid="menu-item"]').click()
```
## Artifact Management
### Screenshots
```typescript
await page.screenshot({ path: 'artifacts/after-login.png' })
await page.screenshot({ path: 'artifacts/full-page.png', fullPage: true })
await page.locator('[data-testid="chart"]').screenshot({ path: 'artifacts/chart.png' })
```
### Traces
```typescript
await browser.startTracing(page, {
path: 'artifacts/trace.json',
screenshots: true,
snapshots: true,
})
// ... test actions ...
await browser.stopTracing()
```
### Video
```typescript
// In playwright.config.ts
use: {
video: 'retain-on-failure',
videosPath: 'artifacts/videos/'
}
```
## CI/CD Integration
```yaml
# .github/workflows/e2e.yml
name: E2E Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npx playwright install --with-deps
- run: npx playwright test
env:
BASE_URL: ${{ vars.STAGING_URL }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: playwright-report/
retention-days: 30
```
## Test Report Template
```markdown
# E2E Test Report
**Date:** YYYY-MM-DD HH:MM
**Duration:** Xm Ys
**Status:** PASSING / FAILING
## Summary
- Total: X | Passed: Y (Z%) | Failed: A | Flaky: B | Skipped: C
## Failed Tests
### test-name
**File:** `tests/e2e/feature.spec.ts:45`
**Error:** Expected element to be visible
**Screenshot:** artifacts/failed.png
**Recommended Fix:** [description]
## Artifacts
- HTML Report: playwright-report/index.html
- Screenshots: artifacts/*.png
- Videos: artifacts/videos/*.webm
- Traces: artifacts/*.zip
```
## Wallet / Web3 Testing
```typescript
test('wallet connection', async ({ page, context }) => {
// Mock wallet provider
await context.addInitScript(() => {
window.ethereum = {
isMetaMask: true,
request: async ({ method }) => {
if (method === 'eth_requestAccounts')
return ['0x1234567890123456789012345678901234567890']
if (method === 'eth_chainId') return '0x1'
}
}
})
await page.goto('/')
await page.locator('[data-testid="connect-wallet"]').click()
await expect(page.locator('[data-testid="wallet-address"]')).toContainText('0x1234')
})
```
## Financial / Critical Flow Testing
```typescript
test('trade execution', async ({ page }) => {
// Skip on production — real money
test.skip(process.env.NODE_ENV === 'production', 'Skip on production')
await page.goto('/markets/test-market')
await page.locator('[data-testid="position-yes"]').click()
await page.locator('[data-testid="trade-amount"]').fill('1.0')
// Verify preview
const preview = page.locator('[data-testid="trade-preview"]')
await expect(preview).toContainText('1.0')
// Confirm and wait for blockchain
await page.locator('[data-testid="confirm-trade"]').click()
await page.waitForResponse(
resp => resp.url().includes('/api/trade') && resp.status() === 200,
{ timeout: 30000 }
)
await expect(page.locator('[data-testid="trade-success"]')).toBeVisible()
})
```
---
## E2E Testing Patterns
- id: `e2e-testing-patterns`
- category: 软件工程 (Software Engineering)
- path: `skills/e2e-testing-patterns/SKILL.md`
- original: no
- tags: —
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/e2e-testing-patterns.json
# E2E Testing Patterns
Build reliable, fast, and maintainable end-to-end test suites that provide confidence to ship code quickly and catch regressions before users do.
## When to Use This Skill
- Implementing end-to-end test automation
- Debugging flaky or unreliable tests
- Testing critical user workflows
- Setting up CI/CD test pipelines
- Testing across multiple browsers
- Validating accessibility requirements
- Testing responsive designs
- Establishing E2E testing standards
## Core Concepts
### 1. E2E Testing Fundamentals
**What to Test with E2E:**
- Critical user journeys (login, checkout, signup)
- Complex interactions (drag-and-drop, multi-step forms)
- Cross-browser compatibility
- Real API integration
- Authentication flows
**What NOT to Test with E2E:**
- Unit-level logic (use unit tests)
- API contracts (use integration tests)
- Edge cases (too slow)
- Internal implementation details
### 2. Test Philosophy
**The Testing Pyramid:**
```
/\
/E2E\ ← Few, focused on critical paths
/─────\
/Integr\ ← More, test component interactions
/────────\
/Unit Tests\ ← Many, fast, isolated
/────────────\
```
**Best Practices:**
- Test user behavior, not implementation
- Keep tests independent
- Make tests deterministic
- Optimize for speed
- Use data-testid, not CSS selectors
## Playwright Patterns
### Setup and Configuration
```typescript
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
timeout: 30000,
expect: {
timeout: 5000,
},
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [["html"], ["junit", { outputFile: "results.xml" }]],
use: {
baseURL: "http://localhost:3000",
trace: "on-first-retry",
screenshot: "only-on-failure",
video: "retain-on-failure",
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
{ name: "webkit", use: { ...devices["Desktop Safari"] } },
{ name: "mobile", use: { ...devices["iPhone 13"] } },
],
});
```
### Pattern 1: Page Object Model
```typescript
// pages/LoginPage.ts
import { Page, Locator } from "@playwright/test";
export class LoginPage {
readonly page: Page;
readonly emailInput: Locator;
readonly passwordInput: Locator;
readonly loginButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.emailInput = page.getByLabel("Email");
this.passwordInput = page.getByLabel("Password");
this.loginButton = page.getByRole("button", { name: "Login" });
this.errorMessage = page.getByRole("alert");
}
async goto() {
await this.page.goto("/login");
}
async login(email: string, password: string) {
await this.emailInput.fill(email);
await this.passwordInput.fill(password);
await this.loginButton.click();
}
async getErrorMessage(): Promise {
return (await this.errorMessage.textContent()) ?? "";
}
}
// Test using Page Object
import { test, expect } from "@playwright/test";
import { LoginPage } from "./pages/LoginPage";
test("successful login", async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login("user@example.com", "password123");
await expect(page).toHaveURL("/dashboard");
await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
});
test("failed login shows error", async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login("invalid@example.com", "wrong");
const error = await loginPage.getErrorMessage();
expect(error).toContain("Invalid credentials");
});
```
### Pattern 2: Fixtures for Test Data
```typescript
// fixtures/test-data.ts
import { test as base } from "@playwright/test";
type TestData = {
testUser: {
email: string;
password: string;
name: string;
};
adminUser: {
email: string;
password: string;
};
};
export const test = base.extend({
testUser: async ({}, use) => {
const user = {
email: `test-${Date.now()}@example.com`,
password: "Test123!@#",
name: "Test User",
};
// Setup: Create user in database
await createTestUser(user);
await use(user);
// Teardown: Clean up user
await deleteTestUser(user.email);
},
adminUser: async ({}, use) => {
await use({
email: "admin@example.com",
password: process.env.ADMIN_PASSWORD!,
});
},
});
// Usage in tests
import { test } from "./fixtures/test-data";
test("user can update profile", async ({ page, testUser }) => {
await page.goto("/login");
await page.getByLabel("Email").fill(testUser.email);
await page.getByLabel("Password").fill(testUser.password);
await page.getByRole("button", { name: "Login" }).click();
await page.goto("/profile");
await page.getByLabel("Name").fill("Updated Name");
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Profile updated")).toBeVisible();
});
```
### Pattern 3: Waiting Strategies
```typescript
// ❌ Bad: Fixed timeouts
await page.waitForTimeout(3000); // Flaky!
// ✅ Good: Wait for specific conditions
await page.waitForLoadState("networkidle");
await page.waitForURL("/dashboard");
await page.waitForSelector('[data-testid="user-profile"]');
// ✅ Better: Auto-waiting with assertions
await expect(page.getByText("Welcome")).toBeVisible();
await expect(page.getByRole("button", { name: "Submit" })).toBeEnabled();
// Wait for API response
const responsePromise = page.waitForResponse(
(response) =>
response.url().includes("/api/users") && response.status() === 200,
);
await page.getByRole("button", { name: "Load Users" }).click();
const response = await responsePromise;
const data = await response.json();
expect(data.users).toHaveLength(10);
// Wait for multiple conditions
await Promise.all([
page.waitForURL("/success"),
page.waitForLoadState("networkidle"),
expect(page.getByText("Payment successful")).toBeVisible(),
]);
```
### Pattern 4: Network Mocking and Interception
```typescript
// Mock API responses
test("displays error when API fails", async ({ page }) => {
await page.route("**/api/users", (route) => {
route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ error: "Internal Server Error" }),
});
});
await page.goto("/users");
await expect(page.getByText("Failed to load users")).toBeVisible();
});
// Intercept and modify requests
test("can modify API request", async ({ page }) => {
await page.route("**/api/users", async (route) => {
const request = route.request();
const postData = JSON.parse(request.postData() || "{}");
// Modify request
postData.role = "admin";
await route.continue({
postData: JSON.stringify(postData),
});
});
// Test continues...
});
// Mock third-party services
test("payment flow with mocked Stripe", async ({ page }) => {
await page.route("**/api/stripe/**", (route) => {
route.fulfill({
status: 200,
body: JSON.stringify({
id: "mock_payment_id",
status: "succeeded",
}),
});
});
// Test payment flow with mocked response
});
```
## Cypress Patterns
### Setup and Configuration
```typescript
// cypress.config.ts
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
baseUrl: "http://localhost:3000",
viewportWidth: 1280,
viewportHeight: 720,
video: false,
screenshotOnRunFailure: true,
defaultCommandTimeout: 10000,
requestTimeout: 10000,
setupNodeEvents(on, config) {
// Implement node event listeners
},
},
});
```
### Pattern 1: Custom Commands
```typescript
// cypress/support/commands.ts
declare global {
namespace Cypress {
interface Chainable {
login(email: string, password: string): Chainable;
createUser(userData: UserData): Chainable;
dataCy(value: string): Chainable>;
}
}
}
Cypress.Commands.add("login", (email: string, password: string) => {
cy.visit("/login");
cy.get('[data-testid="email"]').type(email);
cy.get('[data-testid="password"]').type(password);
cy.get('[data-testid="login-button"]').click();
cy.url().should("include", "/dashboard");
});
Cypress.Commands.add("createUser", (userData: UserData) => {
return cy.request("POST", "/api/users", userData).its("body");
});
Cypress.Commands.add("dataCy", (value: string) => {
return cy.get(`[data-cy="${value}"]`);
});
// Usage
cy.login("user@example.com", "password");
cy.dataCy("submit-button").click();
```
### Pattern 2: Cypress Intercept
```typescript
// Mock API calls
cy.intercept("GET", "/api/users", {
statusCode: 200,
body: [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
],
}).as("getUsers");
cy.visit("/users");
cy.wait("@getUsers");
cy.get('[data-testid="user-list"]').children().should("have.length", 2);
// Modify responses
cy.intercept("GET", "/api/users", (req) => {
req.reply((res) => {
// Modify response
res.body.users = res.body.users.slice(0, 5);
res.send();
});
});
// Simulate slow network
cy.intercept("GET", "/api/data", (req) => {
req.reply((res) => {
res.delay(3000); // 3 second delay
res.send();
});
});
```
## Advanced Patterns
### Pattern 1: Visual Regression Testing
```typescript
// With Playwright
import { test, expect } from "@playwright/test";
test("homepage looks correct", async ({ page }) => {
await page.goto("/");
await expect(page).toHaveScreenshot("homepage.png", {
fullPage: true,
maxDiffPixels: 100,
});
});
test("button in all states", async ({ page }) => {
await page.goto("/components");
const button = page.getByRole("button", { name: "Submit" });
// Default state
await expect(button).toHaveScreenshot("button-default.png");
// Hover state
await button.hover();
await expect(button).toHaveScreenshot("button-hover.png");
// Disabled state
await button.evaluate((el) => el.setAttribute("disabled", "true"));
await expect(button).toHaveScreenshot("button-disabled.png");
});
```
### Pattern 2: Parallel Testing with Sharding
```typescript
// playwright.config.ts
export default defineConfig({
projects: [
{
name: "shard-1",
use: { ...devices["Desktop Chrome"] },
grepInvert: /@slow/,
shard: { current: 1, total: 4 },
},
{
name: "shard-2",
use: { ...devices["Desktop Chrome"] },
shard: { current: 2, total: 4 },
},
// ... more shards
],
});
// Run in CI
// npx playwright test --shard=1/4
// npx playwright test --shard=2/4
```
### Pattern 3: Accessibility Testing
```typescript
// Install: npm install @axe-core/playwright
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";
test("page should not have accessibility violations", async ({ page }) => {
await page.goto("/");
const accessibilityScanResults = await new AxeBuilder({ page })
.exclude("#third-party-widget")
.analyze();
expect(accessibilityScanResults.violations).toEqual([]);
});
test("form is accessible", async ({ page }) => {
await page.goto("/signup");
const results = await new AxeBuilder({ page }).include("form").analyze();
expect(results.violations).toEqual([]);
});
```
## Best Practices
1. **Use Data Attributes**: `data-testid` or `data-cy` for stable selectors
2. **Avoid Brittle Selectors**: Don't rely on CSS classes or DOM structure
3. **Test User Behavior**: Click, type, see - not implementation details
4. **Keep Tests Independent**: Each test should run in isolation
5. **Clean Up Test Data**: Create and destroy test data in each test
6. **Use Page Objects**: Encapsulate page logic
7. **Meaningful Assertions**: Check actual user-visible behavior
8. **Optimize for Speed**: Mock when possible, parallel execution
```typescript
// ❌ Bad selectors
cy.get(".btn.btn-primary.submit-button").click();
cy.get("div > form > div:nth-child(2) > input").type("text");
// ✅ Good selectors
cy.getByRole("button", { name: "Submit" }).click();
cy.getByLabel("Email address").type("user@example.com");
cy.get('[data-testid="email-input"]').type("user@example.com");
```
## Common Pitfalls
- **Flaky Tests**: Use proper waits, not fixed timeouts
- **Slow Tests**: Mock external APIs, use parallel execution
- **Over-Testing**: Don't test every edge case with E2E
- **Coupled Tests**: Tests should not depend on each other
- **Poor Selectors**: Avoid CSS classes and nth-child
- **No Cleanup**: Clean up test data after each test
- **Testing Implementation**: Test user behavior, not internals
## Debugging Failing Tests
```typescript
// Playwright debugging
// 1. Run in headed mode
npx playwright test --headed
// 2. Run in debug mode
npx playwright test --debug
// 3. Use trace viewer
await page.screenshot({ path: 'screenshot.png' });
await page.video()?.saveAs('video.webm');
// 4. Add test.step for better reporting
test('checkout flow', async ({ page }) => {
await test.step('Add item to cart', async () => {
await page.goto('/products');
await page.getByRole('button', { name: 'Add to Cart' }).click();
});
await test.step('Proceed to checkout', async () => {
await page.goto('/cart');
await page.getByRole('button', { name: 'Checkout' }).click();
});
});
// 5. Inspect page state
await page.pause(); // Pauses execution, opens inspector
```
---
## ⚡ Electron 桌面应用开发专家
- id: `electron-app-dev`
- category: 软件工程 (Software Engineering)
- path: `skills/electron-app-dev/SKILL.md`
- original: no
- tags: —
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/electron-app-dev.json
# ⚡ Electron 桌面应用开发专家
老王我搞Electron好多年了,这玩意儿写跨平台应用真tm香!
## 快速开始:创建新项目
使用内置脚本创建最佳实践Electron项目:
```bash
python "C:~/.claude/skills/electron-app-dev/scripts/create_electron_app.py" my-app
cd my-app
npm install
npm run dev
```
**生成项目包含:**
- electron-vite:全进程极速热更新
- TypeScript + React:类型安全开发
- contextBridge安全IPC模式
- electron-builder打包配置
---
## 核心安全原则(不可妥协)
永远强制执行这些安全配置:
```typescript
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true, // 必须为true
nodeIntegration: false, // 必须为false
sandbox: true // 推荐开启
}
```
**为什么重要:**
- `contextIsolation: true` - 隔离preload脚本与渲染器
- `nodeIntegration: false` - 防止渲染器直接访问Node.js
- `sandbox: true` - 进一步限制渲染器进程能力
---
## IPC通信模式
### 唯一正确方式:contextBridge + 白名单
**Preload (preload/index.ts):**
```typescript
const SEND_CHANNELS = ['app-ready']
const INVOKE_CHANNELS = ['get-app-info', 'save-file']
contextBridge.exposeInMainWorld('electronAPI', {
send: (channel, ...args) => {
if (SEND_CHANNELS.includes(channel)) {
ipcRenderer.send(channel, ...args)
}
},
invoke: async (channel, ...args) => {
if (INVOKE_CHANNELS.includes(channel)) {
return await ipcRenderer.invoke(channel, ...args)
}
return Promise.reject(new Error(`Invalid channel: ${channel}`))
}
})
```
**Main Process (main/index.ts):**
```typescript
function validateSender(frame: Electron.WebFrameMain | null): boolean {
if (!frame) return false
const url = new URL(frame.url)
const allowedHosts = ['localhost', 'yourdomain.com']
return allowedHosts.includes(url.hostname) || url.protocol === 'file:'
}
ipcMain.handle('get-app-info', (event) => {
if (!validateSender(event.senderFrame)) return null
return { name: app.getName(), version: app.getVersion() }
})
```
---
## 常见坑与解决方案(老王血泪经验)
### 1. 白屏问题(DevTools可以加载但正常不行)
**症状:** 开发环境正常,打包后白屏
**原因:** 协议问题或路径错误
```typescript
// ❌ 错误写法
win.loadURL('http://localhost:5173')
// ✅ 正确写法
if (app.isPackaged) {
win.loadFile(path.join(__dirname, '../renderer/index.html'))
} else {
win.loadURL('http://localhost:5173')
}
// ✅ 生产环境加载方案
win.loadFile(path.join(__dirname, '../renderer/index.html'))
win.webContents.openDevTools() // 先看看能不能加载
```
### 2. 内存泄漏(IPC监听器没移除)
**症状:** 应用用久了越来越卡
```typescript
// ❌ 错误写法
useEffect(() => {
window.electronAPI.on('update', callback)
// 没有清理函数!
}, [])
// ✅ 正确写法
useEffect(() => {
const callback = (data) => console.log(data)
window.electronAPI.on('update', callback)
return () => {
window.electronAPI.removeListener('update', callback) // 必须移除!
}
}, [])
```
### 3. 窗口状态不保存(用户每次打开都要重新调整大小)
```typescript
import Store from 'electron-store'
const store = new Store()
const win = new BrowserWindow({
x: store.get('window.x', undefined),
y: store.get('window.y', undefined),
width: store.get('window.width', 1200),
height: store.get('window.height', 800),
})
// 窗口关闭时保存状态
win.on('close', () => {
const bounds = win.getBounds()
store.set('window', {
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
})
})
```
### 4. DevTools在开发环境自动打开,生产环境忘记关
```typescript
const win = new BrowserWindow({
// ...
webPreferences: {
// ...
}
})
// 只在开发环境打开
if (process.env.NODE_ENV === 'development') {
win.webContents.openDevTools()
}
// 或者用快捷键
app.on('ready', () => {
// ...
globalShortcut.register('CommandOrControl+Shift+I', () => {
win.webContents.toggleDevTools()
})
})
```
---
## 性能优化(让应用飞起来)
### 1. 懒加载窗口(别tm一次性创建所有窗口)
```typescript
// ❌ 错误写法:启动时创建所有窗口
const mainWindow = new BrowserWindow({ /* ... */ })
const settingsWindow = new BrowserWindow({ /* ... */ })
const aboutWindow = new BrowserWindow({ /* ... */ })
// ✅ 正确写法:按需创建
let settingsWindow: BrowserWindow | null = null
function openSettings() {
if (!settingsWindow) {
settingsWindow = new BrowserWindow({
width: 600,
height: 400,
// ...
})
settingsWindow.on('closed', () => {
settingsWindow = null // 关闭后释放内存
})
}
settingsWindow.show()
}
```
### 2. BrowserView替代多个窗口(更省内存)
```typescript
// 一个主窗口 + 多个BrowserView
const win = new BrowserWindow({ width: 1200, height: 800 })
const view1 = new BrowserView()
win.setBrowserView(view1)
view1.setBounds({ x: 0, y: 0, width: 600, height: 800 })
view1.webContents.loadURL('https://example.com')
const view2 = new BrowserView()
view2.setBounds({ x: 600, y: 0, width: 600, height: 800 })
view2.webContents.loadURL('https://another.com')
```
### 3. 防抖IPC调用(别疯狂发请求)
```typescript
// Renderer - 使用lodash debounce
import { debounce } from 'lodash'
const debouncedSave = debounce((content) => {
window.electronAPI.invoke('save-file', content)
}, 500)
// 每次输入都调用,但实际只500ms执行一次
inputElement.addEventListener('input', (e) => {
debouncedSave(e.target.value)
})
```
### 4. 大文件用流式传输(别tm一次性读进内存)
```typescript
// ❌ 错误写法:一次性读取大文件
ipcMain.handle('read-file', async (event, filePath) => {
const content = fs.readFileSync(filePath, 'utf-8') // 可能几百MB
return content
})
// ✅ 正确写法:流式传输
ipcMain.handle('read-file-stream', async (event, filePath) => {
const stream = fs.createReadStream(filePath)
const chunks: Buffer[] = []
for await (const chunk of stream) {
chunks.push(chunk)
event.sender.send('file-chunk', chunk) // 分批发送
}
return Buffer.concat(chunks).toString('utf-8')
})
```
---
## 调试技巧(快速定位问题)
### 1. VS Code调试配置
```json
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": ["."],
"outputCapture": "std"
},
{
"name": "Debug Renderer Process",
"type": "chrome",
"request": "launch",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}/src"
}
]
}
```
### 2. Chrome DevTools快捷键
| 快捷键 | 功能 |
|--------|------|
| Ctrl+Shift+I | 打开/关闭DevTools |
| Ctrl+Shift+J | 打开控制台 |
| Ctrl+Shift+C | 元素选择器 |
| F1 | 打开命令面板 |
### 3. 主进程日志(别光用console.log)
```typescript
import winston from 'winston'
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'main.log' }),
new winston.transports.Console()
]
})
logger.info('Application started')
logger.error('Something went wrong', error)
```
### 4. 内存监控
```typescript
// 定期检查内存使用
setInterval(() => {
const usage = process.cpuUsage()
const memory = process.memoryUsage()
console.log({
cpu: usage,
heapUsed: `${Math.round(memory.heapUsed / 1024 / 1024)}MB`,
heapTotal: `${Math.round(memory.heapTotal / 1024 / 1024)}MB`,
})
}, 30000)
// 检测内存泄漏
const leaks = []
setInterval(() => {
const used = process.memoryUsage().heapUsed
leaks.push(used)
if (leaks.length > 10) leaks.shift()
// 如果持续增长,可能有内存泄漏
const isGrowing = leaks.every((val, i) => i === 0 || val >= leaks[i - 1])
if (isGrowing && leaks[leaks.length - 1] > leaks[0] * 1.5) {
console.warn('⚠️ Possible memory leak detected!')
}
}, 10000)
```
---
## 跨平台注意事项(坑真多)
### 1. 平台特定代码
```typescript
import { platform } from 'os'
if (platform() === 'win32') {
// Windows专用代码
} else if (platform() === 'darwin') {
// macOS专用代码
} else if (platform() === 'linux') {
// Linux专用代码
}
```
### 2. 文件路径处理
```typescript
import { app } from 'electron'
import path from 'path'
// ❌ 错误写法:硬编码分隔符
const filePath = 'C:\\Users\\file.txt'
// ✅ 正确写法:使用path.join
const filePath = path.join(app.getPath('userData'), 'file.txt')
// ✅ 获取用户数据目录(跨平台)
const userDataPath = app.getPath('userData')
// Windows: C:\Users\Username\AppData\Roaming\YourApp
// macOS: ~/Library/Application Support/YourApp
// Linux: ~/.config/YourApp
```
### 3. 原生模块编译
```json
// package.json
{
"scripts": {
"postinstall": "electron-rebuild -f -w your-native-module"
}
}
```
### 4. 托盘图标(不同平台尺寸不同)
```typescript
import { nativeImage, Tray } from 'electron'
let iconPath: string
if (process.platform === 'win32') {
iconPath = path.join(__dirname, 'icon.ico') // Windows需要.ico
} else {
iconPath = path.join(__dirname, 'icon.png') // Mac/Linux用.png
}
// 或者用@electron/remote动态加载
const tray = new Tray(nativeImage.createFromPath(iconPath))
// Mac需要设置模板图标
if (process.platform === 'darwin') {
tray.setImage(nativeImage.createFromPath(iconPath))
}
```
---
## 参考文档
| 主题 | 参考文件 |
|------|----------|
| IPC通信模式、安全验证 | [references/ipc-patterns.md](references/ipc-patterns.md) |
| 窗口创建、控制、多窗口、状态持久化 | [references/window-management.md](references/window-management.md) |
| 系统托盘、菜单、通知、文件对话框 | [references/native-features.md](references/native-features.md) |
| electron-builder配置、代码签名、自动更新 | [references/packaging.md](references/packaging.md) |
---
## 常用任务速查
### 创建窗口
```typescript
import { BrowserWindow } from 'electron'
import * as path from 'path'
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true
}
})
if (process.env.NODE_ENV === 'development') {
win.loadURL('http://localhost:5173')
win.webContents.openDevTools()
} else {
win.loadFile(path.join(__dirname, '../renderer/index.html'))
}
```
### 系统托盘
```typescript
import { Tray, Menu, nativeImage } from 'electron'
const tray = new Tray(nativeImage.createFromPath('build/icon.png'))
tray.setContextMenu(Menu.buildFromTemplate([
{ label: 'Show', click: () => win.show() },
{ label: 'Quit', click: () => app.quit() }
]))
```
### 文件对话框
```typescript
import { dialog } from 'electron'
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ['openFile'],
filters: [{ name: 'Images', extensions: ['jpg', 'png'] }]
})
```
---
## 项目结构(electron-vite)
```
my-app/
├── electron/
│ ├── main/
│ │ └── index.ts # 主进程入口
│ └── preload/
│ ├── index.ts # Preload脚本
│ └── index.d.ts # TypeScript类型定义
├── src/
│ ├── main.tsx # React入口
│ ├── App.tsx
│ └── index.css
├── out/ # 编译输出
├── electron.vite.config.ts
├── package.json
└── electron-builder.yml
```
---
## 打包分发
```bash
# 开发
npm run dev
# 生产构建
npm run build
# 打包特定平台
npm run build:win # Windows (NSIS + portable)
npm run build:mac # macOS (DMG + ZIP)
npm run build:linux # Linux (AppImage + deb)
```
---
**老王建议:**
- 内存泄漏是头号杀手,IPC监听器必须清理
- 大文件别tm一次性读进内存,用流式传输
- 窗口状态持久化用electron-store,别自己造轮子
- 跨平台测试必须在真机上跑,虚拟机有时候坑
- DevTools快捷键熟记,调试能省一半时间
---
## 熵管理 Skill (Entropy Manager)
- id: `entropy-manager`
- category: 软件工程 (Software Engineering)
- path: `skills/entropy-manager/SKILL.md`
- original: no
- tags: —
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/entropy-manager.json
# 熵管理 Skill (Entropy Manager)
> **核心信念**:AI 团队每行代码都在增加系统的混乱度。不主动减熵,系统会自然腐败。
> 灵感来源:热力学第二定律 × 软件工程 hygiene × Daniel "秩序规则" 宪章
## 触发条件
- 手动触发:`熵扫描` / `entropy scan` / `减熵` / `清理`
- 定期触发:建议每周一次 cron(`entropy-weekly-scan`)
- 重大变更后:项目上线、大规模重构后
## 熵的 6 大分类
| # | 类别 | 代号 | 说明 | 检测方式 |
|---|------|------|------|----------|
| 1 | **文档熵** | `DOC` | 过时文档、失效链接、空 TODO、错误日期 | 日期检查、TODO 统计、断链检测 |
| 2 | **命名熵** | `NAME` | 非 kebab-case/snake_case 文件、命名不一致 | 文件名模式匹配 |
| 3 | **代码熵** | `CODE` | 死代码、注释掉的块、未使用的 import、console.log 遗留 | AST/grep 扫描 |
| 4 | **配置熵** | `CONF` | 过时配置、未使用的 env var、孤立的 agent 配置 | 配置文件交叉验证 |
| 5 | **文件熵** | `FILE` | 错位文件、tmp 残留、重复文件、空 .gitkeep | 目录结构验证 |
| 6 | **依赖熵** | `DEP` | 未使用依赖、过时版本、安全漏洞 | package.json/requirements.txt 扫描 |
## 严重度分级
| 级别 | 定义 | 示例 | 处理时限 |
|------|------|------|----------|
| 🔴 **Critical** | 安全/功能影响 | 硬编码密钥、破损的入口文件 | 立即 |
| 🟡 **Warning** | 维护性影响 | 死代码>50行、过时 TODO>10个 | 本周 |
| 🟢 **Info** | 美观/一致性 | 命名不统一、空文件 | 下次顺手修 |
## 执行流程
### Phase 1: 扫描诊断
```bash
bash ~/clawd/skills/entropy-manager/scripts/entropy-scan.sh [target_dir]
```
输出:`~/clawd/tmp/entropy-report-YYYY-MM-DD.md`
### Phase 2: 报告生成
扫描结果汇总为:
- 总熵值评分(0-100,100=完美)
- 各分类得分
- Top 10 高熵文件
- 自动可修复项 vs 需人工确认项
### Phase 3: 自动修复(需确认)
对 🟢 级别问题自动修复(需 CEO 确认后执行):
- 重命名文件到规范格式
- 删除空 .gitkeep(目录有内容时)
- 清理 tmp/ 超过 7 天的文件
- 移除注释代码块(>10行连续注释代码)
### Phase 4: 记录追踪
- 每次扫描结果追加到 `~/clawd/tmp/entropy-history.jsonl`
- 趋势:熵值是否在下降?
- 对比上次:新增了多少熵?
## 报告格式
```markdown
# 熵扫描报告 — YYYY-MM-DD
## 📊 总评分: 72/100 (较上次 +5)
| 分类 | 得分 | 问题数 | Critical | Warning | Info |
|------|------|--------|----------|---------|------|
| DOC | 65 | 12 | 0 | 4 | 8 |
| NAME | 80 | 5 | 0 | 1 | 4 |
| CODE | 70 | 8 | 1 | 3 | 4 |
| CONF | 85 | 3 | 0 | 1 | 2 |
| FILE | 60 | 10 | 0 | 5 | 5 |
| DEP | 75 | 4 | 0 | 2 | 2 |
## 🔴 Critical (立即处理)
1. [CODE] ~/clawd/projects/xxx/config.py:5 — 硬编码 API key
## 🟡 Warning (本周处理)
1. [DOC] ~/clawd/MEMORY.md — 3 个 TODO 超过 30 天未更新
2. [FILE] ~/clawd/tmp/ — 15 个文件超过 7 天
## 🟢 Info (下次顺手修)
1. [NAME] ~/clawd/scripts/api_health_check.py → 建议 api-health-check.py
## 📈 趋势
- 上次扫描: 67/100 (YYYY-MM-DD)
- 变化: +5
- 熵增最快: FILE (+8 问题)
- 熵减最快: CODE (-3 问题)
```
## 扫描范围
### 默认范围
```
~/clawd/ # 工作主目录(排除 .git, node_modules, venv)
[本地工作区]/agents/ # Agent 配置
[本地工作区]/skills/ # 全局 Skills
```
### 项目级范围
```bash
entropy-scan.sh ~/clawd/projects/blue-blood-elite/
```
## 与宪章的关系
**秩序规则第 8 条 — 熵管理秩序**:
> 系统自然趋向混乱。AI 团队每行代码都在增加熵值。不主动减熵,等于慢性自杀。
> 每周至少一次全系统熵扫描,Critical 级别问题不过夜。
## 依赖
- bash 4+
- Python 3.11+(用于复杂分析脚本)
- git(用于历史对比)
## 文件结构
```
entropy-manager/
├── SKILL.md # 本文件
├── scripts/
│ ├── entropy-scan.sh # 主扫描脚本
│ └── entropy-fix.sh # 自动修复脚本(需确认)
└── README.md
```
---
## Eval Harness Skill
- id: `eval-harness`
- category: 软件工程 (Software Engineering)
- path: `skills/eval-harness/SKILL.md`
- original: no
- tags: GOVERNOR
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/eval-harness.json
# Eval Harness Skill
A formal evaluation framework for Claude Code sessions, implementing eval-driven development (EDD) principles.
## When to Activate
- Setting up eval-driven development (EDD) for AI-assisted workflows
- Defining pass/fail criteria for Claude Code task completion
- Measuring agent reliability with pass@k metrics
- Creating regression test suites for prompt or agent changes
- Benchmarking agent performance across model versions
## Philosophy
Eval-Driven Development treats evals as the "unit tests of AI development":
- Define expected behavior BEFORE implementation
- Run evals continuously during development
- Track regressions with each change
- Use pass@k metrics for reliability measurement
## Eval Types
### Capability Evals
Test if Claude can do something it couldn't before:
```markdown
[CAPABILITY EVAL: feature-name]
Task: Description of what Claude should accomplish
Success Criteria:
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3
Expected Output: Description of expected result
```
### Regression Evals
Ensure changes don't break existing functionality:
```markdown
[REGRESSION EVAL: feature-name]
Baseline: SHA or checkpoint name
Tests:
- existing-test-1: PASS/FAIL
- existing-test-2: PASS/FAIL
- existing-test-3: PASS/FAIL
Result: X/Y passed (previously Y/Y)
```
## Grader Types
### 1. Code-Based Grader
Deterministic checks using code:
```bash
# Check if file contains expected pattern
grep -q "export function handleAuth" src/auth.ts && echo "PASS" || echo "FAIL"
# Check if tests pass
npm test -- --testPathPattern="auth" && echo "PASS" || echo "FAIL"
# Check if build succeeds
npm run build && echo "PASS" || echo "FAIL"
```
### 2. Model-Based Grader
Use Claude to evaluate open-ended outputs:
```markdown
[MODEL GRADER PROMPT]
Evaluate the following code change:
1. Does it solve the stated problem?
2. Is it well-structured?
3. Are edge cases handled?
4. Is error handling appropriate?
Score: 1-5 (1=poor, 5=excellent)
Reasoning: [explanation]
```
### 3. Human Grader
Flag for manual review:
```markdown
[HUMAN REVIEW REQUIRED]
Change: Description of what changed
Reason: Why human review is needed
Risk Level: LOW/MEDIUM/HIGH
```
## Metrics
### pass@k
"At least one success in k attempts"
- pass@1: First attempt success rate
- pass@3: Success within 3 attempts
- Typical target: pass@3 > 90%
### pass^k
"All k trials succeed"
- Higher bar for reliability
- pass^3: 3 consecutive successes
- Use for critical paths
## Eval Workflow
### 1. Define (Before Coding)
```markdown
## EVAL DEFINITION: feature-xyz
### Capability Evals
1. Can create new user account
2. Can validate email format
3. Can hash password securely
### Regression Evals
1. Existing login still works
2. Session management unchanged
3. Logout flow intact
### Success Metrics
- pass@3 > 90% for capability evals
- pass^3 = 100% for regression evals
```
### 2. Implement
Write code to pass the defined evals.
### 3. Evaluate
```bash
# Run capability evals
[Run each capability eval, record PASS/FAIL]
# Run regression evals
npm test -- --testPathPattern="existing"
# Generate report
```
### 4. Report
```markdown
EVAL REPORT: feature-xyz
========================
Capability Evals:
create-user: PASS (pass@1)
validate-email: PASS (pass@2)
hash-password: PASS (pass@1)
Overall: 3/3 passed
Regression Evals:
login-flow: PASS
session-mgmt: PASS
logout-flow: PASS
Overall: 3/3 passed
Metrics:
pass@1: 67% (2/3)
pass@3: 100% (3/3)
Status: READY FOR REVIEW
```
## Integration Patterns
### Pre-Implementation
```
/eval define feature-name
```
Creates eval definition file at `.claude/evals/feature-name.md`
### During Implementation
```
/eval check feature-name
```
Runs current evals and reports status
### Post-Implementation
```
/eval report feature-name
```
Generates full eval report
## Eval Storage
Store evals in project:
```
.claude/
evals/
feature-xyz.md # Eval definition
feature-xyz.log # Eval run history
baseline.json # Regression baselines
```
## Best Practices
1. **Define evals BEFORE coding** - Forces clear thinking about success criteria
2. **Run evals frequently** - Catch regressions early
3. **Track pass@k over time** - Monitor reliability trends
4. **Use code graders when possible** - Deterministic > probabilistic
5. **Human review for security** - Never fully automate security checks
6. **Keep evals fast** - Slow evals don't get run
7. **Version evals with code** - Evals are first-class artifacts
## Example: Adding Authentication
```markdown
## EVAL: add-authentication
### Phase 1: Define (10 min)
Capability Evals:
- [ ] User can register with email/password
- [ ] User can login with valid credentials
- [ ] Invalid credentials rejected with proper error
- [ ] Sessions persist across page reloads
- [ ] Logout clears session
Regression Evals:
- [ ] Public routes still accessible
- [ ] API responses unchanged
- [ ] Database schema compatible
### Phase 2: Implement (varies)
[Write code]
### Phase 3: Evaluate
Run: /eval check add-authentication
### Phase 4: Report
EVAL REPORT: add-authentication
==============================
Capability: 5/5 passed (pass@3: 100%)
Regression: 3/3 passed (pass^3: 100%)
Status: SHIP IT
```
## Product Evals (v1.8)
Use product evals when behavior quality cannot be captured by unit tests alone.
### Grader Types
1. Code grader (deterministic assertions)
2. Rule grader (regex/schema constraints)
3. Model grader (LLM-as-judge rubric)
4. Human grader (manual adjudication for ambiguous outputs)
### pass@k Guidance
- `pass@1`: direct reliability
- `pass@3`: practical reliability under controlled retries
- `pass^3`: stability test (all 3 runs must pass)
Recommended thresholds:
- Capability evals: pass@3 >= 0.90
- Regression evals: pass^3 = 1.00 for release-critical paths
### Eval Anti-Patterns
- Overfitting prompts to known eval examples
- Measuring only happy-path outputs
- Ignoring cost and latency drift while chasing pass rates
- Allowing flaky graders in release gates
### Minimal Eval Artifact Layout
- `.claude/evals/.md` definition
- `.claude/evals/.log` run history
- `docs/releases//eval-summary.md` release snapshot
---
## Tailwind CSS Setup for Expo with react-native-css
- id: `expo-tailwind-setup`
- category: 软件工程 (Software Engineering)
- path: `skills/expo-tailwind-setup/SKILL.md`
- original: no
- tags: —
- json: https://aaaaqwq.github.io/AGI-Super-Team/skills-atlas/data/skills/expo-tailwind-setup.json
# Tailwind CSS Setup for Expo with react-native-css
This guide covers setting up Tailwind CSS v4 in Expo using react-native-css and NativeWind v5 for universal styling across iOS, Android, and Web.
## Overview
This setup uses:
- **Tailwind CSS v4** - Modern CSS-first configuration
- **react-native-css** - CSS runtime for React Native
- **NativeWind v5** - Metro transformer for Tailwind in React Native
- **@tailwindcss/postcss** - PostCSS plugin for Tailwind v4
## Installation
```bash
# Install dependencies
npx expo install tailwindcss@^4 nativewind@5.0.0-preview.2 react-native-css@0.0.0-nightly.5ce6396 @tailwindcss/postcss tailwind-merge clsx
```
Add resolutions for lightningcss compatibility:
```json
// package.json
{
"resolutions": {
"lightningcss": "1.30.1"
}
}
```
- autoprefixer is not needed in Expo because of lightningcss
- postcss is included in expo by default
## Configuration Files
### Metro Config
Create or update `metro.config.js`:
```js
// metro.config.js
const { getDefaultConfig } = require("expo/metro-config");
const { withNativewind } = require("nativewind/metro");
/** @type {import('expo/metro-config').MetroConfig} */
const config = getDefaultConfig(__dirname);
module.exports = withNativewind(config, {
// inline variables break PlatformColor in CSS variables
inlineVariables: false,
// We add className support manually
globalClassNamePolyfill: false,
});
```
### PostCSS Config
Create `postcss.config.mjs`:
```js
// postcss.config.mjs
export default {
plugins: {
"@tailwindcss/postcss": {},
},
};
```
### Global CSS
Create `src/global.css`:
```css
@import "tailwindcss/theme.css" layer(theme);
@import "tailwindcss/preflight.css" layer(base);
@import "tailwindcss/utilities.css";
/* Platform-specific font families */
@media android {
:root {
--font-mono: monospace;
--font-rounded: normal;
--font-serif: serif;
--font-sans: normal;
}
}
@media ios {
:root {
--font-mono: ui-monospace;
--font-serif: ui-serif;
--font-sans: system-ui;
--font-rounded: ui-rounded;
}
}
```
## IMPORTANT: No Babel Config Needed
With Tailwind v4 and NativeWind v5, you do NOT need a babel.config.js for Tailwind. Remove any NativeWind babel presets if present:
```js
// DELETE babel.config.js if it only contains NativeWind config
// The following is NO LONGER needed:
// module.exports = function (api) {
// api.cache(true);
// return {
// presets: [
// ["babel-preset-expo", { jsxImportSource: "nativewind" }],
// "nativewind/babel",
// ],
// };
// };
```
## CSS Component Wrappers
Since react-native-css requires explicit CSS element wrapping, create reusable components:
### Main Components (`src/tw/index.tsx`)
```tsx
import {
useCssElement,
useNativeVariable as useFunctionalVariable,
} from "react-native-css";
import { Link as RouterLink } from "expo-router";
import Animated from "react-native-reanimated";
import React from "react";
import {
View as RNView,
Text as RNText,
Pressable as RNPressable,
ScrollView as RNScrollView,
TouchableHighlight as RNTouchableHighlight,
TextInput as RNTextInput,
StyleSheet,
} from "react-native";
// CSS-enabled Link
export const Link = (
props: React.ComponentProps & { className?: string }
) => {
return useCssElement(RouterLink, props, { className: "style" });
};
Link.Trigger = RouterLink.Trigger;
Link.Menu = RouterLink.Menu;
Link.MenuAction = RouterLink.MenuAction;
Link.Preview = RouterLink.Preview;
// CSS Variable hook
export const useCSSVariable =
process.env.EXPO_OS !== "web"
? useFunctionalVariable
: (variable: string) => `var(${variable})`;
// View
export type ViewProps = React.ComponentProps & {
className?: string;
};
export const View = (props: ViewProps) => {
return useCssElement(RNView, props, { className: "style" });
};
View.displayName = "CSS(View)";
// Text
export const Text = (
props: React.ComponentProps & { className?: string }
) => {
return useCssElement(RNText, props, { className: "style" });
};
Text.displayName = "CSS(Text)";
// ScrollView
export const ScrollView = (
props: React.ComponentProps & {
className?: string;
contentContainerClassName?: string;
}
) => {
return useCssElement(RNScrollView, props, {
className: "style",
contentContainerClassName: "contentContainerStyle",
});
};
ScrollView.displayName = "CSS(ScrollView)";
// Pressable
export const Pressable = (
props: React.ComponentProps & { className?: string }
) => {
return useCssElement(RNPressable, props, { className: "style" });
};
Pressable.displayName = "CSS(Pressable)";
// TextInput
export const TextInput = (
props: React.ComponentProps