Skill: melody1015/forge-loop (version 1.0.0)

--- name: forge description: "Forge 🔨 — Repair-Inspect loop orchestrator. Automated code repair with independent inspection, dependency-aware parallel execution, protected file guardrails, and crash-recoverable state. Use when: fixing multiple code issues (bug fixes, review board recommendations, audit findings), need verified repairs with independent QA, want safe automated code changes with rollback protection. NOT for: simple one-line fixes, architecture decisions, prompt modifications." --- # Forge 🔨 — 维修-监理自动循环 Automated repair-inspect loop with state persistence, dependency analysis, and safety guardrails. ## When to Use - Multiple repair tasks from review board / audit / user instructions - Need independent verification (not just "looks fixed") - Want protected file safety + auto-commit on PASS ## Quick Start ```bash cd /path/to/project # 1. Initialize python3 ~/clawd/skills/forge/scripts/forge.py init # 2. Add tasks python3 forge.py add "修复空值处理" --criteria "空输入不崩溃" --priority P0 python3 forge.py add "清理废弃代码" --criteria "无import报错" --depends task-001 # 3. See execution plan python3 forge.py plan # 4. Run (outputs spawn instructions) python3 forge.py run # 5. Execute spawns, then run again to check results python3 forge.py run # checks results, auto-loops on FAIL # 6. When all done python3 forge.py summary ``` ## CLI Reference | Command | Description | |---------|-------------| | `init --workdir DIR` | Initialize forge session | | `add "desc" --criteria "..." --depends task-001 --priority P0` | Add repair task | | `plan` | Show dependency graph + parallel execution waves | | `run` | Advance state machine (spawn or check results) | | `status` | Show current progress | | `check` | Pre-commit safety check (protected files, deletions) | | `summary` | Generate completion report | | `reset` | Clear state | ## How It Works ### State Machine (per task) ``` pending → repairing → inspecting → done ↑ │ └── fail ──┘ (auto-loop, max 5 rounds) inspecting → needs_human (pause, escalate) inspecting → escalated (>5 rounds) repairing → needs_human (all BLOCKED) ``` ### Dependency-Aware Parallel Execution Tasks without dependencies run in parallel. `forge.py plan` shows execution waves: ``` Wave 1: task-001, task-002, task-003 (并行) Wave 2: task-004 ← task-001 (等task-001完成) ``` ### Safety Guardrails (3 layers) 1. **Protected files** — `protected-files.txt` in project root. Listed files cannot be modified by repair agents. Touching them → BLOCKED → NEEDS_HUMAN. 2. **Pre-commit diff check** — `forge.py check` detects: file deletions, protected file modifications, abnormally large changes. 3. **Prompt constraints** — Repair engineer prompt explicitly forbids deletions, protected files, cron changes. ### Experience Accumulation Each repair produces a `repair_pattern` with error classification and reusable solution templates. These are stored in `forge-reflections.jsonl` and the most recent 5 patterns are injected into future repair tasks as context. ## Integration with AI Agents When the agent receives repair tasks (from code review, audit, or user): ```python # 1. Init forge in project dir exec("cd /path/to/project && python3 ~/clawd/skills/forge/scripts/forge.py init") # 2. Add tasks exec("python3 forge.py add 'Fix null handling in processor' --criteria 'No crash on empty input' --priority P0") # 3. Run to get spawn instructions exec("python3 forge.py run") # → Script outputs spawn instructions # 4. Execute spawns sessions_spawn(task=read(task_file), label=label, model=model) # 5. After spawn completes, run again exec("python3 forge.py run") # → Checks repair result → prepares inspector spawn # → Or auto-loops on FAIL → prepares next repair spawn # 6. On all PASS → git commit + notify ``` ## File Layout ``` forge/ ├── SKILL.md # This file ├── scripts/ │ └── forge.py # Core orchestrator ├── references/ │ └── protocol.md # Full protocol documentation └── assets/ └── templates/ ├── repair-engineer.md # Repair agent role reference └── inspector.md # Inspector role reference ``` ### Project-side files (created by forge) ``` project/ ├── forge-state.json # State persistence (crash recovery) ├── forge-reflections.jsonl # Project-specific experience (stays with project) ├── forge-output/ # Task files and results │ ├── task-001-repair-r1.task.md # Repair spawn task │ ├── task-001-repair-r1.json # Repair result │ ├── task-001-inspect-r1.task.md # Inspect spawn task │ └── task-001-inspect-r1.json # Inspect result └── protected-files.txt # (optional) Protected file list ``` ### Experience: Two-Layer Architecture ``` forge/reflections/patterns.jsonl # Universal patterns (cross-project, stays with skill) project/forge-reflections.jsonl # Project-specific patterns (stays with project) ``` - **Universal layer** (`forge/reflections/patterns.jsonl`): Abstract lessons stripped of file paths and project context. Auto-extracted from project patterns after each repair. Deduped by pattern_name. Injected into ALL future repairs across any project. - **Project layer** (`{project}/forge-reflections.jsonl`): Full detail with file names, paths, project-specific context. Only injected when working on that project. - **Auto-extraction**: After each repair, `extract_universal_pattern()` checks if the pattern is generalizable (not too many project-specific paths). If so, it's added to the universal layer with dedup. ## Doc-Sync Check (文档同步检查) Forge收尾时自动检查：修改的代码文件是否有关联文档需要同步更新。 ### 工作原理 1. **优先运行 `scripts/tools/doc-sync-checker.py --json`**（如果存在） 2. **回退到 `references/doc-sync-manifest.yaml`**：交叉对比forge修改的文件与manifest中的authority→consumer映射 ### 项目配置 在项目中创建 `references/doc-sync-manifest.yaml`： ```yaml facts: api_config: authority: src/config.py consumers: - docs/api-reference.md - docs/deployment-guide.md last_synced: 2026-03-01 ``` Forge完成报告会显示： ``` 📄 文档同步检查 — 2 个文档可能需要更新: ⚠️ docs/api-reference.md 可能需要同步更新（api_config 的权威源 src/config.py 已修改） ``` ## Configuration Via `init` flags or `forge-state.json` config section: | Key | Default | Description | |-----|---------|-------------| | `model` | `anthropic/claude-opus-4-6` | LLM model for agents | | `max_rounds` | `5` | Max repair-inspect cycles before escalation | | `repair_timeout` | `600` | Repair agent timeout (seconds) | | `inspect_timeout` | `300` | Inspector timeout (seconds) | | `auto_commit` | `true` | Auto git-commit on PASS |

path: assets/templates/inspector.md
content: # 🔍 监理（Inspector）

你是独立监理，验收修复是否真正解决了问题。

## 核心原则

**你不是来表扬的，你是来找问题的。**

- "已修复" ≠ 真修了
- 代码改了 ≠ 问题解决了
- 测试通过 ≠ 边缘情况覆盖了

## 验收方法论

1. **代码验证**（静态）— 确认改动逻辑正确，检查回归风险
2. **运行验证**（动态）— 实际执行代码，用真实数据验证
3. **集成验证** — 上下游脚本是否仍正常
4. **持久性验证** — 重启/新数据后是否仍有效

## 判定标准

- **PASS** — 验收标准全部满足，无回归
- **FAIL** — 问题未解决或引入新问题
- **CONDITIONAL** — 核心修复但边缘未覆盖
- **NEEDS_HUMAN** — 需要人工决策（方向/权限/逻辑取舍）

## 规则

1. **必须跑代码验证** — 不接受"看起来对了"
2. **必须引用实际输出** — evidence 字段给出真实数据
3. **发现新问题要分级** — critical/warning/info
4. **不替修复者修bug** — 记录问题打回，不自己改
5. **独立判断** — 不受修复者说法影响


path: assets/templates/repair-engineer.md
content: # 🔧 维修工程师（Repair Engineer）

你是维修工程师，负责精准修复指定问题。

## 核心原则

**最小改动，精准修复。**

- 只改需要改的，不顺手重构
- 修一个bug不引入两个新bug
- 不确定的地方标记 `NEEDS_REVIEW`
- 每个修复必须可验证

## 修复方法论

1. **诊断** — 读代码，定位根因，区分表面症状和底层原因
2. **方案** — 选最小侵入性方案（安全 > 优雅）
3. **实施** — edit 精确修改，保留原有风格
4. **自测** — 运行代码确认输出正确，检查边缘情况

## 修复状态定义

- **FIXED** — 根因修复 + 自测通过 + 回归风险可接受
- **PARTIAL** — 核心修复但边缘情况待验证
- **BLOCKED** — 需外部条件（权限/数据/人工确认）
- **SKIPPED** — 已被后续事件解决

## 安全规则

1. 🚫 禁止删除文件（用 `# DEPRECATED` 标记）
2. 🚫 禁止修改受保护文件（BLOCKED并说明）
3. ✅ 只改任务指定的文件
4. ✅ 用 edit 精确修改，不重写整个文件
5. ✅ JSON修改后验证格式
6. ✅ 不做 git commit（由编排器统一处理）


path: references/protocol.md
content: # 🔄 Forge 维修-监理自动循环协议

## 流程

```
任务进入
  │
  ▼
┌──────────────────────────────┐
│  派维修工程师 (spawn)         │
│  输入: 任务 + 上轮issues     │
└──────────┬───────────────────┘
           ▼
┌──────────────────────────────┐
│  检查维修报告                 │
│  全BLOCKED → NEEDS_HUMAN     │
│  有FIXED → 继续监理           │
└──────────┬───────────────────┘
           ▼
┌──────────────────────────────┐
│  派监理 (spawn)               │
│  输入: 验收标准 + 维修报告    │
└──────────┬───────────────────┘
           ▼
┌──────────────────────────────┐
│  判定                        │
│  PASS → commit + 通知 ✅      │
│  FAIL → 回到维修（自动）      │
│  NEEDS_HUMAN → 暂停           │
│  >5轮 → 升级给人              │
└──────────────────────────────┘
```

## 触发条件

自动启动此循环：
1. Code review / audit findings that need fixing
2. Automated monitoring detects high severity issues
3. User says "fix X" / "resolve X"

## 行为承诺

1. **FAIL/CONDITIONAL → 自动循环**，不问人
2. **PASS → 自动commit**，然后通知
3. **NEEDS_HUMAN → 暂停**，把问题发给人
4. **超5轮 → 升级**，承认能力不足

## 安全护栏（三层）

| 层 | 作用 | 机制 |
|----|------|------|
| 第一层 | 定义 | `protected-files.txt` 列出禁碰文件 |
| 第二层 | 检测 | commit前diff审查（删除/保护/规模） |
| 第三层 | 预防 | 维修工程师prompt约束 |

## 不适用场景

- Prompt修改（需人审阅）
- 架构决策（需人拍板）
- <10分钟简单修复（直接改）
- 涉及受保护文件（需授权）

## 成本参考

- 每轮: 维修(~30K tokens) + 监理(~15K tokens) ≈ $2.7
- 5轮上限 ≈ $13.5（一般2-3轮收敛）


path: reflections/README.md
content: # Universal Patterns

Cross-project repair experience. Auto-populated by Forge after each repair cycle.

## Format (JSONL)

```json
{"pattern_name": "descriptive_name", "error_type": "category", "solution_template": "abstract fix approach", "prevention": "how to avoid in future"}
```

Patterns are auto-extracted from project-specific reflections, stripped of file paths and project context.
Deduped by `pattern_name`.


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)