---
name: tavily-web
description: "Web search, content extraction, crawling, and research capabilities using Tavily API. Use when you need to search the web for current information, extracting content from URLs, or crawling websites."
risk: critical
source: community
date_added: "2026-02-27"
---

# tavily-web

## Overview
Web search, content extraction, crawling, and research capabilities using Tavily API

## When to Use
- When you need to search the web for current information
- When extracting content from URLs
- When crawling websites

## Installation
```bash
npx skills add -g BenedictKing/tavily-web
```

## Step-by-Step Guide
1. Install the skill using the command above
2. Configure Tavily API key
3. Use naturally in Claude Code conversations

## Examples
See [GitHub Repository](https://github.com/BenedictKing/tavily-web) for examples.

## Best Practices
- Configure API keys via environment variables

## Troubleshooting
See the GitHub repository for troubleshooting guides.

## Related Skills
- context7-auto-research, exa-search, firecrawl-scraper, codex-review

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tcm-constitution-analyzer
description: 分析中医体质数据、识别体质类型、评估体质特征,并提供个性化养生建议。支持与营养、运动、睡眠等健康数据的关联分析。
allowed-tools: Read, Grep, Glob, Write
risk: critical
source: community
---

# 中医体质辨识分析器技能

分析中医体质数据,识别体质类型,评估体质特征,并提供个性化养生改善建议。

## When to Use
- 你需要根据中医体质分类标准评估用户体质，并识别主导体质与兼夹体质。
- 你想结合营养、运动、睡眠等健康数据分析体质特征、风险和变化趋势。
- 你需要面向个体化调理的养生建议、趋势跟踪和相关性分析结果。

## 功能

### 1. 体质辨识评估

基于《中医体质分类与判定》标准进行体质辨识。

**评估维度**:
- 9种体质类型评分(平和质、气虚质、阳虚质、阴虚质、痰湿质、湿热质、血瘀质、气郁质、特禀质)
- 主体质判定
- 兼夹体质识别
- 体质特征分析

**评估方法**:
- 60题标准化问卷
- 5分制评分(没有/很少/有时/经常/总是)
- 转化分数计算(0-100分)

**输出**:
- 体质类型判定结果
- 各体质评分
- 体质特征描述
- 个体化养生建议

### 2. 体质特征分析

综合评估用户的体质特征。

**分析内容**:
- **形体特征**:
  - 体型特点
  - 面色表现
  - 舌象脉象

- **心理特征**:
  - 性格特点
  - 情绪倾向

- **发病倾向**:
  - 易感疾病
  - 健康风险

- **适应能力**:
  - 环境适应
  - 季节适应

**输出**:
- 体质类型分类
- 特征描述
- 风险评估
- 调理优先级

### 3. 体质变化趋势分析

追踪体质变化,评估调理效果。

**分析内容**:
- 多次评估对比
- 评分变化趋势
- 体质稳定性分析
- 调理效果评估

**输出**:
- 趋势图表
- 改善幅度
- 稳定性评估
- 继续调理建议

### 4. 相关性分析

分析体质与其他健康指标的相关性。

**支持的相关性分析**:
- **体质 ↔ 营养**:
  - 体质类型与饮食偏好的关系
  - 营养状况对体质的影响
  - 个性化饮食建议

- **体质 ↔ 运动**:
  - 不同体质适合的运动类型
  - 运动对体质改善的作用

- **体质 ↔ 睡眠**:
  - 体质与睡眠质量的关系
  - 睡眠对体质的影响

- **体质 ↔ 慢性病**:
  - 不同体质易患疾病
  - 体质与疾病的关系

**输出**:
- 相关系数
- 相关性强度
- 统计显著性
- 实践建议

### 5. 个性化建议生成

基于体质类型生成个性化养生建议。

**建议类型**:
- **饮食调养**:
  - 宜食食物清单
  - 忌食食物清单
  - 推荐食谱
  - 饮食原则

- **起居调摄**:
  - 作息建议
  - 环境要求
  - 生活习惯

- **运动锻炼**:
  - 推荐运动类型
  - 运动频次和强度
  - 注意事项

- **情志调摄**:
  - 情绪管理
  - 心理调节

- **穴位保健**:
  - 推荐穴位
  - 按摩方法
  - 艾灸建议

- **中药调理**:
  - 推荐方剂
  - 方剂组成
  - 用法用量
  - 注意事项

**建议依据**:
- 中医体质理论
- 用户体质类型
- 季节因素
- 用户健康状况

---

## 使用说明

### 触发条件

当用户请求以下内容时触发本技能:
- 中医体质辨识评估
- 体质类型查询
- 体质特征分析
- 中医养生建议
- 体质趋势分析
- 体质与其他健康指标的关联分析

### 执行步骤

#### 步骤 1: 确定分析范围

明确用户请求的分析类型:
- 体质辨识评估
- 体质特征查询
- 养生建议获取
- 趋势分析
- 相关性分析

#### 步骤 2: 读取数据

**主要数据源**:
1. `data/constitutions.json` - 体质知识库
2. `data/constitution-recommendations.json` - 养生建议库
3. `data-example/tcm-constitution-tracker.json` - 体质追踪主数据
4. `data-example/tcm-constitution-logs/YYYY-MM/YYYY-MM-DD.json` - 每日评估记录

**关联数据源**:
1. `data-example/profile.json` - 基础信息
2. `data-example/nutrition-tracker.json` - 营养数据
3. `data-example/fitness-tracker.json` - 运动数据
4. `data-example/sleep-tracker.json` - 睡眠数据

#### 步骤 3: 数据分析

根据分析类型执行相应的分析算法:

**体质评分算法**:
```python
def calculate_constitution_scores(answers):
    """
    基于《中医体质分类与判定》标准

    计算公式:
    转化分数 = [(原始分数 - 题目数) / (题目数 × 4)] × 100

    其中:
    - 原始分数 = 各题目得分之和
    - 题目数 = 该体质的问题数量
    """
    scores = {}
    for constitution, questions in CONSTITUTION_QUESTIONS.items():
        original_score = sum(answers[q] for q in questions)
        question_count = len(questions)
        converted_score = ((original_score - question_count) / (question_count * 4)) * 100
        scores[constitution] = round(converted_score, 1)
    return scores
```

**体质判定算法**:
```python
def determine_constitution_type(scores):
    """
    判定逻辑:
    1. 平和质判定:
       - 得分 ≥ 60分
       - 其他8种体质得分均 < 40分

    2. 偏颇体质判定:
       - 得分最高的体质为判定结果

    3. 兼夹体质判定:
       - 次高分的体质得分 ≥ 40分
       - 则为兼夹体质
    """
    peaceful_score = scores['平和质']
    other_scores = {k: v for k, v in scores.items() if k != '平和质'}

    # 判定是否为平和质
    if peaceful_score >= 60 and all(s < 40 for s in other_scores.values()):
        return {
            'primary': '平和质',
            'secondary': [],
            'type': 'balanced'
        }

    # 偏颇体质判定
    sorted_scores = sorted(other_scores.items(), key=lambda x: x[1], reverse=True)
    primary = sorted_scores[0][0]

    # 判断兼夹体质
    secondary = [k for k, v in sorted_scores[1:3] if v >= 40]

    return {
        'primary': primary,
        'secondary': secondary,
        'type': 'compound' if secondary else 'single'
    }
```

**趋势分析算法**:
- 线性回归计算趋势
- 移动平均平滑波动
- 统计显著性检验

#### 步骤 4: 生成报告

按照标准格式输出分析报告(见"输出格式"部分)

---

## 输出格式

### 体质辨识评估报告

```markdown
# 中医体质辨识评估报告

## 评估日期
2025-06-20

## 评估结果

### 体质类型判定
- **主体质**: 气虚质
- **兼夹体质**: 阳虚质
- **体质类型**: 兼夹体质

### 各体质评分

| 体质类型 | 评分 | 判定 |
|---------|------|------|
| 气虚质 | 78.5 | ⚠ 偏颇 |
| 阳虚质 | 62.3 | ⚠ 偏颇 |
| 平和质 | 42.1 | 正常 |
| 痰湿质 | 38.7 | 正常 |
| 气郁质 | 35.2 | 正常 |
| 阴虚质 | 32.1 | 正常 |
| 湿热质 | 28.4 | 正常 |
| 血瘀质 | 25.6 | 正常 |
| 特禀质 | 18.3 | 正常 |

---

## 体质特征分析

### 气虚质特征

**形体特征**:
- 肌肉松软
- 容易疲乏
- 声音低弱
- 喜静懒言
- 容易出汗

**心理特征**:
- 性格内向
- 不喜冒险
- 情绪不稳定

**发病倾向**:
- 易感冒
- 易内脏下垂
- 易疲劳

**适应能力**:
- 不耐受风、寒、暑、湿邪
- 秋季易发病

### 阳虚质特征

**形体特征**:
- 畏寒怕冷
- 手足不温
- 喜热饮食

**心理特征**:
- 性格多沉静
- 内向

**发病倾向**:
- 易患痰饮、肿胀、腹泻
- 易感寒邪

**适应能力**:
- 不耐寒邪,耐受夏热
- 冬季易发病

---

## 养生建议

### 饮食调养

**原则**: 补气健脾,温补肾阳

**宜食食物**:
- 补气类: 山药、大枣、黄芪、人参、白术
- 温阳类: 羊肉、韭菜、花椒、生姜、桂圆
- 健脾类: 薏苡仁、茯苓、扁豆

**忌食食物**:
- 生冷寒凉: 冰淇淋、冰镇饮料、生鱼片
- 油腻厚味: 油炸食品、肥肉
- 辛辣燥热: 辣椒、花椒

**推荐食谱**:
1. 黄芪炖鸡
2. 山药粥
3. 红枣茯苓粥
4. 当归生姜羊肉汤

**饮食建议**:
- 少食多餐,细嚼慢咽
- 饮食宜温热,忌生冷
- 饭后适当休息

### 起居调摄

**作息建议**:
- 保证充足睡眠(8小时以上)
- 早睡晚起
- 避免熬夜

**环境要求**:
- 保持环境温暖干燥
- 避免受风寒
- 注意保暖,特别是腰腹部和脚部

**生活习惯**:
- 避免过度劳累
- 劳逸结合
- 可适当晒太阳
- 温水泡脚

### 运动锻炼

**原则**: 温和运动,避免剧烈

**推荐运动**:
- 太极拳
- 八段锦
- 散步
- 气功
- 瑜伽

**运动建议**:
- 频率: 每日1-2次
- 时长: 每次20-30分钟
- 强度: 低至中等强度
- 注意: 以不感到过度疲劳为宜

**注意事项**:
- 避免剧烈运动
- 运动后及时休息
- 循序渐进
- 避免在寒冷环境中运动

### 情志调摄

**原则**: 保持心情舒畅,避免过度思虑

**调摄方法**:
- 保持积极乐观
- 避免过度思虑
- 适当参加社交活动
- 学会放松

**情绪管理**:
- 培养兴趣爱好
- 保持社交活动
- 学会调节情绪

### 穴位保健

**推荐穴位**:

#### 1. 足三里
- **位置**: 小腿外侧,膝眼下3寸
- **功效**: 健脾益气,强壮身体
- **方法**: 每日按揉3-5分钟,可艾灸

#### 2. 气海
- **位置**: 肚脐下1.5寸
- **功效**: 培补元气
- **方法**: 每日按揉3-5分钟,可艾灸

#### 3. 关元
- **位置**: 肚脐下3寸
- **功效**: 培元固本,温补肾阳
- **方法**: 每日按揉3-5分钟,可艾灸10-15分钟

### 中药调理

⚠ **重要提醒**: 以下内容仅供中医师参考,不可自行抓药服用

**推荐方剂**: 四君子汤加减

**方源**: 《太平惠民和剂局方》

**方剂组成**:
- 人参: 9-15g, 大补元气
- 白术: 9-12g, 健脾益气
- 茯苓: 9-15g, 健脾渗湿
- 甘草: 6-9g, 调和诸药

**随症加减**:
- 气虚重者: 加黄芪 15-30g
- 脾虚湿盛者: 加薏苡仁 15-30g, 扁豆 10-15g
- 食少腹胀者: 加陈皮 6-9g, 砂仁 3-6g

**用法**: 水煎服,日一剂,分早晚两次温服

**注意事项**:
- ⚠ 需经专业中医师辨证后使用
- ⚠ 孕妇、儿童、体弱者需医师指导
- ⚠ 服药期间忌食生冷、油腻、辛辣食物
- ⚠ 感冒发烧时暂停服用
- ⚠ 服用期间出现不良反应立即停用并就医

---

## 季节调养建议

### 春季调养
- 养阳为主,顺应生发之气
- 多食韭菜、菠菜、山药
- 保持心情舒畅,适当运动
- 注意防风保暖

### 夏季调养
- 清暑热,养心神
- 多食绿豆、冬瓜、苦瓜
- 注意防暑降温
- 保持心情平和

### 秋季调养
- 养收润燥,养肺
- 多食银耳、百合、梨
- 注意保暖,避免受凉
- 保持情绪稳定

### 冬季调养
- 养藏为主,温补肾阳
- 多食羊肉、核桃、栗子
- 注意保暖,特别是腰腹部
- 早睡晚起,避免过度劳累

---

## 与其他健康指标的关联

### 体质与营养
- 气虚质、阳虚质: 宜温补饮食
- 阴虚质、湿热质: 宜清淡饮食
- 痰湿质: 宜低脂低糖,控制体重

### 体质与运动
- 气虚质、阳虚质: 温和运动为主
- 湿热质、痰湿质: 适度加强运动强度
- 阴虚质: 避免剧烈运动

### 体质与睡眠
- 气虚质、阳虚质: 保证充足睡眠
- 阴虚质: 避免熬夜
- 气郁质: 疏肝解郁,改善睡眠质量

### 体质与慢性病
- 痰湿质: 易患高血压、糖尿病、高脂血症
- 湿热质: 易患代谢综合征
- 血瘀质: 易患心血管疾病
- 气郁质: 易患抑郁症、焦虑症

---

## 医学安全边界

⚠ **重要声明**

本分析仅供健康参考,不构成医疗诊断或治疗建议。

### 分析能力范围

✅ **能做到**:
- 中医体质辨识评估
- 体质特征分析
- 一般性养生建议
- 中医知识普及
- 体质趋势追踪

❌ **不做到**:
- 中医疾病诊断
- 中药处方开具
- 替代中医师诊疗
- 针灸等治疗操作
- 处理严重健康问题

### 危险信号检测

在分析过程中检测以下危险信号:

1. **严重体质偏颇**:
   - 单一偏颇体质得分 > 80分
   - 多种偏颇体质兼夹

2. **健康风险提示**:
   - 痰湿质 → 高血压、糖尿病风险
   - 湿热质 → 代谢综合征风险
   - 血瘀质 → 心血管疾病风险
   - 气郁质 → 抑郁症风险

3. **就医引导**:
   - 疑似疾病症状 → 建议就医
   - 需要中药治疗 → 咨询中医师
   - 体质调理无效 → 寻求专业帮助

### 建议分级

**Level 1: 一般性建议**
- 基于中医体质理论
- 适用于一般人群
- 无需医疗监督

**Level 2: 参考性建议**
- 基于用户体质和健康状况
- 需结合个人情况
- 建议咨询中医师

**Level 3: 医疗建议**
- 涉及中药调理
- 需中医师确认
- 不得自行服用中药

---

## 数据结构

### 体质评估记录

```json
{
  "date": "2025-06-20",
  "questionnaire": {
    "questions": [
      {
        "id": 1,
        "constitution": "气虚质",
        "question": "您容易疲乏吗?",
        "answer": 4,
        "weight": 1.0
      }
    ],
    "total_questions": 60
  },
  "results": {
    "primary_constitution": "气虚质",
    "secondary_constitutions": ["阳虚质"],
    "constitution_scores": {
      "平和质": 42.1,
      "气虚质": 78.5,
      "阳虚质": 62.3,
      "阴虚质": 32.1,
      "痰湿质": 38.7,
      "湿热质": 28.4,
      "血瘀质": 25.6,
      "气郁质": 35.2,
      "特禀质": 18.3
    },
    "constitution_type": "compound"
  },
  "characteristics": {
    "physical": ["容易疲劳", "气短", "自汗"],
    "psychological": ["性格内向", "不喜欢说话"]
  },
  "recommendations": {
    "diet": {
      "principles": ["补气健脾", "温补肾阳"],
      "beneficial": ["山药", "大枣", "黄芪"],
      "avoid": ["生冷寒凉", "油腻厚味"]
    },
    "exercise": "温和运动,如太极拳、散步",
    "lifestyle": "规律作息,避免过度劳累",
    "acupoints": ["足三里", "气海", "关元"]
  }
}
```

---

## 参考资源

### 中医体质理论
- 《中医体质分类与判定》标准
- 王琦九种体质学说
- 《中医体质学》教材

### 养生原则
- 中医基础理论
- 四季养生原则
- 辨证施治原则

### 中药方剂
- 《方剂学》教材
- 《太平惠民和剂局方》
- 《金匮要略》

---

**技能版本**: v1.0
**创建日期**: 2026-01-08
**维护者**: WellAlly Tech

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tdd
description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
category: "development"
risk: "safe"
source: "community"
source_repo: "mattpocock/skills"
source_type: "community"
date_added: "2026-06-19"
author: "Matt Pocock"
license: "MIT"
license_source: "https://github.com/mattpocock/skills/blob/main/LICENSE"
tags:
  - engineering
  - workflow
  - coding-agents
tools:
  - claude-code
  - codex-cli
  - cursor
---

# Test-Driven Development

## When to Use

Use when this workflow matches the user request: Use this skill for its documented workflow.

_Source: [mattpocock/skills](https://github.com/mattpocock/skills) (MIT)._

## Philosophy

**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.

**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.

**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.

See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.

## Anti-Pattern: Horizontal Slices

**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code."

This produces **crap tests**:

- Tests written in bulk test _imagined_ behavior, not _actual_ behavior
- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior
- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine
- You outrun your headlights, committing to test structure before understanding the implementation

**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle. Because you just wrote the code, you know exactly what behavior matters and how to verify it.

```
WRONG (horizontal):
  RED:   test1, test2, test3, test4, test5
  GREEN: impl1, impl2, impl3, impl4, impl5

RIGHT (vertical):
  RED→GREEN: test1→impl1
  RED→GREEN: test2→impl2
  RED→GREEN: test3→impl3
  ...
```

## Workflow

### 1. Planning

When exploring the codebase, read `CONTEXT.md` (if it exists) so that test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching.

Before writing any code:

- [ ] Confirm with user what interface changes are needed
- [ ] Confirm with user which behaviors to test (prioritize)
- [ ] Identify opportunities for deep modules (small interface, deep implementation) — run the `/codebase-design` skill for the vocabulary and the testability checks
- [ ] List the behaviors to test (not implementation steps)
- [ ] Get user approval on the plan

Ask: "What should the public interface look like? Which behaviors are most important to test?"

**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case.

### 2. Tracer Bullet

Write ONE test that confirms ONE thing about the system:

```
RED:   Write test for first behavior → test fails
GREEN: Write minimal code to pass → test passes
```

This is your tracer bullet - proves the path works end-to-end.

### 3. Incremental Loop

For each remaining behavior:

```
RED:   Write next test → fails
GREEN: Minimal code to pass → passes
```

Rules:

- One test at a time
- Only enough code to pass current test
- Don't anticipate future tests
- Keep tests focused on observable behavior

### 4. Refactor

After all tests pass, look for [refactor candidates](refactoring.md):

- [ ] Extract duplication
- [ ] Deepen modules (move complexity behind simple interfaces)
- [ ] Apply SOLID principles where natural
- [ ] Consider what new code reveals about existing code
- [ ] Run tests after each refactor step

**Never refactor while RED.** Get to GREEN first.

## Checklist Per Cycle

```
[ ] Test describes behavior, not implementation
[ ] Test uses public interface only
[ ] Test would survive internal refactor
[ ] Code is minimal for this test
[ ] No speculative features added
```

## Limitations

- Requires the upstream tool, account, API key, or local setup when the workflow names one.
- Does not authorize destructive, production, paid, or external-message actions without explicit user approval.
- Validate generated artifacts or recommendations against the user's real sources before treating them as final.


---
name: tdd-orchestrator
description: Master TDD orchestrator specializing in red-green-refactor discipline, multi-agent workflow coordination, and comprehensive test-driven development practices.
risk: critical
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on tdd orchestrator tasks or workflows
- Needing guidance, best practices, or checklists for tdd orchestrator

## Do not use this skill when

- The task is unrelated to tdd orchestrator
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are an expert TDD orchestrator specializing in comprehensive test-driven development coordination, modern TDD practices, and multi-agent workflow management.

## Expert Purpose

Elite TDD orchestrator focused on enforcing disciplined test-driven development practices across complex software projects. Masters the complete red-green-refactor cycle, coordinates multi-agent TDD workflows, and ensures comprehensive test coverage while maintaining development velocity. Combines deep TDD expertise with modern AI-assisted testing tools to deliver robust, maintainable, and thoroughly tested software systems.

## Capabilities

### TDD Discipline & Cycle Management

- Complete red-green-refactor cycle orchestration and enforcement
- TDD rhythm establishment and maintenance across development teams
- Test-first discipline verification and automated compliance checking
- Refactoring safety nets and regression prevention strategies
- TDD flow state optimization and developer productivity enhancement
- Cycle time measurement and optimization for rapid feedback loops
- TDD anti-pattern detection and prevention (test-after, partial coverage)

### Multi-Agent TDD Workflow Coordination

- Orchestration of specialized testing agents (unit, integration, E2E)
- Coordinated test suite evolution across multiple development streams
- Cross-team TDD practice synchronization and knowledge sharing
- Agent task delegation for parallel test development and execution
- Workflow automation for continuous TDD compliance monitoring
- Integration with development tools and IDE TDD plugins
- Multi-repository TDD governance and consistency enforcement

### Modern TDD Practices & Methodologies

- Classic TDD (Chicago School) implementation and coaching
- London School (mockist) TDD practices and double management
- Acceptance Test-Driven Development (ATDD) integration
- Behavior-Driven Development (BDD) workflow orchestration
- Outside-in TDD for feature development and user story implementation
- Inside-out TDD for component and library development
- Hexagonal architecture TDD with ports and adapters testing

### AI-Assisted Test Generation & Evolution

- Intelligent test case generation from requirements and user stories
- AI-powered test data creation and management strategies
- Machine learning for test prioritization and execution optimization
- Natural language to test code conversion and automation
- Predictive test failure analysis and proactive test maintenance
- Automated test evolution based on code changes and refactoring
- Smart test doubles and mock generation with realistic behaviors

### Test Suite Architecture & Organization

- Test pyramid optimization and balanced testing strategy implementation
- Comprehensive test categorization (unit, integration, contract, E2E)
- Test suite performance optimization and parallel execution strategies
- Test isolation and independence verification across all test levels
- Shared test utilities and common testing infrastructure management
- Test data management and fixture orchestration across test types
- Cross-cutting concern testing (security, performance, accessibility)

### TDD Metrics & Quality Assurance

- Comprehensive TDD metrics collection and analysis (cycle time, coverage)
- Test quality assessment through mutation testing and fault injection
- Code coverage tracking with meaningful threshold establishment
- TDD velocity measurement and team productivity optimization
- Test maintenance cost analysis and technical debt prevention
- Quality gate enforcement and automated compliance reporting
- Trend analysis for continuous improvement identification

### Framework & Technology Integration

- Multi-language TDD support (Java, C#, Python, JavaScript, TypeScript, Go)
- Testing framework expertise (JUnit, NUnit, pytest, Jest, Mocha, testing/T)
- Test runner optimization and IDE integration across development environments
- Build system integration (Maven, Gradle, npm, Cargo, MSBuild)
- Continuous Integration TDD pipeline design and execution
- Cloud-native testing infrastructure and containerized test environments
- Microservices TDD patterns and distributed system testing strategies

### Property-Based & Advanced Testing Techniques

- Property-based testing implementation with QuickCheck, Hypothesis, fast-check
- Generative testing strategies and property discovery methodologies
- Mutation testing orchestration for test suite quality validation
- Fuzz testing integration and security vulnerability discovery
- Contract testing coordination between services and API boundaries
- Snapshot testing for UI components and API response validation
- Chaos engineering integration with TDD for resilience validation

### Test Data & Environment Management

- Test data generation strategies and realistic dataset creation
- Database state management and transactional test isolation
- Environment provisioning and cleanup automation
- Test doubles orchestration (mocks, stubs, fakes, spies)
- External dependency management and service virtualization
- Test environment configuration and infrastructure as code
- Secrets and credential management for testing environments

### Legacy Code & Refactoring Support

- Legacy code characterization through comprehensive test creation
- Seam identification and dependency breaking for testability improvement
- Refactoring orchestration with safety net establishment
- Golden master testing for legacy system behavior preservation
- Approval testing implementation for complex output validation
- Incremental TDD adoption strategies for existing codebases
- Technical debt reduction through systematic test-driven refactoring

### Cross-Team TDD Governance

- TDD standard establishment and organization-wide implementation
- Training program coordination and developer skill assessment
- Code review processes with TDD compliance verification
- Pair programming and mob programming TDD session facilitation
- TDD coaching and mentorship program management
- Best practice documentation and knowledge base maintenance
- TDD culture transformation and organizational change management

### Performance & Scalability Testing

- Performance test-driven development for scalability requirements
- Load testing integration within TDD cycles for performance validation
- Benchmark-driven development with automated performance regression detection
- Memory usage and resource consumption testing automation
- Database performance testing and query optimization validation
- API performance contracts and SLA-driven test development
- Scalability testing coordination for distributed system components

## Behavioral Traits

- Enforces unwavering test-first discipline and maintains TDD purity
- Champions comprehensive test coverage without sacrificing development speed
- Facilitates seamless red-green-refactor cycle adoption across teams
- Prioritizes test maintainability and readability as first-class concerns
- Advocates for balanced testing strategies avoiding over-testing and under-testing
- Promotes continuous learning and TDD practice improvement
- Emphasizes refactoring confidence through comprehensive test safety nets
- Maintains development momentum while ensuring thorough test coverage
- Encourages collaborative TDD practices and knowledge sharing
- Adapts TDD approaches to different project contexts and team dynamics

## Knowledge Base

- Kent Beck's original TDD principles and modern interpretations
- Growing Object-Oriented Software Guided by Tests methodologies
- Test-Driven Development by Example and advanced TDD patterns
- Modern testing frameworks and toolchain ecosystem knowledge
- Refactoring techniques and automated refactoring tool expertise
- Clean Code principles applied specifically to test code quality
- Domain-Driven Design integration with TDD and ubiquitous language
- Continuous Integration and DevOps practices for TDD workflows
- Agile development methodologies and TDD integration strategies
- Software architecture patterns that enable effective TDD practices

## Response Approach

1. **Assess TDD readiness** and current development practices maturity
2. **Establish TDD discipline** with appropriate cycle enforcement mechanisms
3. **Orchestrate test workflows** across multiple agents and development streams
4. **Implement comprehensive metrics** for TDD effectiveness measurement
5. **Coordinate refactoring efforts** with safety net establishment
6. **Optimize test execution** for rapid feedback and development velocity
7. **Monitor compliance** and provide continuous improvement recommendations
8. **Scale TDD practices** across teams and organizational boundaries

## Example Interactions

- "Orchestrate a complete TDD implementation for a new microservices project"
- "Design a multi-agent workflow for coordinated unit and integration testing"
- "Establish TDD compliance monitoring and automated quality gate enforcement"
- "Implement property-based testing strategy for complex business logic validation"
- "Coordinate legacy code refactoring with comprehensive test safety net creation"
- "Design TDD metrics dashboard for team productivity and quality tracking"
- "Create cross-team TDD governance framework with automated compliance checking"
- "Orchestrate performance TDD workflow with load testing integration"
- "Implement mutation testing pipeline for test suite quality validation"
- "Design AI-assisted test generation workflow for rapid TDD cycle acceleration"

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tdd-workflow
description: "Test-Driven Development workflow principles. RED-GREEN-REFACTOR cycle."
risk: critical
source: community
date_added: "2026-02-27"
---

# TDD Workflow

> Write tests first, code second.

---

## 1. The TDD Cycle

```
🔴 RED → Write failing test
    ↓
🟢 GREEN → Write minimal code to pass
    ↓
🔵 REFACTOR → Improve code quality
    ↓
   Repeat...
```

---

## 2. The Three Laws of TDD

1. Write production code only to make a failing test pass
2. Write only enough test to demonstrate failure
3. Write only enough code to make the test pass

---

## 3. RED Phase Principles

### What to Write

| Focus | Example |
|-------|---------|
| Behavior | "should add two numbers" |
| Edge cases | "should handle empty input" |
| Error states | "should throw for invalid data" |

### RED Phase Rules

- Test must fail first
- Test name describes expected behavior
- One assertion per test (ideally)

---

## 4. GREEN Phase Principles

### Minimum Code

| Principle | Meaning |
|-----------|---------|
| **YAGNI** | You Aren't Gonna Need It |
| **Simplest thing** | Write the minimum to pass |
| **No optimization** | Just make it work |

### GREEN Phase Rules

- Don't write unneeded code
- Don't optimize yet
- Pass the test, nothing more

---

## 5. REFACTOR Phase Principles

### What to Improve

| Area | Action |
|------|--------|
| Duplication | Extract common code |
| Naming | Make intent clear |
| Structure | Improve organization |
| Complexity | Simplify logic |

### REFACTOR Rules

- All tests must stay green
- Small incremental changes
- Commit after each refactor

---

## 6. AAA Pattern

Every test follows:

| Step | Purpose |
|------|---------|
| **Arrange** | Set up test data |
| **Act** | Execute code under test |
| **Assert** | Verify expected outcome |

---

## 7. When to Use TDD

| Scenario | TDD Value |
|----------|-----------|
| New feature | High |
| Bug fix | High (write test first) |
| Complex logic | High |
| Exploratory | Low (spike, then TDD) |
| UI layout | Low |

---

## 8. Test Prioritization

| Priority | Test Type |
|----------|-----------|
| 1 | Happy path |
| 2 | Error cases |
| 3 | Edge cases |
| 4 | Performance |

---

## 9. Anti-Patterns

| ❌ Don't | ✅ Do |
|----------|-------|
| Skip the RED phase | Watch test fail first |
| Write tests after | Write tests before |
| Over-engineer initial | Keep it simple |
| Multiple asserts | One behavior per test |
| Test implementation | Test behavior |

---

## 10. AI-Augmented TDD

### Multi-Agent Pattern

| Agent | Role |
|-------|------|
| Agent A | Write failing tests (RED) |
| Agent B | Implement to pass (GREEN) |
| Agent C | Optimize (REFACTOR) |

---

> **Remember:** The test is the specification. If you can't write a test, you don't understand the requirement.

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tdd-workflows
description: "Use when working with tdd workflows tdd cycle (Alias for tdd-workflows-tdd-cycle)"
risk: none
source: "alias"
date_added: "2026-06-02"
---

# Tdd Workflows

> **This is an alias.** The canonical skill is **`tdd-workflows-tdd-cycle`**.

This skill redirects to `tdd-workflows-tdd-cycle`. Load it from the vault:

`skill-libraries/testing/tdd-workflows-tdd-cycle/SKILL.md`

## When to Use
- Use this skill when working with tdd workflows tdd cycle (Alias for tdd-workflows-tdd-cycle)

## Why this alias exists

Users commonly search for `tdd-workflows` but the full skill name in this collection is `tdd-workflows-tdd-cycle`. This alias ensures discoverability.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

## Examples
```text
Use @tdd-workflows for this task: Use when working with tdd workflows tdd cycle (Alias for tdd-workflows-tdd-cycle).

Apply the skill to my current work and walk me through the safest next steps,
key checks, and the concrete output I should produce.
```


---
name: tdd-workflows-tdd-cycle
description: "Use when working with tdd workflows tdd cycle"
risk: critical
source: community
date_added: "2026-02-27"
---

## Use this skill when

- Working on tdd workflows tdd cycle tasks or workflows
- Needing guidance, best practices, or checklists for tdd workflows tdd cycle

## Do not use this skill when

- The task is unrelated to tdd workflows tdd cycle
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-green-refactor discipline:

[Extended thinking: This workflow enforces test-first development through coordinated agent orchestration. Each phase of the TDD cycle is strictly enforced with fail-first verification, incremental implementation, and continuous refactoring. The workflow supports both single test and test suite approaches with configurable coverage thresholds.]

## Configuration

### Coverage Thresholds
- Minimum line coverage: 80%
- Minimum branch coverage: 75%
- Critical path coverage: 100%

### Refactoring Triggers
- Cyclomatic complexity > 10
- Method length > 20 lines
- Class length > 200 lines
- Duplicate code blocks > 3 lines

## Phase 1: Test Specification and Design

### 1. Requirements Analysis
- Use Task tool with subagent_type="comprehensive-review::architect-review"
- Prompt: "Analyze requirements for: $ARGUMENTS. Define acceptance criteria, identify edge cases, and create test scenarios. Output a comprehensive test specification."
- Output: Test specification, acceptance criteria, edge case matrix
- Validation: Ensure all requirements have corresponding test scenarios

### 2. Test Architecture Design
- Use Task tool with subagent_type="unit-testing::test-automator"
- Prompt: "Design test architecture for: $ARGUMENTS based on test specification. Define test structure, fixtures, mocks, and test data strategy. Ensure testability and maintainability."
- Output: Test architecture, fixture design, mock strategy
- Validation: Architecture supports isolated, fast, reliable tests

## Phase 2: RED - Write Failing Tests

### 3. Write Unit Tests (Failing)
- Use Task tool with subagent_type="unit-testing::test-automator"
- Prompt: "Write FAILING unit tests for: $ARGUMENTS. Tests must fail initially. Include edge cases, error scenarios, and happy paths. DO NOT implement production code."
- Output: Failing unit tests, test documentation
- **CRITICAL**: Verify all tests fail with expected error messages

### 4. Verify Test Failure
- Use Task tool with subagent_type="tdd-workflows::code-reviewer"
- Prompt: "Verify that all tests for: $ARGUMENTS are failing correctly. Ensure failures are for the right reasons (missing implementation, not test errors). Confirm no false positives."
- Output: Test failure verification report
- **GATE**: Do not proceed until all tests fail appropriately

## Phase 3: GREEN - Make Tests Pass

### 5. Minimal Implementation
- Use Task tool with subagent_type="backend-development::backend-architect"
- Prompt: "Implement MINIMAL code to make tests pass for: $ARGUMENTS. Focus only on making tests green. Do not add extra features or optimizations. Keep it simple."
- Output: Minimal working implementation
- Constraint: No code beyond what's needed to pass tests

### 6. Verify Test Success
- Use Task tool with subagent_type="unit-testing::test-automator"
- Prompt: "Run all tests for: $ARGUMENTS and verify they pass. Check test coverage metrics. Ensure no tests were accidentally broken."
- Output: Test execution report, coverage metrics
- **GATE**: All tests must pass before proceeding

## Phase 4: REFACTOR - Improve Code Quality

### 7. Code Refactoring
- Use Task tool with subagent_type="tdd-workflows::code-reviewer"
- Prompt: "Refactor implementation for: $ARGUMENTS while keeping tests green. Apply SOLID principles, remove duplication, improve naming, and optimize performance. Run tests after each refactoring."
- Output: Refactored code, refactoring report
- Constraint: Tests must remain green throughout

### 8. Test Refactoring
- Use Task tool with subagent_type="unit-testing::test-automator"
- Prompt: "Refactor tests for: $ARGUMENTS. Remove test duplication, improve test names, extract common fixtures, and enhance test readability. Ensure tests still provide same coverage."
- Output: Refactored tests, improved test structure
- Validation: Coverage metrics unchanged or improved

## Phase 5: Integration and System Tests

### 9. Write Integration Tests (Failing First)
- Use Task tool with subagent_type="unit-testing::test-automator"
- Prompt: "Write FAILING integration tests for: $ARGUMENTS. Test component interactions, API contracts, and data flow. Tests must fail initially."
- Output: Failing integration tests
- Validation: Tests fail due to missing integration logic

### 10. Implement Integration
- Use Task tool with subagent_type="backend-development::backend-architect"
- Prompt: "Implement integration code for: $ARGUMENTS to make integration tests pass. Focus on component interaction and data flow."
- Output: Integration implementation
- Validation: All integration tests pass

## Phase 6: Continuous Improvement Cycle

### 11. Performance and Edge Case Tests
- Use Task tool with subagent_type="unit-testing::test-automator"
- Prompt: "Add performance tests and additional edge case tests for: $ARGUMENTS. Include stress tests, boundary tests, and error recovery tests."
- Output: Extended test suite
- Metric: Increased test coverage and scenario coverage

### 12. Final Code Review
- Use Task tool with subagent_type="comprehensive-review::architect-review"
- Prompt: "Perform comprehensive review of: $ARGUMENTS. Verify TDD process was followed, check code quality, test quality, and coverage. Suggest improvements."
- Output: Review report, improvement suggestions
- Action: Implement critical suggestions while maintaining green tests

## Incremental Development Mode

For test-by-test development:
1. Write ONE failing test
2. Make ONLY that test pass
3. Refactor if needed
4. Repeat for next test

Use this approach by adding `--incremental` flag to focus on one test at a time.

## Test Suite Mode

For comprehensive test suite development:
1. Write ALL tests for a feature/module (failing)
2. Implement code to pass ALL tests
3. Refactor entire module
4. Add integration tests

Use this approach by adding `--suite` flag for batch test development.

## Validation Checkpoints

### RED Phase Validation
- [ ] All tests written before implementation
- [ ] All tests fail with meaningful error messages
- [ ] Test failures are due to missing implementation
- [ ] No test passes accidentally

### GREEN Phase Validation
- [ ] All tests pass
- [ ] No extra code beyond test requirements
- [ ] Coverage meets minimum thresholds
- [ ] No test was modified to make it pass

### REFACTOR Phase Validation
- [ ] All tests still pass after refactoring
- [ ] Code complexity reduced
- [ ] Duplication eliminated
- [ ] Performance improved or maintained
- [ ] Test readability improved

## Coverage Reports

Generate coverage reports after each phase:
- Line coverage
- Branch coverage
- Function coverage
- Statement coverage

## Failure Recovery

If TDD discipline is broken:
1. **STOP** immediately
2. Identify which phase was violated
3. Rollback to last valid state
4. Resume from correct phase
5. Document lesson learned

## TDD Metrics Tracking

Track and report:
- Time in each phase (Red/Green/Refactor)
- Number of test-implementation cycles
- Coverage progression
- Refactoring frequency
- Defect escape rate

## Anti-Patterns to Avoid

- Writing implementation before tests
- Writing tests that already pass
- Skipping the refactor phase
- Writing multiple features without tests
- Modifying tests to make them pass
- Ignoring failing tests
- Writing tests after implementation

## Success Criteria

- 100% of code written test-first
- All tests pass continuously
- Coverage exceeds thresholds
- Code complexity within limits
- Zero defects in covered code
- Clear test documentation
- Fast test execution (< 5 seconds for unit tests)

## Notes

- Enforce strict RED-GREEN-REFACTOR discipline
- Each phase must be completed before moving to next
- Tests are the specification
- If a test is hard to write, the design needs improvement
- Refactoring is NOT optional
- Keep test execution fast
- Tests should be independent and isolated

TDD implementation for: $ARGUMENTS

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tdd-workflows-tdd-green
description: "Implement the minimal code needed to make failing tests pass in the TDD green phase."
risk: critical
source: community
date_added: "2026-02-27"
---

# Green Phase: Simple function
def product_list(request):
    products = Product.objects.all()
    return JsonResponse({'products': list(products.values())})

# Refactor: Class-based view
class ProductListView(View):
    def get(self, request):
        products = Product.objects.all()
        return JsonResponse({'products': list(products.values())})

# Refactor: Generic view
class ProductListView(ListView):
    model = Product
    context_object_name = 'products'
```

### Express Patterns

**Inline → Middleware → Service Layer:**
```javascript
// Green Phase: Inline logic
app.post('/api/users', (req, res) => {
  const user = { id: Date.now(), ...req.body };
  users.push(user);
  res.json(user);
});

// Refactor: Extract middleware
app.post('/api/users', validateUser, (req, res) => {
  const user = userService.create(req.body);
  res.json(user);
});

// Refactor: Full layering
app.post('/api/users',
  validateUser,
  asyncHandler(userController.create)
);
```

## Use this skill when

- Moving from red to green in a TDD cycle
- Implementing minimal behavior to satisfy tests
- You want to keep implementation intentionally simple

## Do not use this skill when

- You are refactoring for design or performance
- Tests are already passing and you need new requirements
- You need a full architectural redesign

## Instructions

1. Review failing tests and identify the smallest fix.
2. Implement the minimal change to pass the next test.
3. Run tests after each change to confirm progress.
4. Record shortcuts or debt for the refactor phase.

## Safety

- Avoid bypassing tests to make them pass.
- Keep changes scoped to the failing behavior only.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tdd-workflows-tdd-red
description: "Generate failing tests for the TDD red phase to define expected behavior and edge cases."
risk: critical
source: community
date_added: "2026-02-27"
---

Write comprehensive failing tests following TDD red phase principles.

[Extended thinking: Generates failing tests that properly define expected behavior using test-automator agent.]

## Use this skill when

- Starting the TDD red phase for new behavior
- You need failing tests that capture expected behavior
- You want edge case coverage before implementation

## Do not use this skill when

- You are in the green or refactor phase
- You only need performance benchmarks
- Tests must run against production systems

## Instructions

1. Identify behaviors, constraints, and edge cases.
2. Generate failing tests that define expected outcomes.
3. Ensure failures are due to missing behavior, not setup errors.
4. Document how to run tests and verify failures.

## Safety

- Keep test data isolated and avoid production environments.
- Avoid flaky external dependencies in the red phase.

## Role

Generate failing tests using Task tool with subagent_type="unit-testing::test-automator".

## Prompt Template

"Generate comprehensive FAILING tests for: $ARGUMENTS

## Core Requirements

1. **Test Structure**
   - Framework-appropriate setup (Jest/pytest/JUnit/Go/RSpec)
   - Arrange-Act-Assert pattern
   - should_X_when_Y naming convention
   - Isolated fixtures with no interdependencies

2. **Behavior Coverage**
   - Happy path scenarios
   - Edge cases (empty, null, boundary values)
   - Error handling and exceptions
   - Concurrent access (if applicable)

3. **Failure Verification**
   - Tests MUST fail when run
   - Failures for RIGHT reasons (not syntax/import errors)
   - Meaningful diagnostic error messages
   - No cascading failures

4. **Test Categories**
   - Unit: Isolated component behavior
   - Integration: Component interaction
   - Contract: API/interface contracts
   - Property: Mathematical invariants

## Framework Patterns

**JavaScript/TypeScript (Jest/Vitest)**
- Mock dependencies with `vi.fn()` or `jest.fn()`
- Use `@testing-library` for React components
- Property tests with `fast-check`

**Python (pytest)**
- Fixtures with appropriate scopes
- Parametrize for multiple test cases
- Hypothesis for property-based tests

**Go**
- Table-driven tests with subtests
- `t.Parallel()` for parallel execution
- Use `testify/assert` for cleaner assertions

**Ruby (RSpec)**
- `let` for lazy loading, `let!` for eager
- Contexts for different scenarios
- Shared examples for common behavior

## Quality Checklist

- Readable test names documenting intent
- One behavior per test
- No implementation leakage
- Meaningful test data (not 'foo'/'bar')
- Tests serve as living documentation

## Anti-Patterns to Avoid

- Tests passing immediately
- Testing implementation vs behavior
- Complex setup code
- Multiple responsibilities per test
- Brittle tests tied to specifics

## Edge Case Categories

- **Null/Empty**: undefined, null, empty string/array/object
- **Boundaries**: min/max values, single element, capacity limits
- **Special Cases**: Unicode, whitespace, special characters
- **State**: Invalid transitions, concurrent modifications
- **Errors**: Network failures, timeouts, permissions

## Output Requirements

- Complete test files with imports
- Documentation of test purpose
- Commands to run and verify failures
- Metrics: test count, coverage areas
- Next steps for green phase"

## Validation

After generation:
1. Run tests - confirm they fail
2. Verify helpful failure messages
3. Check test independence
4. Ensure comprehensive coverage

## Example (Minimal)

```typescript
// auth.service.test.ts
describe('AuthService', () => {
  let authService: AuthService;
  let mockUserRepo: jest.Mocked<UserRepository>;

  beforeEach(() => {
    mockUserRepo = { findByEmail: jest.fn() } as any;
    authService = new AuthService(mockUserRepo);
  });

  it('should_return_token_when_valid_credentials', async () => {
    const user = { id: '1', email: 'test@example.com', passwordHash: 'hashed' };
    mockUserRepo.findByEmail.mockResolvedValue(user);

    const result = await authService.authenticate('test@example.com', 'pass');

    expect(result.success).toBe(true);
    expect(result.token).toBeDefined();
  });

  it('should_fail_when_user_not_found', async () => {
    mockUserRepo.findByEmail.mockResolvedValue(null);

    const result = await authService.authenticate('none@example.com', 'pass');

    expect(result.success).toBe(false);
    expect(result.error).toBe('INVALID_CREDENTIALS');
  });
});
```

Test requirements: $ARGUMENTS

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tdd-workflows-tdd-refactor
description: "Use when working with tdd workflows tdd refactor"
risk: critical
source: community
date_added: "2026-02-27"
---

## Use this skill when

- Working on tdd workflows tdd refactor tasks or workflows
- Needing guidance, best practices, or checklists for tdd workflows tdd refactor

## Do not use this skill when

- The task is unrelated to tdd workflows tdd refactor
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

Refactor code with confidence using comprehensive test safety net:

[Extended thinking: This tool uses the tdd-orchestrator agent (opus model) for sophisticated refactoring while maintaining all tests green. It applies design patterns, improves code quality, and optimizes performance with the safety of comprehensive test coverage.]

## Usage

Use Task tool with subagent_type="tdd-orchestrator" to perform safe refactoring.

Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD refactor phase:

## Core Process

**1. Pre-Assessment**
- Run tests to establish green baseline
- Analyze code smells and test coverage
- Document current performance metrics
- Create incremental refactoring plan

**2. Code Smell Detection**
- Duplicated code → Extract methods/classes
- Long methods → Decompose into focused functions
- Large classes → Split responsibilities
- Long parameter lists → Parameter objects
- Feature Envy → Move methods to appropriate classes
- Primitive Obsession → Value objects
- Switch statements → Polymorphism
- Dead code → Remove

**3. Design Patterns**
- Apply Creational (Factory, Builder, Singleton)
- Apply Structural (Adapter, Facade, Decorator)
- Apply Behavioral (Strategy, Observer, Command)
- Apply Domain (Repository, Service, Value Objects)
- Use patterns only where they add clear value

**4. SOLID Principles**
- Single Responsibility: One reason to change
- Open/Closed: Open for extension, closed for modification
- Liskov Substitution: Subtypes substitutable
- Interface Segregation: Small, focused interfaces
- Dependency Inversion: Depend on abstractions

**5. Refactoring Techniques**
- Extract Method/Variable/Interface
- Inline unnecessary indirection
- Rename for clarity
- Move Method/Field to appropriate classes
- Replace Magic Numbers with constants
- Encapsulate fields
- Replace Conditional with Polymorphism
- Introduce Null Object

**6. Performance Optimization**
- Profile to identify bottlenecks
- Optimize algorithms and data structures
- Implement caching where beneficial
- Reduce database queries (N+1 elimination)
- Lazy loading and pagination
- Always measure before and after

**7. Incremental Steps**
- Make small, atomic changes
- Run tests after each modification
- Commit after each successful refactoring
- Keep refactoring separate from behavior changes
- Use scaffolding when needed

**8. Architecture Evolution**
- Layer separation and dependency management
- Module boundaries and interface definition
- Event-driven patterns for decoupling
- Database access pattern optimization

**9. Safety Verification**
- Run full test suite after each change
- Performance regression testing
- Mutation testing for test effectiveness
- Rollback plan for major changes

**10. Advanced Patterns**
- Strangler Fig: Gradual legacy replacement
- Branch by Abstraction: Large-scale changes
- Parallel Change: Expand-contract pattern
- Mikado Method: Dependency graph navigation

## Output Requirements

- Refactored code with improvements applied
- Test results (all green)
- Before/after metrics comparison
- Applied refactoring techniques list
- Performance improvement measurements
- Remaining technical debt assessment

## Safety Checklist

Before committing:
- ✓ All tests pass (100% green)
- ✓ No functionality regression
- ✓ Performance metrics acceptable
- ✓ Code coverage maintained/improved
- ✓ Documentation updated

## Recovery Protocol

If tests fail:
- Immediately revert last change
- Identify breaking refactoring
- Apply smaller incremental changes
- Use version control for safe experimentation

## Example: Extract Method Pattern

**Before:**
```typescript
class OrderProcessor {
  processOrder(order: Order): ProcessResult {
    // Validation
    if (!order.customerId || order.items.length === 0) {
      return { success: false, error: "Invalid order" };
    }

    // Calculate totals
    let subtotal = 0;
    for (const item of order.items) {
      subtotal += item.price * item.quantity;
    }
    let total = subtotal + (subtotal * 0.08) + (subtotal > 100 ? 0 : 15);

    // Process payment...
    // Update inventory...
    // Send confirmation...
  }
}
```

**After:**
```typescript
class OrderProcessor {
  async processOrder(order: Order): Promise<ProcessResult> {
    const validation = this.validateOrder(order);
    if (!validation.isValid) return ProcessResult.failure(validation.error);

    const orderTotal = OrderTotal.calculate(order);
    const inventoryCheck = await this.inventoryService.checkAvailability(order.items);
    if (!inventoryCheck.available) return ProcessResult.failure(inventoryCheck.reason);

    await this.paymentService.processPayment(order.paymentMethod, orderTotal.total);
    await this.inventoryService.reserveItems(order.items);
    await this.notificationService.sendOrderConfirmation(order, orderTotal);

    return ProcessResult.success(order.id, orderTotal.total);
  }

  private validateOrder(order: Order): ValidationResult {
    if (!order.customerId) return ValidationResult.invalid("Customer ID required");
    if (order.items.length === 0) return ValidationResult.invalid("Order must contain items");
    return ValidationResult.valid();
  }
}
```

**Applied:** Extract Method, Value Objects, Dependency Injection, Async patterns

Code to refactor: $ARGUMENTS"

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: teach
description: Teach the user a new skill or concept, within this workspace.
disable-model-invocation: true
argument-hint: "What would you like to learn about?"
category: "education"
risk: "safe"
source: "community"
source_repo: "mattpocock/skills"
source_type: "community"
date_added: "2026-06-19"
author: "Matt Pocock"
license: "MIT"
license_source: "https://github.com/mattpocock/skills/blob/main/LICENSE"
tags:
  - education
  - workflow
  - coding-agents
tools:
  - claude-code
  - codex-cli
  - cursor
---

## When to Use

Use when this workflow matches the user request: Teach the user a new skill or concept, within this workspace.

_Source: [mattpocock/skills](https://github.com/mattpocock/skills) (MIT)._The user has asked you to teach them something. This is a stateful request - they intend to learn the topic over multiple sessions.

## Teaching Workspace

Treat the current directory as a teaching workspace. The state of their learning is captured in this directory in several files:

- `MISSION.md`: A document capturing the _reason_ the user is interested in the topic. This should be used to ground all teaching. Use the format in [MISSION-FORMAT.md](./MISSION-FORMAT.md).
- `./reference/*.html`: A directory of reference materials. These are the compressed learnings from the lessons - cheat sheets, reference algorithms, syntax, yoga poses, glossaries. They are the raw units of learning. They should be beautiful documents which print out well, and are designed for quick reference.
- `RESOURCES.md`: A list of resources which can be explored to ground your teaching in contextual knowledge, or to acquire knowledge and wisdom. Use the format in [RESOURCES-FORMAT.md](./RESOURCES-FORMAT.md).
- `./learning-records/*.md`: A directory of learning records, which capture what the user has learned. These are loosely equivalent to architectural decision records in software development - they capture non-obvious lessons and key insights that may need to be revised later, or drive future sessions. These should be used to calculate the zone of proximal development. They are titled `0001-<dash-case-name>.md`, where the number increments each time. Use the format in [LEARNING-RECORD-FORMAT.md](./LEARNING-RECORD-FORMAT.md).
- `./lessons/*.html`: A directory of lessons. A **lesson** is a single, self-contained HTML output that teaches one tightly-scoped thing tied to the mission. This is the primary unit of teaching in this workspace.
- `./assets/*`: Reusable **components** shared across lessons. See [Assets](#assets).
- `NOTES.md`: A scratchpad for you to jot down user preferences, or working notes.

## Philosophy

To learn at a deep level, the user needs three things:

- **Knowledge**, captured from high-quality, high-trust resources
- **Skills**, acquired through highly-relevant interactive lessons devised by you, based on the knowledge
- **Wisdom**, which comes from interacting with other learners and practitioners

Before the `RESOURCES.md` is well-populated, your focus should be to find high-quality resources which will help the user acquire knowledge. Never trust your parametric knowledge.

Some topics may require more skills than knowledge. Learning more about theoretical physics might be more knowledge-based. For yoga, more skills-based.

### Fluency vs Storage Strength

You should be careful to split between two types of learning:

- **Fluency strength**: in-the-moment retrieval of knowledge
- **Storage strength**: long-term retention of knowledge

Fluency can give the user an illusory sense of mastery, but storage strength is the real goal. Try to design lessons which build long-term retention by desirable difficulty:

- Using retrieval practice (recall from memory)
- Spacing (distributing practice over time)
- Interleaving (mixing up different but related topics in practice - for skills practice only)

## Lessons

A lesson is the main thing you produce — the unit in which knowledge and skills reach the user. Each lesson is one self-contained HTML file, saved to `./lessons/` and titled `0001-<dash-case-name>.html` where the number increments each time.

A lesson should be **beautiful** — clean, readable typography and layout — since the user will return to these later to review. Think Tufte.

The lesson should be short, and completable very quickly. Learners' working memory is very small, and we need to stay within it. But each lesson should give the user a single tangible win that they can build on. It should be directly tied to the mission, and should be in the user's zone of proximal development.

If possible, open the lesson file for the user by running a CLI command.

Each lesson should link via HTML anchors to other lessons and reference documents.

Each lesson should recommend a primary source for the user to read or watch. This should be the most high-quality, high-trust resource you found on the topic.

Each lesson should contain a reminder to ask followup questions to the agent. The agent is their teacher, and can assist with anything that's unclear.

## Assets

Lessons are built from reusable **components**, stored in `./assets/`: stylesheets, quiz widgets, simulators, diagram helpers — anything a second lesson could reuse.

Reuse is the default, not the exception. Before authoring a lesson, read `./assets/` and build from the components already there. When a lesson needs something new and reusable, write it as a component in `./assets/` and link to it — never inline code a future lesson would duplicate.

A shared stylesheet is the first component every workspace earns: every lesson links it, so the lessons look like one consistent course rather than a pile of one-offs. As the workspace grows, so should the component library.

## The Mission

Every lesson should be tied into the mission - the reason that the user is interested in learning about the topic.

If the user is unclear about the mission, or the `MISSION.md` is not populated, your first job should be to question the user on why they want to learn this.

Failing to understand the mission will mean knowledge acquisition is not grounded in real-world goals. Lessons will feel too abstract. You will have no way of judging what the user should do next.

Missions may change as the user develops more skills and knowledge. This is normal - make sure to update the `MISSION.md` and add a learning record to capture the change. Confirm with the user before changing the mission.

## Zone Of Proximal Development

Each lesson, the user should always feel as if they are being challenged 'just enough'.

The user may specify an exact thing they want to learn. If they don't, figure out their zone of proximal development by:

- Reading their `learning-records`
- Figuring out the right thing to teach them based on their mission
- Teach the most relevant thing that fits in their zone of proximal development

## Knowledge

Lessons should be designed around a skill the user is going to learn. The knowledge in the lesson should be only what's required to acquire that skill. You teach the knowledge first, then get the user to practice the skills via an interactive feedback loop.

Knowledge should first be gathered from trusted resources. Use `RESOURCES.md` to keep track of them. Lessons should be littered with citations - links to external resources to back up any claim made. This increases the trustworthiness of the lesson.

For acquiring knowledge, difficulty is the enemy. It eats working memory you need for understanding.

## Skills

If knowledge is all about acquisition, skills are about durability and flexibility. Make the knowledge stick.

For skill acquisition, difficulty is the tool. Effortful retrieval is what builds storage strength. Skills should be taught through interactive lessons. There are several tools at your disposal:

- Interactive lessons, using quizzes and light in-browser tasks
- Lessons which guide the user through a list of real-world steps to take (for instance, yoga poses)

Each of these should be based on a **feedback loop**, where the user receives feedback on their performance. This feedback loop should be as tight as possible, giving feedback immediately - and ideally automatically.

For quizzes, each answer should be exactly the same number of words (and characters, if possible). Don't give the user any clues about the answer through formatting.

## Acquiring Wisdom

Wisdom comes from true real-world interaction - testing your skills outside the learning environment.

When the user asks a question that appears to require wisdom, your default posture should be to attempt to answer - but to ultimately delegate to a **community**.

A community is a place (online or offline) where the user can test their skills in the real world. This might be a forum, a subreddit, a real-world class (budget permitting) or a local interest group.

You should attempt to find high-reputation communities the user can join. If the user expresses a preference that they don't want to join a community, respect it.

## Reference Documents

While creating lessons, you should also create reference documents. Lessons can reference these documents - they are useful for tracking raw units of knowledge useful across lessons.

Lessons will rarely be revisited later - reference documents will be. They should be the compressed essence of the lesson, in a format designed for quick reference.

Some learning topics lend themselves to reference:

- Syntax and code snippets for programming
- Algorithms and flowcharts for processes
- Yoga poses and sequences for yoga
- Exercises and routines for fitness
- Glossaries for any topic with its own nomenclature

Glossaries, in particular, are an essential reference. Once one is created, it should be adhered to in every lesson.

## `NOTES.md`

The user will sometimes express preferences of how they want to be taught, or things you should keep in mind. This is the place to record those preferences, so you can refer back to them when designing lessons or working with the user.

## Limitations

- Requires the upstream tool, account, API key, or local setup when the workflow names one.
- Does not authorize destructive, production, paid, or external-message actions without explicit user approval.
- Validate generated artifacts or recommendations against the user's real sources before treating them as final.


---
name: team-collaboration-issue
description: "You are a GitHub issue resolution expert specializing in systematic bug investigation, feature implementation, and collaborative development workflows. Your expertise spans issue triage, root cause an"
risk: safe
source: community
date_added: "2026-02-27"
---

# GitHub Issue Resolution Expert

You are a GitHub issue resolution expert specializing in systematic bug investigation, feature implementation, and collaborative development workflows. Your expertise spans issue triage, root cause analysis, test-driven development, and pull request management. You excel at transforming vague bug reports into actionable fixes and feature requests into production-ready code.

## Use this skill when

- Working on github issue resolution expert tasks or workflows
- Needing guidance, best practices, or checklists for github issue resolution expert

## Do not use this skill when

- The task is unrelated to github issue resolution expert
- You need a different domain or tool outside this scope

## Context

The user needs comprehensive GitHub issue resolution that goes beyond simple fixes. Focus on thorough investigation, proper branch management, systematic implementation with testing, and professional pull request creation that follows modern CI/CD practices.

## Requirements

GitHub Issue ID or URL: $ARGUMENTS

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: team-collaboration-standup-notes
description: "You are an expert team communication specialist focused on async-first standup practices, AI-assisted note generation from commit history, and effective remote team coordination patterns."
risk: critical
source: community
date_added: "2026-02-27"
---

# Standup Notes Generator

You are an expert team communication specialist focused on async-first standup practices, AI-assisted note generation from commit history, and effective remote team coordination patterns.

## Use this skill when

- Working on standup notes generator tasks or workflows
- Needing guidance, best practices, or checklists for standup notes generator

## Do not use this skill when

- The task is unrelated to standup notes generator
- You need a different domain or tool outside this scope

## Context

Modern remote-first teams rely on async standup notes to maintain visibility, coordinate work, and identify blockers without synchronous meetings. This tool generates comprehensive daily standup notes by analyzing multiple data sources: Obsidian vault context, Jira tickets, Git commit history, and calendar events. It supports both traditional synchronous standups and async-first team communication patterns, automatically extracting accomplishments from commits and formatting them for maximum team visibility.

## Requirements

**Arguments:** `$ARGUMENTS` (optional)
- If provided: Use as context about specific work areas, projects, or tickets to highlight
- If empty: Automatically discover work from all available sources

**Required MCP Integrations:**
- `mcp-obsidian`: Vault access for daily notes and project updates
- `atlassian`: Jira ticket queries (graceful fallback if unavailable)
- Optional: Calendar integrations for meeting context

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: team-composition-analysis
description: "Design optimal team structures, hiring plans, compensation strategies, and equity allocation for early-stage startups from pre-seed through Series A."
risk: none
source: community
date_added: '2026-02-27'
---

# Team Composition Analysis

Design optimal team structures, hiring plans, compensation strategies, and equity allocation for early-stage startups from pre-seed through Series A.

## Use this skill when

- Working on team composition analysis tasks or workflows
- Needing guidance, best practices, or checklists for team composition analysis

## Do not use this skill when

- The task is unrelated to team composition analysis
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Overview

Build the right team at the right time with appropriate compensation and equity. Plan role-by-role hiring aligned with revenue milestones, budget constraints, and market benchmarks.

## Team Structure by Stage

### Pre-Seed (0-$500K ARR)

**Team Size: 2-5 people**

**Core Roles:**
- Founders (2-3): Product, engineering, business
- First engineer (if needed)
- Contract roles: Design, marketing

**Focus:** Build and validate product-market fit

### Seed ($500K-$2M ARR)

**Team Size: 5-15 people**

**Key Hires:**
- Engineering lead + 2-3 engineers
- First sales/business development
- Product manager
- Marketing/growth lead

**Focus:** Scale product and prove repeatable sales

### Series A ($2M-$10M ARR)

**Team Size: 15-50 people**

**Department Build-Out:**
- Engineering (40%): 6-20 people
- Sales & Marketing (30%): 5-15 people
- Customer Success (10%): 2-5 people
- G&A (10%): 2-5 people
- Product (10%): 2-5 people

**Focus:** Scale revenue and build repeatable processes

## Role-by-Role Planning

### Engineering Team

**Pre-Seed:**
- Founders write code
- 0-1 contract developers

**Seed:**
- Engineering Lead (first $150K-$180K)
- 2-3 Full-Stack Engineers ($120K-$150K)
- 1 Frontend or Backend Specialist ($130K-$160K)

**Series A:**
- VP Engineering ($180K-$250K + equity)
- 2-3 Senior Engineers ($150K-$180K)
- 3-5 Mid-Level Engineers ($120K-$150K)
- 1-2 Junior Engineers ($90K-$120K)
- 1 DevOps/Infrastructure ($140K-$170K)

### Sales & Marketing

**Pre-Seed:**
- Founders do sales
- Contract marketing help

**Seed:**
- First Sales Hire / Head of Sales ($120K-$150K + commission)
- Marketing/Growth Lead ($100K-$140K)
- SDR or BDR (if B2B) ($50K-$70K + commission)

**Series A:**
- VP Sales ($150K-$200K + commission + equity)
- 3-5 Account Executives ($80K-$120K + commission)
- 2-3 SDRs/BDRs ($50K-$70K + commission)
- Marketing Manager ($90K-$130K)
- Content/Demand Gen ($70K-$100K)

### Product Team

**Pre-Seed:**
- Founder as product lead

**Seed:**
- First Product Manager ($120K-$150K)
- Contract designer

**Series A:**
- Head of Product ($150K-$180K)
- 1-2 Product Managers ($120K-$150K)
- Product Designer ($100K-$140K)
- UX Researcher (optional) ($90K-$130K)

### Customer Success

**Pre-Seed:**
- Founders handle support

**Seed:**
- First CS hire (optional) ($60K-$90K)

**Series A:**
- CS Manager ($100K-$130K)
- 2-4 CS Representatives ($60K-$90K)
- Support Engineer (technical) ($80K-$120K)

### G&A (General & Administrative)

**Pre-Seed:**
- Contractors (accounting, legal)

**Seed:**
- Operations/Office Manager ($70K-$100K)
- Contract CFO

**Series A:**
- CFO or Finance Lead ($150K-$200K)
- Recruiter ($80K-$120K)
- Office Manager / EA ($60K-$90K)

## Compensation Strategy

### Base Salary Benchmarks (US, 2024)

**Engineering:**
- Junior: $90K-$120K
- Mid-Level: $120K-$150K
- Senior: $150K-$180K
- Staff/Principal: $180K-$220K
- Engineering Manager: $160K-$200K
- VP Engineering: $180K-$250K

**Sales:**
- SDR/BDR: $50K-$70K base + $50K-$70K commission
- Account Executive: $80K-$120K base + $80K-$120K commission
- Sales Manager: $120K-$160K base + $80K-$120K commission
- VP Sales: $150K-$200K base + $150K-$200K commission

**Product:**
- Product Manager: $120K-$150K
- Senior PM: $150K-$180K
- Head of Product: $150K-$180K
- VP Product: $180K-$220K

**Marketing:**
- Marketing Manager: $90K-$130K
- Content/Demand Gen: $70K-$100K
- Head of Marketing: $130K-$170K
- VP Marketing: $150K-$200K

**Customer Success:**
- CS Representative: $60K-$90K
- CS Manager: $100K-$130K
- VP Customer Success: $140K-$180K

### Total Compensation Formula

```
Total Comp = Base Salary × 1.30 (benefits & taxes) + Equity Value
```

**Fully-Loaded Cost:**
- Base salary
- Payroll taxes (7.65% FICA)
- Benefits (health insurance, 401k): $10K-$15K per employee
- Other (workspace, equipment, software): $5K-$10K per employee

**Rule of Thumb:** Multiply base salary by 1.3-1.4 for fully-loaded cost

### Geographic Adjustments

**San Francisco / New York:** +20-30% above benchmarks
**Seattle / Boston / Los Angeles:** +10-20%
**Austin / Denver / Chicago:** +0-10%
**Remote / Other US Cities:** -10-20%
**International:** Varies widely by country

## Equity Allocation

### Equity by Role and Stage

**Founders:**
- First founder: 40-60%
- Second founder: 20-40%
- Third founder: 10-20%
- Vesting: 4 years with 1-year cliff

**Early Employees (Pre-Seed):**
- First engineer: 0.5-2.0%
- First 5 employees: 0.25-1.0% each

**Seed Stage Hires:**
- VP/Head level: 0.5-1.5%
- Senior IC: 0.1-0.5%
- Mid-level: 0.05-0.25%
- Junior: 0.01-0.1%

**Series A Hires:**
- C-level (CTO, CFO): 1.0-3.0%
- VP level: 0.3-1.0%
- Director level: 0.1-0.5%
- Senior IC: 0.05-0.2%
- Mid-level: 0.01-0.1%
- Junior: 0.005-0.05%

### Equity Pool Sizing

**Option Pool by Round:**
- Pre-Seed: 10-15% reserved
- Seed: 10-15% top-up
- Series A: 10-15% top-up
- Series B+: 5-10% per round

**Pre-Funding Dilution:**
Investors often require option pool creation before investment, diluting founders.

**Example:**
```
Pre-money: $10M
Investors want 15% option pool post-money

Calculation:
Post-money: $15M ($10M + $5M investment)
Option pool: $2.25M (15% × $15M)
Founders diluted by pool creation before new money
```

## Organizational Design

### Reporting Structure

**Pre-Seed:**
```
Founders (flat structure)
├── Contractors
└── First hires (report to founders)
```

**Seed:**
```
CEO
├── Engineering Lead (2-4 engineers)
├── Sales/Growth Lead (1-2 reps)
├── Product Manager
└── Operations
```

**Series A:**
```
CEO
├── CTO / VP Engineering (6-20 people)
│   ├── Engineering Manager(s)
│   └── Individual Contributors
├── VP Sales (5-15 people)
│   ├── Sales Manager
│   ├── Account Executives
│   └── SDRs
├── Head of Product (2-5 people)
│   ├── Product Managers
│   └── Designers
├── Head of Customer Success (2-5 people)
└── CFO / Finance Lead (2-5 people)
    ├── Recruiter
    └── Operations
```

### Span of Control

**Manager Ratios:**
- First-line managers: 4-8 direct reports
- Directors: 3-5 direct reports (managers)
- VPs: 3-5 direct reports (directors)
- CEO: 5-8 direct reports (executive team)

## Full-Time vs. Contract

### Use Full-Time for:
- Core product development
- Sales (revenue-generating roles)
- Mission-critical operations
- Institutional knowledge roles

### Use Contractors for:
- Specialized short-term needs (legal, accounting)
- Variable workload (design, marketing campaigns)
- Skills outside core competency
- Testing role before FTE hire
- Geographic expansion before permanent presence

### Cost Comparison

**Full-Time:**
- Lower hourly cost
- Benefits and overhead
- Long-term commitment
- Cultural fit matters

**Contract:**
- Higher hourly rate ($75-$200/hour vs. $40-$100/hour FTE equivalent)
- No benefits or overhead
- Flexible engagement
- Easier to scale up/down

## Hiring Velocity

### Realistic Timeline

**Role Opening to Hire:**
- Junior: 6-8 weeks
- Mid-Level: 8-12 weeks
- Senior: 12-16 weeks
- Executive: 16-24 weeks

**Time to Productivity:**
- Junior: 4-6 months
- Mid-Level: 2-4 months
- Senior: 1-3 months
- Executive: 3-6 months

### Planning Buffer

Always add 2-3 months buffer to hiring plans.

**Example:**
If need engineer by July 1:
- Start recruiting: April 1 (12 weeks)
- Productivity: September 1 (2 months ramp)

## Budget Planning

### Compensation as % of Revenue

**Early Stage (Seed):**
- Total comp: 120-150% of revenue (burning cash to grow)
- Engineering: 50-60%
- Sales: 30-40%
- Other: 20-30%

**Growth Stage (Series A):**
- Total comp: 70-100% of revenue
- Engineering: 35-45%
- Sales: 25-35%
- Other: 20-30%

### Headcount Budget Formula

```
Total Comp Budget = Σ (Role Count × Fully-Loaded Cost × % of Year)

Example:
3 Engineers × $202K × 100% = $606K
2 AEs × $230K × 75% (mid-year start) = $345K
1 PM × $162K × 100% = $162K
Total: $1.1M
```

## Additional Resources

### Reference Files
- **`references/compensation-benchmarks.md`** - Detailed salary data by role, level, and location
- **`references/equity-calculator.md`** - Equity sizing formulas and dilution scenarios

### Example Files
- **`examples/seed-stage-hiring-plan.md`** - Complete hiring plan for seed-stage SaaS company
- **`examples/org-chart-evolution.md`** - Organizational design from 5 to 50 people

## Quick Start

To plan team composition:

1. **Identify stage** - Pre-seed, seed, or Series A
2. **Define roles** - What functions are needed now
3. **Prioritize hires** - Critical path for business goals
4. **Set compensation** - Base salary + equity by level
5. **Plan timeline** - Account for recruiting and ramp time
6. **Calculate budget** - Fully-loaded cost × headcount
7. **Design org chart** - Reporting structure and span of control
8. **Allocate equity** - Fair allocation that preserves pool

For detailed compensation benchmarks and hiring plan templates, see `references/` and `examples/`.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tech-matrix
description: Reference document for monopoly tech-matrix.
source: community
risk: safe
reports-to: monopoly
---

# MONOPOLY — Technology Decision Matrix

## When to Use
- Use this skill when the task matches this description: Reference document for monopoly tech-matrix.

## Table of Contents
1. Database Selection
2. Cache Selection
3. Message Queue / Event Streaming
4. API Protocol
5. Search Engine
6. Object Storage
7. Container Orchestration
8. Load Balancer
9. Observability Stack
10. CDN

---

## 1. Database Selection

### Relational (SQL)

| Database | Best For | Avoid When | Scale Ceiling |
|----------|----------|------------|---------------|
| **PostgreSQL** | Complex queries, JSONB, GIS, strong consistency, most default use cases | Ultra-high write throughput (>100K writes/s) | ~10TB single node; use Citus for horizontal |
| **MySQL / MariaDB** | Read-heavy apps, legacy systems, WordPress/Drupal ecosystem | Complex queries, full ACID at scale | ~10TB; use Vitess for sharding |
| **CockroachDB** | Global distributed SQL, geo-partitioning, multi-region | Simple single-region apps (overkill) | Petabyte-scale |
| **PlanetScale** | MySQL-compatible, serverless, branch-based workflow | Complex JOINs (foreign keys removed by design) | Very high — Vitess based |
| **Amazon Aurora** | AWS-native apps, managed PostgreSQL/MySQL, high availability | Non-AWS environments | Up to 128TB, 15 replicas |

### NoSQL

| Database | Best For | Avoid When | Scale Ceiling |
|----------|----------|------------|---------------|
| **MongoDB** | Flexible schema, document model, prototyping | Financial transactions requiring ACID | Petabyte-scale with sharding |
| **DynamoDB** | Key-value at massive scale, AWS-native, serverless, predictable latency | Complex queries, ad-hoc analytics, JOINs | Unlimited (AWS-managed) |
| **Cassandra** | Write-heavy, time-series, wide-column, geographically distributed | Read-heavy with complex queries | Petabyte-scale; used at Apple, Netflix |
| **Redis** | Cache, sessions, leaderboards, pub/sub, rate limiting | Primary data store for complex models | ~1TB per node; cluster for more |
| **Elasticsearch** | Full-text search, log aggregation, analytics | Primary database (durability risk) | Petabyte-scale with clusters |
| **InfluxDB** | Time-series metrics, IoT, monitoring data | General-purpose data | Very high write throughput |
| **Neo4j** | Graph data, social networks, recommendation engines, fraud detection | Non-graph data (overhead not worth it) | Billions of nodes |

### Decision Framework

```
Is your data relational (joins, foreign keys, transactions)?
  YES → Start with PostgreSQL
  NO  → Continue below

Is your primary access pattern key-value?
  YES, need extreme scale → DynamoDB or Cassandra
  YES, need speed/cache → Redis

Is your data document-shaped (nested, flexible schema)?
  YES → MongoDB

Is it time-series (metrics, logs, IoT)?
  YES → InfluxDB or TimescaleDB

Is it graph (relationships are the data)?
  YES → Neo4j

Is it search?
  YES → Elasticsearch / OpenSearch
```

---

## 2. Cache Selection

| Technology | Best For | Max Single Node | Cluster Support |
|------------|----------|----------------|----------------|
| **Redis** | Sessions, leaderboards, pub/sub, complex data structures, Lua scripting | ~1TB RAM | Yes (Redis Cluster, Redis Sentinel) |
| **Memcached** | Simple key-value, multi-threaded, large object cache | ~64GB RAM | Yes (client-side sharding) |
| **Varnish** | HTTP reverse proxy cache, full-page caching | RAM bound | Limited |
| **CloudFront / CDN** | Static assets, edge caching globally | N/A (distributed) | Built-in global distribution |

**Default recommendation: Redis** — more features, better ecosystem, active development.

Use **Memcached** only when: you need multi-threading for CPU-bound caching workloads and don't need data structures beyond string.

---

## 3. Message Queue / Event Streaming

| Technology | Model | Best For | Throughput | Retention |
|------------|-------|----------|------------|-----------|
| **Apache Kafka** | Log-based streaming | Event sourcing, high-throughput pipelines, replay, audit | Millions msg/s | Days to forever |
| **RabbitMQ** | AMQP message broker | Task queues, RPC, routing, fanout | 50K–100K msg/s | Until consumed |
| **AWS SQS** | Managed queue | AWS-native, simple task queue, serverless | Very high (managed) | Up to 14 days |
| **AWS SNS** | Pub/sub notification | Fan-out to many subscribers (email, SMS, Lambda, SQS) | Very high (managed) | No retention |
| **Google Pub/Sub** | Managed streaming | GCP-native, global, serverless | Very high (managed) | Up to 7 days |
| **Redis Pub/Sub** | In-memory pub/sub | Real-time notifications, low latency, fire-and-forget | Very high | None (no retention) |
| **NATS** | Lightweight messaging | IoT, microservices, low latency | Very high | JetStream adds retention |

### Decision Matrix

```
Need event replay / audit trail?
  YES → Kafka or Kinesis

Need simple task queue with retries and DLQ?
  AWS shop → SQS
  Self-hosted → RabbitMQ

Need real-time pub/sub with no persistence?
  Redis Pub/Sub or NATS

Need fan-out to multiple consumers?
  Kafka (consumer groups) or SNS → SQS fan-out

Need < 5 minutes guaranteed delivery, AWS-native, zero ops?
  SQS

Volume > 1 million messages/second?
  Kafka (self-hosted) or Kinesis (managed)
```

---

## 4. API Protocol

| Protocol | Best For | Avoid When |
|----------|----------|------------|
| **REST (HTTP/JSON)** | Public APIs, CRUD, browser clients, simplicity | Strict typing required; high-performance internal services |
| **GraphQL** | Complex client data requirements, mobile (reduce over-fetching), BFF pattern | Simple CRUD; not worth the complexity |
| **gRPC (HTTP/2 + Protobuf)** | Internal microservice communication, low latency, strict contracts, streaming | Public browser APIs (needs gRPC-web) |
| **WebSocket** | Real-time bidirectional (chat, live dashboards, multiplayer games) | One-way server push (use SSE instead) |
| **SSE (Server-Sent Events)** | Server → client push (notifications, live feeds) | Bidirectional communication |
| **GraphQL Subscriptions** | Real-time with GraphQL schema consistency | Simple push scenarios |

**Default recommendation:**
- External / public: **REST**
- Internal service-to-service: **gRPC**
- Real-time features: **WebSocket** or **SSE**

---

## 5. Search Engine

| Technology | Best For | Avoid When |
|------------|----------|------------|
| **Elasticsearch** | Full-text search, log analytics (ELK), complex aggregations | Simple lookups; operational overhead is high |
| **OpenSearch** | AWS-native Elasticsearch alternative | Non-AWS preferred setups |
| **Typesense** | Simple, fast full-text search, typo tolerance, easy ops | Complex aggregations at massive scale |
| **Algolia** | Managed search-as-a-service, fast setup, great UI | High volume (expensive); self-hosted preference |
| **Meilisearch** | Self-hosted, developer-friendly, fast relevancy | Enterprise-scale analytics |
| **PostgreSQL FTS** | Basic full-text search, already using PostgreSQL | High relevancy requirements or large datasets |

**Rule of thumb:** Use PostgreSQL FTS under 1M documents. Move to Typesense or Elasticsearch above that.

---

## 6. Object Storage

| Service | Best For | Egress Cost |
|---------|----------|------------|
| **AWS S3** | AWS-native apps, de facto standard, massive ecosystem | $0.09/GB (expensive) |
| **Cloudflare R2** | S3-compatible, **zero egress cost**, global | $0.00 egress |
| **GCS** | GCP-native | $0.12/GB |
| **Azure Blob** | Azure-native | $0.087/GB |
| **Backblaze B2** | Cost-sensitive, S3-compatible | Free with Cloudflare |
| **MinIO** | Self-hosted S3-compatible | Self-managed |

**Cost optimization tip:** Use **Cloudflare R2** for user-facing media delivery (zero egress). Use **S3** for internal/AWS-integrated storage.

---

## 7. Container Orchestration

| Technology | Best For | Avoid When |
|------------|----------|------------|
| **Kubernetes (K8s)** | Large teams, complex deployments, multi-cloud, full control | Small teams (ops overhead is very high) |
| **AWS ECS + Fargate** | AWS-native, serverless containers, simpler than K8s | Multi-cloud or K8s ecosystem tools needed |
| **AWS EKS** | Managed K8s on AWS, best of both | Small teams; Fargate may be enough |
| **GKE (Google)** | Best managed K8s, GCP-native, Autopilot mode | Non-GCP environments |
| **Docker Compose** | Local dev, small single-server deployments | Production at any meaningful scale |
| **Nomad** | HashiCorp ecosystem, simpler than K8s, multi-workload | K8s ecosystem tools required |

**Startup default:** ECS + Fargate (zero cluster management).
**Scale default:** EKS or GKE once team > 5 engineers or services > 10.

---

## 8. Load Balancer

| Technology | Layer | Best For |
|------------|-------|----------|
| **AWS ALB** | L7 (HTTP/HTTPS) | AWS apps, path-based routing, WebSocket, HTTP/2 |
| **AWS NLB** | L4 (TCP/UDP) | Ultra-low latency, static IP, non-HTTP protocols |
| **GCP GLB** | L7 global | GCP apps, global anycast, single IP worldwide |
| **Nginx** | L4/L7 | Self-hosted, reverse proxy, flexible config |
| **HAProxy** | L4/L7 | High performance self-hosted, advanced routing |
| **Cloudflare** | L7 global + DDoS | DDoS protection + CDN + load balancing combined |
| **Traefik** | L7 | Kubernetes-native, automatic SSL, service discovery |

---

## 9. Observability Stack

### Metrics
| Tool | Best For |
|------|----------|
| **Prometheus + Grafana** | Self-hosted, open-source, Kubernetes-native |
| **Datadog** | Managed, APM + infra + logs unified, expensive |
| **CloudWatch** | AWS-native, zero setup, integrated with AWS services |
| **New Relic** | APM-focused, good for application-level insights |

### Logging
| Tool | Best For |
|------|----------|
| **ELK Stack** (Elasticsearch + Logstash + Kibana) | Self-hosted, powerful, high volume |
| **Loki + Grafana** | Lightweight, Kubernetes-native, cheap |
| **Splunk** | Enterprise, compliance, expensive |
| **AWS CloudWatch Logs** | AWS-native, zero setup |
| **Datadog Logs** | Unified with metrics, expensive |

### Distributed Tracing
| Tool | Best For |
|------|----------|
| **Jaeger** | Open-source, Kubernetes-native, OpenTelemetry |
| **Zipkin** | Simple, lightweight, good integrations |
| **AWS X-Ray** | AWS-native, integrates with Lambda, ECS |
| **Datadog APM** | Managed, unified with metrics and logs |
| **Honeycomb** | High-cardinality event-based observability |

**Recommended open-source stack:** Prometheus + Grafana + Loki + Jaeger (all integrate via OpenTelemetry)
**Recommended managed stack:** Datadog (expensive but unified) or Grafana Cloud

---

## 10. CDN

| Technology | Best For | Edge Locations |
|------------|----------|----------------|
| **Cloudflare** | DDoS protection + CDN + DNS, best free tier, edge workers | 300+ |
| **AWS CloudFront** | AWS-native, deep S3 and API GW integration | 450+ |
| **Akamai** | Enterprise, highest performance, expensive | 4000+ |
| **Fastly** | Real-time purging, streaming, VCL customization | 90+ |
| **Vercel Edge / Netlify** | Jamstack, frontend-first, zero config | 100+ |

**Default recommendation:** Cloudflare for most use cases (best value, DDoS included, free SSL, Workers for edge compute).

---

## Scale Benchmarks Quick Reference

| Technology | Write Throughput | Read Throughput | Notes |
|------------|-----------------|----------------|-------|
| PostgreSQL (single) | ~10K writes/s | ~50K reads/s | With connection pooling |
| PostgreSQL (replicas) | ~10K writes/s | ~200K reads/s | 4 replicas |
| MySQL (single) | ~15K writes/s | ~60K reads/s | |
| Cassandra | ~1M writes/s | ~500K reads/s | 10-node cluster |
| Redis | ~1M ops/s | ~1M ops/s | Single node in-memory |
| Kafka | ~1M msgs/s | ~1M msgs/s | Per partition |
| Elasticsearch | ~50K docs/s | ~10K queries/s | Per node |
| MongoDB | ~50K writes/s | ~100K reads/s | Per replica set |

*All benchmarks are approximate and depend heavily on hardware, payload size, and query complexity.*

## Limitations
- This is a reference document and may not cover all edge cases. Always verify architectures before production.


---
name: technical-change-tracker
description: "Track code changes with structured JSON records, state machine enforcement, and AI session handoff for bot continuity"
category: development
risk: safe
source: community
source_repo: Elkidogz/technical-change-skill
source_type: community
date_added: "2026-04-05"
author: Elkidogz
tags: [change-tracking, session-handoff, documentation, accessibility, state-machine]
tools: [claude, cursor, gemini, codex]
---

# Technical Change Tracker

## Overview

Track every code change with structured JSON records and accessible HTML output. Ensures AI bot sessions can resume seamlessly when previous sessions expire or are abandoned.

## When to Use This Skill

- Use when you need structured change tracking across AI coding sessions
- Use when a bot session expires mid-task and the next session needs full context to resume
- Use when onboarding a project with undocumented change history

## How It Works

### State Machine

```
planned -> in_progress -> implemented -> tested -> deployed
             |
             +-> blocked
```

### Commands

`/tc init` | `/tc create` | `/tc update` | `/tc status` | `/tc resume` | `/tc close` | `/tc export` | `/tc dashboard` | `/tc retro`

### Session Handoff

Each TC stores: progress summary, next steps, blockers, key context, and files in progress — so the next bot session picks up exactly where the last left off.

### Non-Blocking

TC bookkeeping runs via background subagents. Never interrupts coding work.

## Features

- Structured JSON records with append-only revision history
- Test cases with log snippet evidence
- WCAG AA+ accessible HTML output (dark theme, rem-based fonts)
- CSS-only dashboard with status filters
- Python stdlib only — zero external dependencies
- Retroactive bulk creation from git history via `/tc retro`

## Full Repository

https://github.com/Elkidogz/technical-change-skill — MIT License

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.