typed-holes-refactor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Typed Holes Refactoring

Typed Holes 重构法

Systematically refactor codebases using the Design by Typed Holes meta-framework: treat architectural unknowns as typed holes, resolve them iteratively with test-driven validation, and propagate constraints through dependency graphs.
使用Design by Typed Holes元框架系统化重构代码库:将架构未知项视为类型化漏洞,通过测试驱动验证迭代解决,并通过依赖图传播约束。

Core Workflow

核心工作流

Phase 0: Hole Discovery & Setup

阶段0:漏洞发现与准备

1. Create safe working branch:
bash
git checkout -b refactor/typed-holes-v1
1. 创建安全的工作分支:
bash
git checkout -b refactor/typed-holes-v1

CRITICAL: Never work in main, never touch .beads/ in main

重要提示:永远不要在主分支工作,永远不要修改主分支的.beads/目录


**2. Analyze current state and identify holes:**

```bash
python scripts/discover_holes.py

**2. 分析当前状态并识别漏洞:**

```bash
python scripts/discover_holes.py

Creates REFACTOR_IR.md with hole catalog

生成包含漏洞目录的REFACTOR_IR.md文件


The Refactor IR documents:
- **Current State Holes**: What's unknown about the current system?
- **Refactor Holes**: What needs resolution to reach the ideal state?
- **Constraints**: What must be preserved/improved/maintained?
- **Dependencies**: Which holes block which others?

**3. Write baseline characterization tests:**

Create `tests/characterization/` to capture exact current behavior:

```python

重构IR文档记录:
- **当前状态漏洞**:当前系统存在哪些未知项?
- **重构漏洞**:要达到理想状态需要解决哪些问题?
- **约束条件**:必须保留、改进或维护哪些内容?
- **依赖关系**:哪些漏洞会阻碍其他漏洞的解决?

**3. 编写基准特征测试:**

创建`tests/characterization/`目录以捕获当前系统的精确行为:

```python

tests/characterization/test_current_behavior.py

tests/characterization/test_current_behavior.py

def test_api_contracts(): """All public APIs must behave identically post-refactor""" for endpoint in discover_public_apis(): old_result = run_current(endpoint, test_inputs) save_baseline(endpoint, old_result)
def test_performance_baselines(): """Record current performance - don't regress""" baselines = measure_all_operations() save_json("baselines.json", baselines)

Run tests on main branch - they should all pass. These are your safety net.
def test_api_contracts(): """所有公开API在重构后必须保持行为一致""" for endpoint in discover_public_apis(): old_result = run_current(endpoint, test_inputs) save_baseline(endpoint, old_result)
def test_performance_baselines(): """记录当前性能水平——不允许出现性能退化""" baselines = measure_all_operations() save_json("baselines.json", baselines)

在主分支运行测试——所有测试都应通过。这些测试是你的安全保障。

Phase 1-N: Iterative Hole Resolution

阶段1-N:迭代式漏洞解决

For each hole (in dependency order):
1. Select next ready hole:
bash
python scripts/next_hole.py
按照依赖顺序处理每个漏洞:
1. 选择下一个可处理的漏洞:
bash
python scripts/next_hole.py

Shows holes whose dependencies are resolved

显示所有依赖已解决的漏洞


**2. Write validation tests FIRST (test-driven):**

```python

**2. 先编写验证测试(测试驱动):**

```python

tests/refactor/test_h{N}_resolution.py

tests/refactor/test_h{N}_resolution.py

def test_h{N}_resolved(): """Define what 'resolved correctly' means""" # This should FAIL initially assert desired_state_achieved()
def test_h{N}_equivalence(): """Ensure no behavioral regressions""" old_behavior = load_baseline() new_behavior = run_refactored() assert old_behavior == new_behavior

**3. Implement resolution:**

- Refactor code to make tests pass
- Keep characterization tests passing
- Commit incrementally with clear messages

**4. Validate resolution:**

```bash
python scripts/validate_resolution.py H{N}
def test_h{N}_resolved(): """定义“正确解决”的标准""" # 初始状态下该测试应失败 assert desired_state_achieved()
def test_h{N}_equivalence(): """确保没有行为退化""" old_behavior = load_baseline() new_behavior = run_refactored() assert old_behavior == new_behavior

**3. 实现漏洞解决:**

- 重构代码使测试通过
- 确保特征测试持续通过
- 分阶段提交并附上清晰的提交信息

**4. 验证解决结果:**

```bash
python scripts/validate_resolution.py H{N}

Checks: tests pass, constraints satisfied, main untouched

检查:测试通过、约束满足、主分支未被修改


**5. Propagate constraints:**

```bash
python scripts/propagate.py H{N}

**5. 传播约束条件:**

```bash
python scripts/propagate.py H{N}

Updates dependent holes based on resolution

根据解决结果更新依赖漏洞


**6. Document and commit:**

```bash
git add .
git commit -m "Resolve H{N}: {description}

- Tests: tests/refactor/test_h{N}_*.py pass
- Constraints: {constraints satisfied}
- Propagates to: {dependent holes}"

**6. 文档记录并提交:**

```bash
git add .
git commit -m "Resolve H{N}: {description}

- Tests: tests/refactor/test_h{N}_*.py pass
- Constraints: {constraints satisfied}
- Propagates to: {dependent holes}"

Phase Final: Reporting

最终阶段:报告生成

Generate comprehensive delta report:
bash
python scripts/generate_report.py > REFACTOR_REPORT.md
Report includes:
  • Hole resolution summary with validation evidence
  • Metrics delta (LOC, complexity, coverage, performance)
  • Behavioral analysis (intentional changes documented)
  • Constraint validation (all satisfied)
  • Risk assessment and migration guide
生成全面的差异报告:
bash
python scripts/generate_report.py > REFACTOR_REPORT.md
报告包含:
  • 漏洞解决总结及验证证据
  • 指标差异(代码行数、复杂度、覆盖率、性能)
  • 行为分析(记录所有有意的变更)
  • 约束验证结果(所有约束均满足)
  • 风险评估与迁移指南

Key Principles

核心原则

1. Test-Driven Everything

1. 全流程测试驱动

  • Write validation criteria BEFORE implementing
  • Tests define "correct resolution"
  • Characterization tests are sacred - never let them fail
  • 在实现前先编写验证标准
  • 测试定义“正确解决”的标准
  • 特征测试是不可侵犯的底线——绝不能让它们失败

2. Hole-Driven Progress

2. 漏洞驱动的进度

  • Resolve holes in dependency order
  • Each resolution propagates constraints
  • Track everything formally in Refactor IR
  • 按依赖顺序解决漏洞
  • 每次解决都会传播约束条件
  • 在重构IR中正式跟踪所有内容

3. Continuous Validation

3. 持续验证

Every commit must validate:
  • ✅ Characterization tests pass (behavior preserved)
  • ✅ Resolution tests pass (hole resolved correctly)
  • ✅ Constraints satisfied
  • ✅ Main branch untouched
  • .beads/
    intact in main
每次提交必须验证:
  • ✅ 特征测试通过(行为保留)
  • ✅ 解决测试通过(漏洞已正确解决)
  • ✅ 约束条件满足
  • ✅ 主分支未被修改
  • ✅ 主分支的.beads/目录保持完整

4. Safe by Construction

4. 构建时保障安全

  • Work only in refactor branch
  • Main is read-only reference
  • Beads are untouchable historical artifacts
  • 仅在重构分支工作
  • 主分支作为只读参考
  • Beads是不可修改的历史工件

5. Formal Completeness

5. 形式化完整性

Design complete when:
  • All holes resolved and validated
  • All constraints satisfied
  • All phase gates passed
  • Metrics improved or maintained
当满足以下条件时,设计完成:
  • 所有漏洞已解决并验证
  • 所有约束条件已满足
  • 所有阶段关卡已通过
  • 指标已提升或保持

Hole Quality Framework

漏洞质量框架

SMART Criteria for Good Holes

优质漏洞的SMART标准

Every hole must be:
  • Specific: Clear, bounded question with concrete answer
    • ✓ Good: "How should error handling work in the API layer?"
    • ✗ Bad: "How to improve the code?"
  • Measurable: Has testable validation criteria
    • ✓ Good: "Reduce duplication from 60% to <15%"
    • ✗ Bad: "Make code better"
  • Achievable: Can be resolved with available information
    • ✓ Good: "Extract parsing logic to separate module"
    • ✗ Bad: "Predict all future requirements"
  • Relevant: Blocks meaningful progress on refactoring
    • ✓ Good: "Define core interface (blocks 5 other holes)"
    • ✗ Bad: "Decide variable naming convention"
  • Typed: Clear type/structure for resolution
    • ✓ Good:
      interface Architecture = { layers: Layer[], rules: Rule[] }
    • ✗ Bad: "Some kind of structure?"
每个漏洞必须符合:
  • 具体性:清晰、有边界的问题,有明确答案
    • ✓ 良好示例:“API层的错误处理应如何设计?”
    • ✗ 不良示例:“如何改进代码?”
  • 可衡量性:有可测试的验证标准
    • ✓ 良好示例:“将重复代码率从60%降至<15%”
    • ✗ 不良示例:“让代码变得更好”
  • 可实现性:可利用现有信息解决
    • ✓ 良好示例:“将解析逻辑提取到独立模块”
    • ✗ 不良示例:“预测所有未来需求”
  • 相关性:阻碍重构的实质性进展
    • ✓ 良好示例:“定义核心接口(阻碍其他5个漏洞)”
    • ✗ 不良示例:“决定变量命名规范”
  • 类型化:有清晰的解决结果类型/结构
    • ✓ 良好示例:
      interface Architecture = { layers: Layer[], rules: Rule[] }
    • ✗ 不良示例:“某种结构?”

Hole Estimation Framework

漏洞估算框架

Size holes using these categories:
SizeDurationCharacteristicsExamples
Nano1-2 hoursSimple, mechanical changesRename files, update imports
Small4-8 hoursSingle module refactorExtract class, consolidate functions
Medium1-3 daysCross-module changesDefine interfaces, reorganize packages
Large4-7 daysArchitecture changesLayer extraction, pattern implementation
Epic>7 daysSPLIT THIS HOLEToo large, break into smaller holes
Estimation Red Flags:
  • More than 3 dependencies → Likely Medium+
  • Unclear validation → Add time for discovery
  • New patterns/tools → Add learning overhead
使用以下类别对漏洞进行规模估算:
规模时长特征示例
微型1-2小时简单、机械性变更重命名文件、更新导入
小型4-8小时单模块重构提取类、合并函数
中型1-3天跨模块变更定义接口、重组包结构
大型4-7天架构级变更提取分层、实现设计模式
史诗级>7天拆分此漏洞规模过大,拆分为更小的漏洞
估算预警信号:
  • 依赖项超过3个 → 可能为中型及以上
  • 验证标准不清晰 → 增加发现时间
  • 涉及新模式/工具 → 增加学习成本

Hole Splitting Guidelines

漏洞拆分指南

Split a hole when:
  1. Estimate exceeds 7 days
  2. More than 5 dependencies
  3. Validation criteria unclear
  4. Multiple distinct concerns mixed
Splitting strategy:
Epic hole: "Refactor entire authentication system"
→ Split into:
  R10_auth_interface: Define new auth interface (Medium)
  R11_token_handling: Implement JWT tokens (Small)
  R12_session_management: Refactor sessions (Medium)
  R13_auth_middleware: Update middleware (Small)
  R14_auth_testing: Comprehensive test suite (Medium)
After splitting:
  • Update dependencies in REFACTOR_IR.md
  • Run
    python scripts/propagate.py
    to update graph
  • Re-sync with beads:
    python scripts/holes_to_beads.py
当出现以下情况时拆分漏洞:
  1. 估算时长超过7天
  2. 依赖项超过5个
  3. 验证标准不清晰
  4. 混合了多个不同关注点
拆分策略:
史诗级漏洞: "重构整个认证系统"
→ 拆分为:
  R10_auth_interface: 定义新的认证接口(中型)
  R11_token_handling: 实现JWT令牌(小型)
  R12_session_management: 重构会话管理(中型)
  R13_auth_middleware: 更新中间件(小型)
  R14_auth_testing: 全面测试套件(中型)
拆分后:
  • 在REFACTOR_IR.md中更新依赖关系
  • 运行
    python scripts/propagate.py
    更新依赖图
  • 与Beads同步:
    python scripts/holes_to_beads.py

Common Hole Types

常见漏洞类型

Architecture Holes

架构漏洞

python
"?R1_target_architecture": "What should the ideal structure be?"
"?R2_module_boundaries": "How should modules be organized?"
"?R3_abstraction_layers": "What layers/interfaces are needed?"
Validation: Architecture tests, dependency analysis, layer violation checks
python
"?R1_target_architecture": "理想的系统结构应该是什么样的?"
"?R2_module_boundaries": "模块应如何组织?"
"?R3_abstraction_layers": "需要哪些分层/接口?"
验证方式: 架构测试、依赖分析、分层违规检查

Implementation Holes

实现漏洞

python
"?R4_consolidation_targets": "What code should merge?"
"?R5_extraction_targets": "What code should split out?"
"?R6_elimination_targets": "What code should be removed?"
Validation: Duplication detection, equivalence tests, dead code analysis
python
"?R4_consolidation_targets": "哪些代码需要合并?"
"?R5_extraction_targets": "哪些代码需要拆分出去?"
"?R6_elimination_targets": "哪些代码需要删除?"
验证方式: 重复代码检测、等价性测试、死代码分析

Quality Holes

质量漏洞

python
"?R7_test_strategy": "How to validate equivalence?"
"?R8_migration_path": "How to safely transition?"
"?R9_rollback_mechanism": "How to undo if needed?"
Validation: Test coverage metrics, migration dry-runs, rollback tests
See HOLE_TYPES.md for complete catalog.
python
"?R7_test_strategy": "如何验证等价性?"
"?R8_migration_path": "如何安全过渡?"
"?R9_rollback_mechanism": "出现问题时如何回滚?"
验证方式: 测试覆盖率指标、迁移演练、回滚测试
完整漏洞类型目录请参考HOLE_TYPES.md

Constraint Propagation Rules

约束传播规则

Rule 1: Interface Resolution → Type Constraints

规则1: 接口解决 → 类型约束

When: Interface hole resolved with concrete types
Then: Propagate type requirements to all consumers

Example:
  Resolve R6: NodeInterface = BaseNode with async run()
  Propagates to:
    → R4: Parallel execution must handle async
    → R5: Error recovery must handle async exceptions
当: 接口漏洞已通过具体类型解决
则: 将类型要求传播给所有消费者

示例:
  解决R6: NodeInterface = 带有async run()的BaseNode
  传播至:
    → R4: 并行执行必须支持异步
    → R5: 错误恢复必须处理异步异常

Rule 2: Implementation → Performance Constraints

规则2: 实现 → 性能约束

When: Implementation resolved with resource usage
Then: Propagate limits to dependent holes

Example:
  Resolve R4: Parallelization with max_concurrent=3
  Propagates to:
    → R8: Rate limit = provider_limit / 3
    → R7: Memory budget = 3 * single_operation_memory
当: 实现已明确资源使用情况
则: 将限制条件传播给依赖漏洞

示例:
  解决R4: 并行化设置max_concurrent=3
  传播至:
    → R8: 速率限制 = 服务商限制 / 3
    → R7: 内存预算 = 3 * 单操作内存

Rule 3: Validation → Test Requirements

规则3: 验证 → 测试要求

When: Validation resolved with test requirements
Then: Propagate data needs upstream

Example:
  Resolve R9: Testing needs 50 examples
  Propagates to:
    → R7: Metrics must support batch evaluation
    → R8: Test data collection strategy needed
See CONSTRAINT_RULES.md for complete propagation rules.
当: 验证已明确测试要求
则: 将数据需求向上游传播

示例:
  解决R9: 测试需要50个示例
  传播至:
    → R7: 指标必须支持批量评估
    → R8: 需要测试数据收集策略
完整传播规则请参考CONSTRAINT_RULES.md

Success Indicators

成功指标

Weekly Progress

每周进度

  • 2-4 holes resolved
  • All tests passing
  • Constraints satisfied
  • Measurable improvements
  • 解决2-4个漏洞
  • 所有测试通过
  • 约束条件满足
  • 可衡量的改进

Red Flags (Stop & Reassess)

危险信号(立即停止并重新评估)

  • ❌ Characterization tests fail
  • ❌ Hole can't be resolved within constraints
  • ❌ Constraints contradict each other
  • ❌ No progress for 3+ days
  • ❌ Main branch accidentally modified
  • ❌ 特征测试失败
  • ❌ 漏洞无法在约束条件下解决
  • ❌ 约束条件相互矛盾
  • ❌ 连续3天以上无进展
  • ❌ 意外修改了主分支

Validation Gates

验证关卡

GateCriteriaCheck
Gate 1: Discovery CompleteAll holes cataloged, dependencies mapped
python scripts/check_discovery.py
Gate 2: Foundation HolesCore interfaces resolved, tests pass
python scripts/check_foundation.py
Gate 3: ImplementationAll refactor holes resolved, metrics improved
python scripts/check_implementation.py
Gate 4: Production ReadyMigration tested, rollback verified
python scripts/check_production.py
关卡标准检查方式
关卡1: 发现完成所有漏洞已分类、依赖关系已映射
python scripts/check_discovery.py
关卡2: 基础漏洞解决核心接口已解决、测试通过
python scripts/check_foundation.py
关卡3: 实现完成所有重构漏洞已解决、指标提升
python scripts/check_implementation.py
关卡4: 生产就绪迁移已测试、回滚已验证
python scripts/check_production.py

Claude-Assisted Workflow

Claude辅助工作流

This skill is designed for effective Claude/LLM collaboration. Here's how to divide work:
该技能专为Claude/LLM协作设计。以下是分工方式:

Phase 0: Discovery

阶段0:发现

Claude's Role:
  • Run
    discover_holes.py
    to analyze codebase
  • Suggest holes based on code analysis
  • Generate initial REFACTOR_IR.md structure
  • Write characterization tests to capture current behavior
  • Set up test infrastructure
Your Role:
  • Confirm holes are well-scoped
  • Prioritize which holes to tackle first
  • Review and approve REFACTOR_IR.md
  • Define critical constraints
Claude的角色:
  • 运行
    discover_holes.py
    分析代码库
  • 根据代码分析建议漏洞
  • 生成初始REFACTOR_IR.md结构
  • 编写特征测试以捕获当前行为
  • 搭建测试基础设施
你的角色:
  • 确认漏洞范围合理
  • 优先处理哪些漏洞
  • 审核并批准REFACTOR_IR.md
  • 定义关键约束条件

Phase 1-N: Hole Resolution

阶段1-N:漏洞解决

Claude's Role:
  • Write resolution tests (TDD) BEFORE implementation
  • Implement hole resolution to make tests pass
  • Run validation scripts:
    validate_resolution.py
    ,
    check_foundation.py
  • Update REFACTOR_IR.md with resolution details
  • Propagate constraints:
    python scripts/propagate.py H{N}
  • Generate commit messages documenting changes
Your Role:
  • Make architecture decisions (which pattern, which approach)
  • Assess risk and determine constraint priorities
  • Review code changes for correctness
  • Approve merge to main when complete
Claude的角色:
  • 在实现前编写解决测试(TDD)
  • 实现漏洞解决使测试通过
  • 运行验证脚本:
    validate_resolution.py
    ,
    check_foundation.py
  • 在REFACTOR_IR.md中更新解决详情
  • 传播约束条件:
    python scripts/propagate.py H{N}
  • 生成记录变更的提交信息
你的角色:
  • 做出架构决策(选择哪种模式、哪种方法)
  • 评估风险并确定约束优先级
  • 审核代码变更的正确性
  • 完成后批准合并到主分支

Phase Final: Reporting

最终阶段:报告生成

Claude's Role:
  • Generate comprehensive REFACTOR_REPORT.md
  • Document all metrics deltas
  • List all validation evidence
  • Create migration guides
  • Prepare PR description
Your Role:
  • Final review of report accuracy
  • Approve for production deployment
  • Conduct post-refactor retrospective
Claude的角色:
  • 生成全面的REFACTOR_REPORT.md
  • 记录所有指标差异
  • 列出所有验证证据
  • 创建迁移指南
  • 准备PR描述
你的角色:
  • 最终审核报告的准确性
  • 批准部署到生产环境
  • 进行重构后回顾

Effective Prompting Patterns

高效提示模式

Starting a session:
"I need to refactor [description]. Use typed-holes-refactor skill.
Start with discovery phase."
Resolving a hole:
"Resolve H3 (target_architecture). Write tests first, then implement.
Use [specific pattern/approach]."
Checking progress:
"Run check_completeness.py and show me the dashboard.
What's ready to work on next?"
Generating visualizations:
"Generate dependency graph showing bottlenecks and critical path.
Use visualize_graph.py with --analyze."
开始会话时:
"我需要重构[描述]。使用typed-holes-refactor技能。
从发现阶段开始。"
解决漏洞时:
"解决H3 (target_architecture)。先编写测试,再实现。
使用[特定模式/方法]。"
检查进度时:
"运行check_completeness.py并显示仪表板。
接下来可以处理什么?"
生成可视化时:
"生成显示瓶颈和关键路径的依赖图。
使用visualize_graph.py --analyze。"

Claude's Limitations

Claude的局限性

Claude CANNOT:
  • Make subjective architecture decisions (you must decide)
  • Determine business-critical constraints (you must specify)
  • Run tests that require external services (mock or you run them)
  • Merge to main (you must approve and merge)
Claude CAN:
  • Analyze code and suggest holes
  • Write comprehensive test suites
  • Implement resolutions within your constraints
  • Generate reports and documentation
  • Track progress across sessions (via beads + REFACTOR_IR.md)
Claude无法:
  • 做出主观的架构决策(必须由你决定)
  • 确定业务关键约束条件(必须由你指定)
  • 运行需要外部服务的测试(需要模拟或由你运行)
  • 合并到主分支(必须由你批准并合并)
Claude可以:
  • 分析代码并建议漏洞
  • 编写全面的测试套件
  • 在你的约束条件下实现解决方案
  • 生成报告和文档
  • 跨会话跟踪进度(通过beads + REFACTOR_IR.md)

Multi-Session Continuity

多会话连续性

At session start:
"Continue typed-holes refactoring. Import beads state and
show current status from REFACTOR_IR.md."
Claude will:
  • Read REFACTOR_IR.md to understand current state
  • Check which holes are resolved
  • Identify next ready holes
  • Resume where previous session left off
You should:
  • Keep REFACTOR_IR.md and .beads/ committed to git
  • Export beads state at session end:
    bd export -o .beads/issues.jsonl
  • Use /context before starting to ensure Claude has full context
会话开始时:
"继续typed-holes重构。导入beads状态并
从REFACTOR_IR.md显示当前状态。"
Claude会:
  • 读取REFACTOR_IR.md了解当前状态
  • 检查哪些漏洞已解决
  • 识别下一个可处理的漏洞
  • 从上一个会话中断的地方继续
你应该:
  • 将REFACTOR_IR.md和.beads/提交到git
  • 会话结束时导出beads状态:
    bd export -o .beads/issues.jsonl
  • 开始前使用/context确保Claude拥有完整上下文

Beads Integration

Beads集成

Why beads + typed holes?
  • Beads tracks issues across sessions (prevents lost work)
  • Holes track refactoring-specific state (dependencies, constraints)
  • Together: Complete continuity for long-running refactors
为什么Beads + Typed Holes?
  • Beads跨会话跟踪问题(防止工作丢失)
  • Holes跟踪重构特定状态(依赖关系、约束条件)
  • 结合使用:为长期重构提供完整的连续性

Setup

设置

bash
undefined
bash
undefined

Install beads (once)

安装beads(仅需一次)

go install github.com/steveyegge/beads/cmd/bd@latest
go install github.com/steveyegge/beads/cmd/bd@latest

After running discover_holes.py

运行discover_holes.py后

python scripts/holes_to_beads.py
python scripts/holes_to_beads.py

Check what's ready

检查可处理的漏洞

bd ready --json
undefined
bd ready --json
undefined

Workflow Integration

工作流集成

During hole resolution:
bash
undefined
漏洞解决过程中:
bash
undefined

Start work on a hole

开始处理一个漏洞

bd update bd-5 --status in_progress --json
bd update bd-5 --status in_progress --json

Implement resolution

实现解决方案

... write tests, implement code ...

... 编写测试、实现代码 ...

Validate resolution

验证解决方案

python scripts/validate_resolution.py H3
python scripts/validate_resolution.py H3

Close bead

关闭bead

bd close bd-5 --reason "Resolved H3: target_architecture" --json
bd close bd-5 --reason "Resolved H3: target_architecture" --json

Export state

导出状态

bd export -o .beads/issues.jsonl git add .beads/issues.jsonl REFACTOR_IR.md git commit -m "Resolve H3: Define target architecture"

**Syncing holes ↔ beads**:
```bash
bd export -o .beads/issues.jsonl git add .beads/issues.jsonl REFACTOR_IR.md git commit -m "Resolve H3: 定义目标架构"

**同步漏洞 ↔ Beads**:
```bash

After updating REFACTOR_IR.md manually

手动更新REFACTOR_IR.md后

python scripts/holes_to_beads.py # Sync changes to beads
python scripts/holes_to_beads.py # 将变更同步到Beads

After resolving holes

解决漏洞后

python scripts/holes_to_beads.py # Update bead statuses

**Cross-session continuity**:
```bash
python scripts/holes_to_beads.py # 更新Bead状态

**跨会话连续性**:
```bash

Session start

会话开始

bd import -i .beads/issues.jsonl bd ready --json # Shows ready holes python scripts/check_completeness.py # Shows overall progress
bd import -i .beads/issues.jsonl bd ready --json # 显示可处理的漏洞 python scripts/check_completeness.py # 显示整体进度

Session end

会话结束

bd export -o .beads/issues.jsonl git add .beads/issues.jsonl git commit -m "Session checkpoint: 3 holes resolved"

**Bead advantages**:
- Tracks work across days/weeks
- Shows dependency graph: `bd deps bd-5`
- Prevents context loss
- Integrates with overall project management
bd export -o .beads/issues.jsonl git add .beads/issues.jsonl git commit -m "会话 checkpoint: 已解决3个漏洞"

**Beads优势**:
- 跨天/周跟踪工作
- 显示依赖图: `bd deps bd-5`
- 防止上下文丢失
- 与整体项目管理集成

Scripts Reference

脚本参考

All scripts are in
scripts/
:
  • discover_holes.py
    - Analyze codebase and generate REFACTOR_IR.md
  • next_hole.py
    - Show next resolvable holes based on dependencies
  • validate_resolution.py
    - Check if hole resolution satisfies constraints
  • propagate.py
    - Update dependent holes after resolution
  • generate_report.py
    - Create comprehensive delta report
  • check_discovery.py
    - Validate Phase 0 completeness (Gate 1)
  • check_foundation.py
    - Validate Phase 1 completeness (Gate 2)
  • check_implementation.py
    - Validate Phase 2 completeness (Gate 3)
  • check_production.py
    - Validate Phase 3 readiness (Gate 4)
  • check_completeness.py
    - Overall progress dashboard
  • visualize_graph.py
    - Generate hole dependency visualization
  • holes_to_beads.py
    - Sync holes with beads issues
Run any script with
--help
for detailed usage.
所有脚本位于
scripts/
目录:
  • discover_holes.py
    - 分析代码库并生成REFACTOR_IR.md
  • next_hole.py
    - 根据依赖关系显示下一个可解决的漏洞
  • validate_resolution.py
    - 检查漏洞解决是否满足约束条件
  • propagate.py
    - 解决后更新依赖漏洞
  • generate_report.py
    - 创建全面的差异报告
  • check_discovery.py
    - 验证阶段0完成情况(关卡1)
  • check_foundation.py
    - 验证阶段1完成情况(关卡2)
  • check_implementation.py
    - 验证阶段2完成情况(关卡3)
  • check_production.py
    - 验证阶段3就绪情况(关卡4)
  • check_completeness.py
    - 整体进度仪表板
  • visualize_graph.py
    - 生成漏洞依赖关系可视化图
  • holes_to_beads.py
    - 同步漏洞与Beads问题
运行任何脚本时添加
--help
查看详细用法。

Meta-Consistency

元一致性

This skill uses its own principles:
Typed Holes PrincipleApplication to Refactoring
Typed HolesArchitectural unknowns cataloged with types
Constraint PropagationDesign constraints flow through dependency graph
Iterative RefinementHole-by-hole resolution cycles
Test-Driven ValidationTests define correctness
Formal CompletenessGates verify design completeness
We use the system to refactor the system.
该技能自身也遵循其核心原则:
Typed Holes原则在重构中的应用
类型化漏洞架构未知项带有类型的分类
约束传播设计约束通过依赖图流动
迭代细化逐个漏洞解决的循环
测试驱动验证测试定义正确性
形式化完整性关卡验证设计完成度
我们用这套系统来重构系统本身。

Advanced Topics

高级主题

For complex scenarios, see:
  • HOLE_TYPES.md - Detailed hole taxonomy
  • CONSTRAINT_RULES.md - Complete propagation rules
  • VALIDATION_PATTERNS.md - Test patterns for different hole types
  • EXAMPLES.md - Complete worked examples
针对复杂场景,请参考:
  • HOLE_TYPES.md - 详细的漏洞分类
  • CONSTRAINT_RULES.md - 完整的传播规则
  • VALIDATION_PATTERNS.md - 不同漏洞类型的测试模式
  • EXAMPLES.md - 完整的实战示例

Quick Start Example

快速开始示例

bash
undefined
bash
undefined

1. Setup

1. 准备工作

git checkout -b refactor/typed-holes-v1 python scripts/discover_holes.py
git checkout -b refactor/typed-holes-v1 python scripts/discover_holes.py

2. Write baseline tests

2. 编写基准测试

Create tests/characterization/test_*.py

创建tests/characterization/test_*.py

3. Resolve first hole

3. 解决第一个漏洞

python scripts/next_hole.py # Shows H1 is ready
python scripts/next_hole.py # 显示H1可处理

Write tests/refactor/test_h1_*.py (fails initially)

编写tests/refactor/test_h1_*.py(初始状态失败)

Refactor code until tests pass

重构代码直到测试通过

python scripts/validate_resolution.py H1 python scripts/propagate.py H1 git commit -m "Resolve H1: ..."
python scripts/validate_resolution.py H1 python scripts/propagate.py H1 git commit -m "Resolve H1: ..."

4. Repeat for each hole

4. 重复处理每个漏洞

...

...

5. Generate report

5. 生成报告

python scripts/generate_report.py > REFACTOR_REPORT.md
undefined
python scripts/generate_report.py > REFACTOR_REPORT.md
undefined

Troubleshooting

故障排除

Characterization tests fail

特征测试失败

Symptom: Tests that captured baseline behavior now fail
Resolution:
  1. Revert changes:
    git diff
    to see what changed
  2. Investigate: What behavior changed and why?
  3. Decision tree:
    • Intentional change: Update baselines with documentation
      python
      # Update baseline with reason
      save_baseline("v2_api", new_behavior,
                    reason="Switched to async implementation")
    • Unintentional regression: Fix the code, tests must pass
Prevention: Run characterization tests before AND after each hole resolution.
症状:捕获基准行为的测试现在失败
解决方法:
  1. 回滚变更:
    git diff
    查看变更内容
  2. 调查: 哪些行为发生了变化?原因是什么?
  3. 决策树:
    • 有意变更: 更新基准并记录原因
      python
      # 更新基准并说明原因
      save_baseline("v2_api", new_behavior,
                    reason="切换为异步实现")
    • 无意退化: 修复代码,测试必须通过
预防措施: 在每次漏洞解决前后都运行特征测试。

Hole can't be resolved

漏洞无法解决

Symptom: Stuck on a hole for >3 days, unclear how to proceed
Resolution:
  1. Check dependencies: Are they actually resolved?
    bash
    python scripts/visualize_graph.py --analyze
    # Look for unresolved dependencies
  2. Review constraints: Are they contradictory?
    • Example: C1 "preserve all behavior" + C5 "change API contract" → Contradictory
    • Fix: Renegotiate constraints with stakeholders
  3. Split the hole: If hole is too large
    bash
    # Original: R4_consolidate_all (Epic, 10+ days)
    # Split into:
    R4a_consolidate_parsers (Medium, 2 days)
    R4b_consolidate_validators (Small, 1 day)
    R4c_consolidate_handlers (Medium, 2 days)
  4. Check for circular dependencies:
    bash
    python scripts/visualize_graph.py
    # Look for cycles: R4 → R5 → R6 → R4
    • Fix: Break cycle by introducing intermediate hole or redefining dependencies
Escalation: If still stuck after 5 days, consider alternative refactoring approach.
症状:卡在某个漏洞上超过3天,不清楚如何推进
解决方法:
  1. 检查依赖关系: 它们真的都解决了吗?
    bash
    python scripts/visualize_graph.py --analyze
    # 查找未解决的依赖项
  2. 审查约束条件: 它们是否相互矛盾?
    • 示例: C1 "保留所有行为" + C5 "修改API契约" → 矛盾
    • 修复: 与利益相关者重新协商约束条件
  3. 拆分漏洞: 如果漏洞过大
    bash
    # 原始: R4_consolidate_all(史诗级,10+天)
    # 拆分为:
    R4a_consolidate_parsers(中型,2天)
    R4b_consolidate_validators(小型,1天)
    R4c_consolidate_handlers(中型,2天)
  4. 检查循环依赖:
    bash
    python scripts/visualize_graph.py
    # 查找循环: R4 → R5 → R6 → R4
    • 修复: 通过引入中间漏洞或重新定义依赖关系打破循环
升级处理: 如果5天后仍无法解决,考虑其他重构方法。

Contradictory Constraints

约束条件矛盾

Symptom: Cannot satisfy all constraints simultaneously
Example:
  • C1: "Preserve exact current behavior" (backward compatibility)
  • C5: "Reduce response time by 50%" (performance improvement)
  • Current behavior includes slow, synchronous operations
Resolution Framework:
  1. Identify the conflict:
    markdown
    C1 requires: Keep synchronous operations
    C5 requires: Switch to async operations
    → Contradiction: Can't be both sync and async
  2. Negotiate priorities:
    OptionC1C5Tradeoff
    A: Keep syncNo performance gain
    B: Switch to asyncBreaking change
    C: Add async, deprecate sync⚠️Migration burden
  3. Choose resolution strategy:
    • Relax constraint: Change C1 to "Preserve behavior where possible"
    • Add migration period: C implemented over 2 releases
    • Split into phases: Phase 1 (C1), Phase 2 (C5)
  4. Document decision:
    markdown
    ## Constraint Resolution: C1 vs C5
    
    **Decision**: Relax C1 to allow async migration
    **Rationale**: Performance critical for user experience
    **Migration**: 3-month deprecation period for sync API
    **Approved by**: [Stakeholder], [Date]
症状:无法同时满足所有约束条件
示例:
  • C1: "保留当前所有行为"(向后兼容)
  • C5: "将响应时间减少50%"(性能提升)
  • 当前行为包含缓慢的同步操作
解决框架:
  1. 识别冲突:
    markdown
    C1要求: 保留同步操作
    C5要求: 切换为异步操作
    → 矛盾: 无法同时支持同步和异步
  2. 协商优先级:
    选项C1C5权衡
    A: 保留同步无性能提升
    B: 切换为异步破坏性变更
    C: 添加异步,弃用同步⚠️迁移负担
  3. 选择解决策略:
    • 放宽约束: 将C1改为“尽可能保留行为”
    • 添加迁移周期: 分2个版本实现方案C
    • 分阶段处理: 阶段1(满足C1),阶段2(满足C5)
  4. 记录决策:
    markdown
    ## 约束解决: C1 vs C5
    
    **决策**: 放宽C1以允许异步迁移
    **理由**: 性能对用户体验至关重要
    **迁移**: 同步API的3个月弃用期
    **批准人**: [利益相关者], [日期]

Circular Dependencies

循环依赖

Symptom:
visualize_graph.py
shows cycles
Example:
R4 (consolidate parsers) → depends on R6 (define interface)
R6 (define interface) → depends on R4 (needs parser examples)
Resolution strategies:
  1. Introduce intermediate hole:
    H0_parser_analysis: Analyze existing parsers (no dependencies)
    R6_interface: Define interface using H0 analysis
    R4_consolidate: Implement using R6 interface
  2. Redefine dependencies:
    • Maybe R4 doesn't actually need R6
    • Or R6 only needs partial R4 (split R4)
  3. Accept iterative refinement:
    R6_interface_v1: Initial interface (simple)
    R4_consolidate: Implement with v1 interface
    R6_interface_v2: Refine based on R4 learnings
Prevention: Define architecture holes before implementation holes.
症状:
visualize_graph.py
显示循环
示例:
R4 (合并解析器) → 依赖R6 (定义接口)
R6 (定义接口) → 依赖R4 (需要解析器示例)
解决策略:
  1. 引入中间漏洞:
    H0_parser_analysis: 分析现有解析器(无依赖)
    R6_interface: 基于H0的分析定义接口
    R4_consolidate: 使用R6接口实现
  2. 重新定义依赖关系:
    • 可能R4实际上不需要R6
    • 或者R6只需要R4的部分内容(拆分R4)
  3. 接受迭代细化:
    R6_interface_v1: 初始接口(简单版)
    R4_consolidate: 使用v1接口实现
    R6_interface_v2: 基于R4的经验优化
预防措施: 在实现漏洞之前先定义架构漏洞。

No Progress for 3+ Days

连续3天以上无进展

Symptom: Feeling stuck, no commits, uncertain how to proceed
Resolution checklist:
  • Review REFACTOR_IR.md: Are holes well-defined (SMART criteria)?
    • If not: Rewrite holes to be more specific
  • Check hole size: Is current hole >7 days estimate?
    • If yes: Split into smaller holes
  • Run dashboard:
    python scripts/check_completeness.py
    • Are you working on a blocked hole?
    • Switch to a ready hole instead
  • Visualize dependencies:
    python scripts/visualize_graph.py --analyze
    • Identify bottlenecks
    • Look for parallel work opportunities
  • Review constraints: Are they achievable?
    • Renegotiate if necessary
  • Seek external review:
    • Share REFACTOR_IR.md with colleague
    • Get feedback on approach
  • Consider alternative: Maybe this refactor isn't feasible
    • Document why
    • Propose different approach
Reset protocol: If still stuck, revert to last working state and try different approach.
症状: 感到停滞,无提交,不确定如何推进
解决清单:
  • 审查REFACTOR_IR.md: 漏洞是否符合SMART标准?
    • 如果不符合: 重写漏洞使其更具体
  • 检查漏洞规模: 当前漏洞估算是否超过7天?
    • 如果是: 拆分为更小的漏洞
  • 运行仪表板:
    python scripts/check_completeness.py
    • 你是否在处理一个被阻塞的漏洞?
    • 改为处理可立即开始的漏洞
  • 可视化依赖关系:
    python scripts/visualize_graph.py --analyze
    • 识别瓶颈
    • 寻找并行工作的机会
  • 审查约束条件: 它们是否可实现?
    • 必要时重新协商
  • 寻求外部审查:
    • 与同事分享REFACTOR_IR.md
    • 获取对方法的反馈
  • 考虑替代方案: 也许此重构不可行
    • 记录原因
    • 提出不同的方法
重置协议: 如果仍然停滞,回滚到最后可工作的状态并尝试其他方法。

Estimation Failures

估算失败

Symptom: Hole taking 3x longer than estimated
Analysis:
  1. Why did estimate fail?
    • Underestimated complexity
    • Unforeseen dependencies
    • Unclear requirements
    • Technical issues (tool problems, infrastructure)
  2. Immediate actions:
    • Update REFACTOR_IR.md with revised estimate
    • If >7 days, split the hole
    • Update beads:
      bd update bd-5 --note "Revised estimate: 5 days (was 2)"
  3. Future improvements:
    • Use actual times to calibrate future estimates
    • Add buffer for discovery (20% overhead)
    • Note uncertainty in IR: "Estimate: 2-4 days (high uncertainty)"
Learning: Track actual vs estimated time in REFACTOR_REPORT.md for future reference.

Begin with Phase 0: Discovery. Always work in a branch. Test first, refactor second.
症状: 漏洞处理时间是估算的3倍以上
分析:
  1. 估算失败的原因?
    • 低估了复杂度
    • 未预见的依赖关系
    • 需求不明确
    • 技术问题(工具故障、基础设施问题)
  2. 立即行动:
    • 在REFACTOR_IR.md中更新估算时间
    • 如果超过7天,拆分漏洞
    • 更新Beads:
      bd update bd-5 --note "修订估算: 5天(原2天)"
  3. 未来改进:
    • 使用实际耗时校准未来估算
    • 为发现工作添加20%的缓冲时间
    • 在IR中注明不确定性: "估算: 2-4天(高不确定性)"
经验总结: 在REFACTOR_REPORT.md中记录实际耗时与估算耗时的对比,为未来参考。

从阶段0开始:发现。始终在分支中工作。先测试,后重构。