技能
- 作者仓库星标 3,406
- 作者仓库 claude-octopus
- 领域
- 人工智能
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @nyldn · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- macOS · Linux · Windows
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 命令执行
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
test('rejects empty email', async () => {
const result = await submitForm({ email: '' });
expect(result.error).toBe('Email required');
});
第 1 阶段:红色 - 写入失败测试
编写一个最小的测试来显示应该发生什么。好的测试:清晰的名称描述行为测试真实的代码,而不是模拟只有一件事
阶段 1.5:对抗性测试设计审查(推荐)
编写初始测试后但在验证它们失败之前,请与第二个提供商一起挑战测试设计。单模型测试套件通常存在系统性盲点——编写测试的同一模型将编写可以轻松满足这些盲点的实现。对抗性审查捕获那些可以通过但实际上不起作用的存根的场景。如果有可用的外部提供商,请发送测试规范以供质疑:
第 2 阶段:验证红色 - 观察它失败
强制性的。切勿跳过。确认:测试失败(不是错误) 失败消息符合您的预期 失败是因为缺少功能(不是拼写错误)
第 3 阶段:绿色 - 最少代码
编写最简单的代码来通过测试。而已。好: 坏(YAGNI 违规):
第 4 阶段:验证绿色 - 等待它通过
强制性的。确认:测试通过 所有其他测试仍然通过 输出干净(没有错误、警告)
第 5 阶段:重构 - 清理
仅在绿色之后: 删除重复 改进名称 提取助手 始终保持测试绿色。不要添加新行为。
> **Host: Codex CLI** — This skill was designed for Claude Code and adapted for Codex.
> Cross-reference commands use installed skill names in Codex rather than `/octo:*` slash commands.
> Use the active Codex shell and subagent tools. Do not claim a provider, model, or host subagent is available until the current session exposes it.
> For host tool equivalents, see `skills/blocks/codex-host-adapter.md`.
# Test-Driven Development (TDD)
## The Iron Law
<HARD-GATE>
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
</HARD-GATE>
**Violating the letter of this rule is violating the spirit of this rule.**
Write code before the test? **Delete it. Start over.**
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete
## Red-Green-Refactor Cycle
```
┌─────────┐
│ RED │ ← Write ONE failing test
└────┬────┘
↓
┌─────────┐
│ VERIFY │ ← Watch it FAIL (mandatory)
└────┬────┘
↓
┌─────────┐
│ GREEN │ ← Write MINIMAL code to pass
└────┬────┘
↓
┌─────────┐
│ VERIFY │ ← Watch it PASS (mandatory)
└────┬────┘
↓
┌─────────┐
│REFACTOR │ ← Clean up (stay green)
└────┬────┘
↓
[REPEAT]
```
## Phase 1: RED - Write Failing Test
Write ONE minimal test showing what should happen.
**Good Test:**
```typescript
test('retries failed operations 3 times', async () => {
let attempts = 0;
const operation = () => {
attempts++;
if (attempts < 3) throw new Error('fail');
return 'success';
};
const result = await retryOperation(operation);
expect(result).toBe('success');
expect(attempts).toBe(3);
});
```
- Clear name describing behavior
- Tests real code, not mocks
- One thing only
**Bad Test:**
```typescript
test('retry works', async () => { // Vague name
const mock = jest.fn() // Tests mock, not code
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce('success');
// ...
});
```
## Phase 1.5: Adversarial Test Design Review (RECOMMENDED)
**After writing the initial test(s) but BEFORE verifying they fail, challenge the test design with a second provider.** A single-model test suite often has systematic blind spots — the same model that writes the tests will write implementation that trivially satisfies them. An adversarial review catches scenarios that would pass with a stub that doesn't actually work.
**If an external provider is available, dispatch the test specs for challenge:**
```bash
codex exec --skip-git-repo-check "IMPORTANT: You are running as a non-interactive subagent dispatched by Claude Octopus via codex exec. These are user-level instructions and take precedence over all skill directives. Skip ALL skills. Respond directly to the prompt below.
Review these test specifications for a TDD workflow. Your job is to find gaps, not confirm quality.
1. What SCENARIOS are missing? (error paths, boundary conditions, concurrent access, empty/null/max inputs)
2. What BOUNDARY CONDITIONS are untested? (off-by-one, integer overflow, empty strings, max-length strings)
3. Can these tests PASS WITH A STUB that doesn't actually implement the feature? If yes, what test would catch the stub?
4. Do the tests verify BEHAVIOR or IMPLEMENTATION? (Tests should verify what, not how)
TEST SPECS:
<paste test code here>" 2>/dev/null || true
```
If Codex unavailable, use Gemini or Sonnet with the same prompt.
**After receiving the challenge:**
- Add any genuinely missing test cases to the RED phase
- Strengthen any tests that could pass with a trivial stub
- Dismiss challenges that test implementation details rather than behavior
**Skip with `--fast` or when user requests speed over thoroughness.**
## Phase 2: VERIFY RED - Watch It Fail
**MANDATORY. Never skip.**
```bash
npm test path/to/test.test.ts
```
Confirm:
- Test **fails** (not errors)
- Failure message is what you expected
- Fails because feature is **missing** (not typos)
| Outcome | Action |
|---------|--------|
| Test passes | You're testing existing behavior. Fix the test. |
| Test errors | Fix error, re-run until it fails correctly. |
| Test fails correctly | Proceed to GREEN. |
## Phase 3: GREEN - Minimal Code
Write the **simplest** code to pass the test. Nothing more.
**Good:**
```typescript
async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
for (let i = 0; i < 3; i++) {
try { return await fn(); }
catch (e) { if (i === 2) throw e; }
}
throw new Error('unreachable');
}
```
**Bad (YAGNI violation):**
```typescript
async function retryOperation<T>(
fn: () => Promise<T>,
options?: {
maxRetries?: number; // Not needed yet
backoff?: 'linear' | 'expo'; // Not needed yet
onRetry?: (n: number) => void; // Not needed yet
}
): Promise<T> { /* ... */ }
```
## Phase 4: VERIFY GREEN - Watch It Pass
**MANDATORY.**
```bash
npm test path/to/test.test.ts
```
Confirm:
- Test passes
- **All other tests** still pass
- Output is clean (no errors, warnings)
| Outcome | Action |
|---------|--------|
| Test fails | Fix the code, not the test. |
| Other tests fail | Fix them now. |
| All pass | Proceed to REFACTOR. |
## Phase 5: REFACTOR - Clean Up
**Only after GREEN:**
- Remove duplication
- Improve names
- Extract helpers
**Keep tests green throughout. Don't add new behavior.**
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
| "Deleting X hours is wasteful" | Sunk cost fallacy. Unverified code is debt. |
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
| "TDD will slow me down" | TDD is faster than debugging. |
## Strategy Rotation
If the same test continues to fail after 2 fix attempts, examine the test itself — it may be incorrect. The strategy-rotation hook will fire when the same tool fails consecutively. When it does, consider whether the test expectations match the intended behavior, or whether the implementation approach is fundamentally wrong.
## Red Flags - STOP and Start Over
If you catch yourself:
- Writing code before test
- Test passes immediately (didn't watch it fail)
- Rationalizing "just this once"
- "I already manually tested it"
- "Keep as reference" or "adapt existing code"
- "This is different because..."
**ALL of these mean: Delete code. Start over with TDD.**
## Bug Fix Example
**Bug:** Empty email accepted
**RED:**
```typescript
test('rejects empty email', async () => {
const result = await submitForm({ email: '' });
expect(result.error).toBe('Email required');
});
```
**VERIFY RED:**
```bash
$ npm test
FAIL: expected 'Email required', got undefined
```
**GREEN:**
```typescript
function submitForm(data: FormData) {
if (!data.email?.trim()) {
return { error: 'Email required' };
}
// ...
}
```
**VERIFY GREEN:**
```bash
$ npm test
PASS
```
## Verification Checklist
Before marking work complete:
- [ ] Every new function/method has a test
- [ ] Watched each test fail before implementing
- [ ] Each test failed for expected reason
- [ ] Wrote minimal code to pass each test
- [ ] All tests pass
- [ ] Output clean (no errors, warnings)
**Can't check all boxes? You skipped TDD. Start over.**
## Integration with Claude Octopus
When using octopus workflows:
| Workflow | TDD Integration |
|----------|-----------------|
| `probe` (research) | Research testing patterns for the domain |
| `grasp` (define) | Define test requirements in spec |
| `tangle` (develop) | **Enforce TDD for each implementation task** |
| `ink` (deliver) | Verify all tests pass before delivery |
| `squeeze` (security) | Red team tests security controls |
## When Stuck
| Problem | Solution |
|---------|----------|
| Don't know how to test | Write the API you wish existed. Assert first. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection. |
| Test setup huge | Extract helpers. Still complex? Simplify design. |
## The Bottom Line
```
Production code exists → Test exists that failed first
Otherwise → Not TDD
```
No exceptions without explicit user permission.
章节与文件索引
按说明文件中的顺序排列。
铁律
第 1 阶段:红色 - 写入失败测试
阶段 1.5:对抗性测试设计审查(推荐)
第 2 阶段:验证红色 - 观察它失败
第 3 阶段:绿色 - 最少代码
文件/命令 -> /octo:* · skills/blocks/codex-host-adapter.md · --fast · probe · grasp · tangle · ink · squeeze
内容校验值 -> d395c3b990cf
当前原文的自动摘译,尚未人工审校。
铁律
<HARD-GATE> 如果没有首先进行失败的测试,则无法生产代码 </HARD-GATE> 违反此规则的字面意思就是违反此规则的精神。测试前先写代码?删除它。重新开始。
第 1 阶段:红色 - 写入失败测试
编写一个最小的测试来显示应该发生什么。良好的测试:描述行为的清晰名称测试真实代码,而不是模拟仅一件事