Exploring the workspace to align the module-repair skill with the existing Soul structure and other modules.
Checking for an existing output path or partial generation for this soul.
# Module Repair — Modular Soul Surgical Restoration

> **Module ID**: `SKILL-MODULE-REPAIR`  
> **File Path**: `skills/module-repair.md`  
> **Soul Compatibility**: nanoclaw Modular Soul Maintenance Engineer  
> **Primary Path**: `M3` (Repair / Restore)  
> **Secondary Paths**: `M1` (Audit findings → repair), `M5` (Post-integration regression), `M7` (Emergency hotfix after publish failure)  
> **Typical Deliverables**: Repair report, corrected module diff, cross-reference patch list, regression checklist, changelog entry  
> **Upstream Dependencies**: `SOUL.md`, `RULES.md`, `SKILL.md`, `SKILLS-MANIFEST.md` (load before repair)  
> **Frequently Stacked Modules**: `skills/module-audit.md`, `skills/integration-validation.md`, `references/soul-anatomy.md`, `references/quality-gates.md`, `references/versioning-sop.md`

---

## 0. Module Charter & Activation Discipline

### 0.1 What This Module Solves

Modular Souls degrade. Modules drift from each other. Triggers stop firing. Cross-references point to deleted files. `SKILL.md` routes to the wrong skill. `RULES.md` contradicts `STYLE.md`. A `skills/*.md` file becomes a wall of generic fluff. A reference framework goes stale after the domain evolved.

**Module Repair** is the surgical restoration protocol for a Modular Soul repository. It does not "rewrite everything." It:

1. **Diagnoses** the failure mode with evidence, not vibes
2. **Classifies** severity and repair strategy before touching text
3. **Repairs** with minimal, traceable diffs that preserve intent
4. **Verifies** cross-module consistency and trigger integrity
5. **Documents** what broke, why, and how to prevent recurrence

This is a **pluggable specialist skill**. When a request hits repair triggers or path `M3`, load this module and **override** the simplified repair steps in `SKILL.md` with this full SOP.

### 0.2 Iron Laws After Loading

| # | Iron Law | Violation Consequence |
|:---|:---|:---|
| R1 | **Diagnose before edit** | Fixes symptoms; creates new contradictions |
| R2 | **One repair objective per pass** | Unreviewable diffs; mixed intent commits |
| R3 | **Preserve Soul identity** | Repairs that accidentally rebrand the persona |
| R4 | **Minimal diff principle** | Scope creep disguised as maintenance |
| R5 | **Cross-module verification mandatory** | Local fix breaks global orchestration |
| R6 | **No silent deletions** | Lost triggers, broken manifest entries, orphan users |
| R7 | **Evidence-backed root cause** | "Feels unclear" is not a diagnosis |
| R8 | **Repair ≠ full redesign** | Route to decomposition/redesign paths instead |
| R9 | **Manifest stays authoritative** | File exists but manifest omits it → invisible skill |
| R10 | **Post-repair regression gate** | Shipping broken activation routing |

### 0.3 Relationship to Main Skill Orchestrator

```
SKILL.md routes M3 (Repair)
    → Load skills/module-repair.md (this module)
    → Execute 7-Phase Restoration Protocol
    → Stack skills/integration-validation.md if cross-file impact ≥ 2 modules
    → Deliver against Repair Completion Checklist (§12)
```

**This module owns**: symptom taxonomy, repair decision trees, per-file-type playbooks, diff discipline, regression verification.  
**This module does not own**: initial Soul authoring (`M0`), greenfield decomposition (`M2`), publishing pipeline (`M6`) — but may hand off to them.

---

## 1. Activation Triggers

### 1.1 Strong Triggers (Load Immediately)

| Category | Trigger Phrases / Signals |
|:---|:---|
| **Explicit repair** | `repair module`, `fix skill`, `restore soul`, `patch SKILL.md`, `broken trigger`, `contradiction` |
| **Degradation symptoms** | `stopped working`, `wrong mode`, `loads wrong file`, `ignored RULES`, `inconsistent tone` |
| **Structural damage** | `orphan file`, `missing cross-reference`, `manifest out of sync`, `dead link`, `duplicate triggers` |
| **Quality collapse** | `too generic`, `corporate fluff`, `not actionable`, `shallow module`, `placeholder content` |
| **Post-change regression** | `after we edited`, `broke after merge`, `used to work`, `regression` |
| **User artifacts** | Pasted module excerpt + "this is wrong" / diff showing drift |
| **Commands** | `--mode repair`, `/repair-module`, `M3` path from `SKILL.md` |

### 1.2 Weak Triggers (Context-Dependent)

| Signal | Condition |
|:---|:---|
| "Improve this skill" | User means *fix broken behavior*, not enhance features → repair |
| "Review my Soul" | Audit findings include P1/P0 defects → repair after `module-audit` |
| "Update for new LLM" | Compatibility drift → repair + `references/versioning-sop.md` |
| "Merge two skills" | Integration surgery → repair + possible decomposition consult |

### 1.3 Anti-Triggers (Do Not Lead With This Module)

| Scenario | Correct Route |
|:---|:---|
| Greenfield Soul creation | `M0` Authoring workflow |
| "Design me a new Soul from scratch" | Decomposition + authoring |
| User wants strategic repositioning of persona | `SOUL.md` redesign path — not patch |
| Single typo in one bullet | Quick fix; full protocol optional |
| User asks *how* modular Souls work (education) | Reference mode; no repair |

### 1.4 Stacking Rules

| Detected Signal | Stack Module |
|:---|:---|
| Unknown scope / "whole Soul feels off" | `skills/module-audit.md` first |
| ≥ 3 files touched OR manifest change | `skills/integration-validation.md` |
| Version bump / publish after repair | `references/versioning-sop.md` |
| Architectural contradiction (identity vs rules) | `references/soul-anatomy.md` |
| Trigger collision across skills | `SKILLS-MANIFEST.md` + §6.4 Trigger Arbitration |

---

## 2. Failure Mode Taxonomy

Before repair, classify the defect. **Wrong classification → wrong surgery.**

### 2.1 Defect Classes

| Code | Class | Definition | Typical Location |
|:---|:---|:---|:---|
| `D1` | **Orchestration Break** | `SKILL.md` routes incorrectly; wrong module load order | `SKILL.md`, `SKILLS-MANIFEST.md` |
| `D2` | **Cross-Module Contradiction** | Two files assert incompatible rules or behaviors | Any pair; often `RULES.md` ↔ `skills/*` |
| `D3` | **Reference Rot** | Dead paths, renamed files, stale § references | All modules |
| `D4` | **Trigger Failure** | Keywords exist but don't fire; missing from manifest index | `SKILL.md`, `SKILLS-MANIFEST.md`, skill headers |
| `D5` | **Structural Malformation** | Missing required sections; wrong heading hierarchy | `skills/*`, `references/*` |
| `D6` | **Quality Decay** | Generic filler; no decision trees; no examples | Usually `skills/*`, `references/*` |
| `D7` | **Scope Bloat** | Module absorbed responsibilities of others | God-skill files |
| `D8` | **Scope Starvation** | Module too thin to be pluggable | Stub skills |
| `D9` | **Identity Drift** | Tone/expertise level diverges from `SOUL.md` | `STYLE.md`, any module |
| `D10` | **Boundary Violation** | Module instructs forbidden behaviors per `RULES.md` | Any |
| `D11` | **Manifest Desync** | File ↔ registry mismatch | `SKILLS-MANIFEST.md` |
| `D12` | **Activation Noise** | Overlapping triggers cause wrong skill dominance | Multiple `skills/*` |

### 2.2 Severity Matrix

| Severity | Criteria | Response SLA | Repair Depth |
|:---|:---|:---|:---|
| **P0 — Soul Unsafe** | `D10` boundary violation; harmful instructions; identity collapse | Immediate hotfix | Surgical + mandatory audit |
| **P1 — Orchestration Broken** | `D1`, `D4`, `D11`; wrong skill loads >50% of time | Same session | Full protocol |
| **P2 — Consistency Broken** | `D2`, `D9`; user-visible confusion | Standard | Targeted cross-patch |
| **P3 — Maintainability** | `D3`, `D5`, `D6`, `D7`, `D8` | Scheduled | Module-local or split/merge |
| **P4 — Cosmetic** | Typos, formatting, non-functional links in examples | Opportunistic | Minimal diff |

---

## 3. Seven-Phase Restoration Protocol

### Overview

```
┌────────┐   ┌────────┐   ┌──────────┐   ┌────────┐   ┌────────┐   ┌────────┐   ┌─────────┐
│1.Triage│ → │2.Scout │ → │3.Diagnose│ → │4.Plan  │ → │5.Repair│ → │6.Verify│ → │7.Record │
│        │   │  Repo  │   │          │   │        │   │        │   │        │   │         │
└────────┘   └────────┘   └──────────┘   └────────┘   └────────┘   └────────┘   └─────────┘
                ↑______________________________________________|
                         new defects found during verify
```

**Todo discipline** (when tooling available):

```
triage → scout → diagnose → plan → repair → verify → record → deliver
```

---

### Phase 1: Triage — Stabilize & Scope

**Goal**: Define *what* is broken, *for whom*, and *whether repair is the right move*.

#### 1.1 Intake Form (Complete Before Reading Files)

| Field | Capture |
|:---|:---|
| **Reporter** | User / audit / self-detected during integration |
| **Symptom** | Observable failure (quote user words verbatim) |
| **Expected** | Correct behavior per Soul contract |
| **Trigger context** | User phrase, task type, or file being edited |
| **Blast radius** | Single file / skill family / whole Soul |
| **Recency** | Always broken / regression since {change} |
| **Constraints** | No rename / must stay backward compatible / publish deadline |

#### 1.2 Triage Decision Gate

| Question | If YES | If NO |
|:---|:---|:---|
| Is this a safety/boundary issue (`D10`, `P0`)? | Skip to Phase 5 hotfix lane; flag `RULES.md` | Continue |
| Is the Soul concept itself wrong for the user? | Hand off — not repair | Continue |
| Is >60% of content generic fluff (`D6`)? | Consider rewrite path (§4.2) | Patch viable |
| Did audit not run and scope is unclear? | Stack `module-audit` | Continue |

#### 1.3 Triage Output Template

```markdown
## Triage Summary
- **ID**: REPAIR-{YYYYMMDD}-{short-slug}
- **Severity**: P0 | P1 | P2 | P3 | P4
- **Defect class**: D1–D12 (primary), secondary if any
- **Scope**: {file list or "TBD after scout"}
- **Strategy preview**: patch | cross-patch | rewrite-section | split | merge | deprecate
- **Blocked on**: {nothing | user decision | audit completion}
```

---

### Phase 2: Scout — Repository Reconnaissance

**Goal**: Build a **Soul Topology Map** before editing a single line.

#### 2.1 Mandatory Inventory

| Asset | Action |
|:---|:---|
| All `*.md` in Soul root | List with line counts |
| `skills/` directory | Enumerate; note stubs (<80 lines) and giants (>800 lines) |
| `references/` directory | Same |
| `prompts/` | Check placeholder residue (`{{TODO}}`, `lorem`, `TBD`) |
| `SKILLS-MANIFEST.md` | Extract registered IDs vs filesystem |
| `SKILL.md` | Extract paths `M0–M9`, trigger lists, load rules |
| Cross-references | Grep for `See `, `§`, `.md`, backtick paths |

#### 2.2 Topology Map Template

| Path | Manifest ID | Registered | Line Count | Inbound Refs | Outbound Refs | Health Flag |
|:---|:---|:---|:---|:---|:---|:---|
| `SOUL.md` | `CORE-SOUL` | ✅ | 142 | 6 | 2 | OK |
| `skills/xxx.md` | `SKILL-XXX` | ❌ missing | 45 | 0 | 1 | `D8` `D11` |

**Health flags**: OK · WARN · BROKEN · ORPHAN · DUPLICATE

#### 2.3 Scout Commands (Adapt to Environment)

```bash
# File inventory
find . -name '*.md' -not -path './.git/*' | sort

# Manifest vs disk
diff <(grep -oE 'skills/[^`)]+|references/[^`)]+' SKILLS-MANIFEST.md | sort -u) \
     <(find skills references -name '*.md' 2>/dev/null | sort)

# Cross-reference scan
rg -n '\.md`|See |skills/|references/' --glob '*.md'

# Trigger collision scan
rg -n 'Trigger|触发|強觸發|Strong Trigger' SKILLS-MANIFEST.md skills/
```

---

### Phase 3: Diagnose — Root Cause, Not Complaint

**Goal**: Produce a **Causal Chain** linking symptom → mechanism → root cause → affected modules.

#### 3.1 Diagnostic Questions (Answer All Applicable)

| # | Question | Evidence Required |
|:---|:---|:---|
| Q1 | What exact user input fails? | Reproduction phrase or task |
| Q2 | Which module *should* have loaded? | `SKILL.md` routing table row |
| Q3 | Which module *actually* dominates? | Trigger overlap analysis |
| Q4 | Is there a direct textual contradiction? | Side-by-side quotes + line refs |
| Q5 | When did manifest last match filesystem? | Git history if available |
| Q6 | Did a recent edit introduce regression? | Diff / user statement |
| Q7 | Is the module structurally valid per anatomy spec? | Section checklist §5 |
| Q8 | Does `RULES.md` forbid what the module commands? | Rule ID + violating instruction |

#### 3.2 Root Cause Statement Format

> **Because** `{mechanism}` (e.g., duplicate trigger "refactor" in both `skill-a` and `skill-b` with equal priority),  
> **when** `{condition}` (user says "refactor my Soul module"),  
> **the Soul** `{failure}` (loads `skill-b` integration path instead of `skill-refactor`),  
> **causing** `{symptom}` (user receives API design advice instead of module surgery).

If root cause cannot be stated in this form → **return to Scout** or request more context (max 3 questions).

#### 3.3 Contradiction Severity Rubric

| Level | Example | Action |
|:---|:---|:---|
| **Hard** | `RULES.md` forbids X; skill requires X | P0 — fix before any other work |
| **Soft** | `STYLE.md` says brief; reference module is verbose | P2 — harmonize on next touch |
| **Apparent** | Same rule, different wording | Normalize vocabulary via `references/vocabulary.md` |
| **Temporal** | Old module references deprecated workflow | `D3` reference rot patch |

---

### Phase 4: Plan — Choose Repair Strategy

**Goal**: Select the **smallest intervention** that fully resolves the causal chain.

#### 4.1 Strategy Decision Tree

```
Symptom identified
    │
    ├─ P0 boundary/identity? ──YES──► Hotfix lane (§4.4)
    │
    ├─ Single file, localized D5/D6/D8? ──YES──► Module-local patch (§5)
    │
    ├─ D2 contradiction across 2 files? ──YES──► Cross-patch (§6)
    │
    ├─ D1/D4/D11 orchestration? ──YES──► Orchestration repair (§7)
    │
    ├─ D7 bloat OR D8 starvation? ──YES──► Split / merge / rewrite-section (§4.2)
    │
    ├─ D12 trigger collision? ──YES──► Trigger arbitration (§6.4)
    │
    └─ Multiple P1+ across ≥4 files? ──YES──► Audit-first + phased repair plan
```

#### 4.2 Strategy Selection Matrix

| Strategy | When | Risk | Approval |
|:---|:---|:---|:---|
| **Patch** | Single defect, clear fix, <80 lines changed | Low | Maintainer discretion |
| **Cross-patch** | `D2` across 2–3 files | Medium | Document both sides |
| **Rewrite-section** | One section `D6` but rest salvageable | Medium | Preserve § anchors |
| **Rewrite-module** | >50% content generic or wrong paradigm | High | User confirm if identity-adjacent |
| **Split** | `D7` god-skill | High | Update manifest + routing |
| **Merge** | `D8` stubs with overlapping scope | Medium | Deprecate loser ID |
| **Deprecate** | Obsolete skill; superseded | Low | Redirect triggers + changelog |
| **Hotfix** | `P0` publish blocker | High velocity | Verify immediately after |

#### 4.3 Repair Plan Document (Required for P1+)

```markdown
## Repair Plan: REPAIR-{id}

### Root Cause
{one paragraph causal chain}

### Strategy
{patch | cross-patch | ...}

### Files Touched (ordered)
1. `RULES.md` — {why first}
2. `skills/foo.md` — {change summary}
3. `SKILLS-MANIFEST.md` — {registry updates}

### Explicit Non-Goals
- Will NOT rename Soul title
- Will NOT add new skills

### Verification Scenarios
1. User says "{phrase}" → loads `{module}`
2. `{module}` does not contradict `RULES.md` rule {id}

### Rollback
{git revert hash | backup path}
```

#### 4.4 Hotfix Lane (P0 Only)

1. Neutralize harmful instruction **first** (delete or comment with `<!-- HOTFIX: reason -->` only if format allows)
2. Patch `RULES.md` reinforcement if gap exposed
3. Run abbreviated verify (§8.1 P0 checklist)
4. Schedule full protocol within same maintenance cycle

---

### Phase 5: Repair — Execute With Diff Discipline

**Goal**: Apply planned changes with **traceable, reviewable** edits.

#### 5.1 Global Edit Rules

| Rule | Detail |
|:---|:---|
| **Anchor preservation** | Keep `##` section IDs stable when other modules link to them |
| **Trigger hygiene** | Add/remove triggers in **three places**: module header, `SKILL.md` index, `SKILLS-MANIFEST.md` |
| **Voice lock** | Re-read `SOUL.md` + `STYLE.md` before writing >20 lines |
| **Example-or-delete** | Every repaired section must have ≥1 concrete example or checklist |
| **No new fluff** | If a paragraph doesn't change behavior, it doesn't belong |
| **Cross-ref format** | Use `` `path/to/file.md` `` and `§section` consistently |

#### 5.2 Per-File-Type Playbooks

##### `SOUL.md` Repairs

| Defect | Repair Action | Caution |
|:---|:---|:---|
| Identity drift (`D9`) | Re-align mission statement to evidenced user failures | Don't rewrite personality on taste |
| Missing target user | Add § with 2–3 concrete user personas | Must match `SKILL.md` modes |
| Bloated history | Compress anecdotes to bullet proof points | Keep at least 3 "war stories" |

##### `STYLE.md` Repairs

| Defect | Repair Action |
|:---|:---|
| Contradicts module output format | Pick one canonical format table; modules reference it |
| Missing expertise-level adaptation | Add Beginner / Practitioner / Maintainer matrix |
| Ambiguous language rules | Resolve bilingual policy explicitly |

##### `RULES.md` Repairs

| Defect | Repair Action |
|:---|:---|
| Rule not enforced in skills | Add matching MUST/MUST NOT in offending skill |
| Rule too vague to enforce | Add rule ID + testable violation example |
| Overlapping prohibitions | Merge; dedupe IDs |

##### `SKILL.md` Repairs

| Defect | Repair Action |
|:---|:---|
| Broken path routing | Fix `M*` mapping table; add missing path |
| Step 0 module loader incomplete | Sync with manifest registry |
| Missing response modes | Add mode + when-to-use + output diff |
| Stale activation triggers | Diff against manifest global index |

##### `SKILLS-MANIFEST.md` Repairs

| Defect | Repair Action |
|:---|:---|
| Missing file entry | Add row: ID, path, purpose, triggers, load rule |
| Orphan registry entry | Remove or restore file |
| Wrong default load flags | Fix ✅/⚡/path legend consistency |
| Broken dependency graph | Update § module dependency graph |

##### `skills/*.md` Repairs

| Defect | Repair Action |
|:---|:---|
| `D5` missing sections | Insert: Triggers, Workflow, Pitfalls, Integration (§5.3) |
| `D6` quality decay | Replace fluff with decision table + IO example |
| `D7` bloat | Extract reference material to `references/`; leave executable SOP |
| `D8` starvation | Expand to minimum viable skill (§5.3) or merge |
| `D12` trigger overlap | Narrow triggers; add anti-triggers |

##### `references/*.md` Repairs

| Defect | Repair Action |
|:---|:---|
| Stale framework | Date-stamp "Last validated"; update tables |
| Executable steps in reference | Move SOP to `skills/`; leave principles |
| No quick lookup | Add summary table at top |

#### 5.3 Minimum Viable Pluggable Skill Template

Every repaired `skills/*.md` MUST contain at minimum:

1. **Module header block** (ID, path, paths, dependencies)
2. **§0 Charter** — what it solves + iron laws
3. **§1 Triggers** — strong / weak / anti-triggers
4. **§2+ Workflow** — numbered phases with decision tables
5. **§ Pitfalls** — ≥5 rows
6. **§ Integration** — explicit handoffs to other modules
7. **§ IO Examples** — ≥1 before/after repair narrative
8. **§ Completion Checklist**

#### 5.4 Cross-Patch Protocol (`D2`)

When two modules contradict:

1. **Identify authority hierarchy** (default):

   ```
   RULES.md > SOUL.md identity boundaries > SKILL.md routing > skills/* > references/* > STYLE.md formatting
   ```

2. Quote both conflicting assertions with paths
3. Modify **lower-authority** module unless `RULES.md` itself is wrong
4. If `RULES.md` is wrong → fix rule **and** scan all modules citing old rule ID
5. Add reconciliation note in repair report

---

### Phase 6: Verify — Regression Gate

**Goal**: Prove the Soul **behaves correctly** after repair, not just "reads nicer."

#### 6.1 Verification Layers

| Layer | Test | Pass Criteria |
|:---|:---|:---|
| **L1 Structural** | Manifest ↔ filesystem | Zero orphans either direction |
| **L2 Reference** | All `*.md` paths resolve | 100% valid |
| **L3 Trigger** | 5 canonical user phrases (from plan) | Correct module routing |
| **L4 Contradiction** | Pairwise scan RULES vs skills | Zero hard contradictions |
| **L5 Identity** | Sample output mental sim | Matches SOUL voice + STYLE format |
| **L6 Integration** | Multi-skill scenario | Correct stacking order |

#### 6.2 Trigger Simulation Table (Fill Per Repair)

| # | User Input | Expected Load Order | Expected Mode | Pass |
|:---|:---|:---|:---|:---|
| 1 | "repair broken skill module" | CORE-* → SKILL → module-repair | M3 Standard | ☐ |
| 2 | "audit then fix manifest" | CORE-* → module-audit → module-repair | M1→M3 | ☐ |
| 3 | `{custom}` | | | ☐ |

#### 6.3 Anti-Regression Checks

- [ ] No new triggers added without manifest entry
- [ ] No RULES violations introduced
- [ ] `SKILL.md` Step 0 still lists all skills
- [ ] Section anchors referenced elsewhere still exist
- [ ] Primary language consistent across touched files
- [ ] Line count change justified in repair report

#### 6.4 Trigger Arbitration (for `D12`)

| Step | Action |
|:---|:---|
| 1 | List colliding triggers across skills |
| 2 | Assign **exclusive ownership** — one primary skill per trigger |
| 3 | Demote others to weak triggers with extra context requirements |
| 4 | Add anti-triggers where ambiguity remains |
| 5 | Update `SKILLS-MANIFEST.md` global trigger index |

**Priority formula** when ownership disputed:

```
specificity score (phrase length + domain terms)
+ path match (user names file/module)
+ manifest declared primary
− generality (single-word triggers lose)
```

---

### Phase 7: Record — Institutional Memory

**Goal**: Future maintainers understand **what changed and why**.

#### 7.1 Repair Report Template (Deliver to User)

```markdown
# Module Repair Report — REPAIR-{id}

## Summary
{1–2 sentences}

## Root Cause
{causal chain}

## Changes
| File | Change Type | Lines ± | Notes |
|:---|:---|:---|:---|
| `skills/foo.md` | patch | +24 / -31 | Added anti-triggers |

## Verification
{Trigger simulation results}

## Prevention
{What process/gate would have caught this earlier}

## Follow-ups
| Item | Owner | Priority |
|:---|:---|:---|
| Split `god-skill.md` | Maintainer | P3 |
```

#### 7.2 Changelog Entry (If Soul Versioned)

```markdown
### [{version}] — {date}
**Fixed** ({module}): {user-visible outcome, not internal diff stats}
**Registry**: {manifest IDs added/removed/renamed}
```

---

## 4. Input / Output Examples

### Example A — Trigger Collision (`D12` / `D1`)

**Input (user)**:
> "When I ask to refactor a skill file, the Soul gives me Python refactoring advice instead of Soul module surgery."

**Diagnosis**:
- `SKILL.md` path `M3` and Python-dev path `P3` both claim trigger `refactor`
- `skills/refactor-surgery.md` (wrong Soul) or misloaded overlap

**Repair actions**:
1. Narrow Python triggers to `refactor code`, `refactor function`
2. Add Soul triggers: `refactor module`, `refactor skill`, `split skill`
3. Update `SKILLS-MANIFEST.md` global index
4. Add anti-trigger in wrong module: "If context is Soul `.md` files → not this module"

**Output (excerpt)**:
> **Fixed trigger routing.** `refactor` alone is no longer a strong trigger for code refactoring. Soul module work now requires `module`, `skill`, or `soul` in the phrase. Verified 5 simulation phrases — all route to `skills/module-repair.md` or `skills/module-decomposition.md`.

---

### Example B — Manifest Desync (`D11`)

**Input (audit finding)**:
> `skills/integration-validation.md` exists (312 lines) but is absent from `SKILLS-MANIFEST.md`.

**Repair actions**:
1. Add registry row with ID `SKILL-INTEGRATION`, triggers, load rules
2. Add entry to `SKILL.md` Step 0 conditional loader
3. Add cross-ref from `module-repair.md` §1.4 (already references it)

**Output**:
> Registry synchronized. Integration validation is now discoverable via triggers `validate integration`, `cross-module check`, `soul regression`.

---

### Example C — Quality Decay (`D6`)

**Input (user)**:
> "My `skills/api-design.md` is 40 lines of generic 'be clear and consistent' advice. Fix it."

**Diagnosis**: `D6` + `D8` starvation — not pluggable

**Strategy**: `rewrite-section` (not full Soul rewrite)

**Repair actions**:
1. Preserve module ID and triggers
2. Insert decision framework: REST vs GraphQL vs gRPC
3. Add workflow phases, IO example, pitfalls
4. Move principle essay to `references/api-principles.md` if needed

**Output**:
> Expanded to production-grade pluggable skill (§5.3 compliant). Generic principles relocated to reference file. Triggers unchanged for backward compatibility.

---

### Example D — Hard Contradiction (`D2` / `P0`)

**Input**:
> "`RULES.md` says never invent file paths, but `skills/debug-mastery.md` tells the agent to cite hypothetical `src/foo.py`."

**Repair actions** (cross-patch):
1. **Authority**: `RULES.md` wins
2. Patch skill: "cite only paths confirmed via repo scout; use placeholders only in templates marked as hypothetical"
3. Add violation example to `RULES.md` rule entry for clarity

**Output**:
> P0 contradiction resolved. Skill now explicitly requires repo recon before path citation. RULES R-{id} clarified with Soul-specific example.

---

## 5. Common Pitfalls

| # | Pitfall | Why It Hurts | Prevention |
|:---|:---|:---|:---|
| P1 | **Symptom chasing** | Fix wording; routing still broken | Require causal chain before edit |
| P2 | **Manifest afterthought** | Skill exists but never loads | Registry update is part of definition of done |
| P3 | **Repair as redesign** | Scope explosion; user didn't ask | Enforce §4.3 non-goals |
| P4 | **Trigger inflation** | `D12` noise gets worse | Every new trigger removes or narrows one |
| P5 | **God file absorption** | `D7` returns in 2 months | Split reference vs executable SOP |
| P6 | **Voice remix** | Soul feels like different author | Read SOUL + STYLE before writing |
| P7 | **Orphan anchors** | Links break silently | Grep inbound refs before renaming § |
| P8 | **Fluff replacement** | Longer but still not actionable | Require table OR checklist OR IO example per § |
| P9 | **Single-file verify** | Cross-patch incomplete | Mandatory L4 contradiction scan |
| P10 | **Implicit deprecation** | Users follow dead skill | Formal deprecate + redirect triggers |
| P11 | **Bilingual drift** | HK Chinese + English rules diverge | One primary language per generation; terms in English |
| P12 | **Copy-paste from other Soul** | Identity contamination | Grep foreign persona names |

### Do's & Don'ts

| Do | Don't |
|:---|:---|
| Produce repair plan for P1+ | Edit files "while reading" without plan |
| Quote line-level evidence in reports | Say "cleaned up the module" |
| Fix orchestration in `SKILL.md` + manifest together | Patch skill triggers only |
| Use smallest strategy that resolves causal chain | Default to full rewrite |
| Run trigger simulation table | Assume routing works because text "looks right" |
| Document prevention recommendations | Close ticket without institutional memory |

---

## 6. Integration With Other Soul Modules

### 6.1 Upstream (Loads Before This Module)

| Module | Provides |
|:---|:---|
| `SOUL.md` | Identity lock — repairs must not drift persona |
| `RULES.md` | Non-negotiable boundaries for patch content |
| `SKILL.md` | Entry routing; repair path `M3` declaration |
| `SKILLS-MANIFEST.md` | Registry truth for scoping |

### 6.2 Parallel / Sequential Partners

| Module | Relationship |
|:---|:---|
| `skills/module-audit.md` | **Before** repair when scope unknown or multi-P1 |
| `skills/integration-validation.md` | **After** repair when ≥2 files or manifest changed |
| `skills/module-decomposition.md` | **Instead of** repair when `D7` needs split not patch |
| `references/soul-anatomy.md` | Structural validity checklist |
| `references/quality-gates.md` | Production readiness criteria |
| `references/versioning-sop.md` | Version bump + publish after repair |

### 6.3 Downstream Handoffs

| Condition | Hand Off To |
|:---|:---|
| Repair reveals Soul concept mismatch | Soul redesign / author consult |
| User requests publish after repair | `M6` publishing workflow |
| Repeated same `D*` on same module | Long-term maintainability review |
| New skill needed (not fixable) | `M0` authoring + manifest registration |

### 6.4 Module Interaction Diagram

```
                    ┌─────────────────┐
                    │    SOUL.md      │
                    │  (identity)     │
                    └────────┬────────┘
                             │
         ┌───────────────────┼───────────────────┐
         ▼                   ▼                   ▼
   ┌──────────┐        ┌──────────┐        ┌──────────┐
   │ RULES.md │        │ STYLE.md │        │ SKILL.md │
   └────┬─────┘        └──────────┘        └────┬─────┘
        │                                       │
        │         ┌─────────────────────────────┤
        │         ▼                             ▼
        │  ┌──────────────┐            ┌──────────────────┐
        └──│ module-audit │──findings─►│ module-repair    │
           └──────────────┘            │  (THIS MODULE)   │
                                        └────────┬─────────┘
                                                 │
                    ┌────────────────────────────┼────────────────────────┐
                    ▼                            ▼                        ▼
           ┌────────────────┐        ┌─────────────────┐      ┌─────────────────┐
           │ SKILLS-MANIFEST│◄───────│ patched skills/ │─────►│ integration-    │
           │    (registry)  │        │   references/   │      │ validation      │
           └────────────────┘        └─────────────────┘      └─────────────────┘
```

---

## 7. Quick Reference — Repair Selector Card

| User Says / Signal | Defect | First File to Open | Strategy |
|:---|:---|:---|:---|
| "Wrong skill loads" | `D1` `D4` | `SKILL.md` | Orchestration |
| "Contradicts itself" | `D2` | Quote both files | Cross-patch |
| "Link broken" | `D3` | Target + inbound refs | Patch |
| "Too generic" | `D6` | Offending skill | Rewrite-section |
| "File too long" | `D7` | God-skill | Split |
| "Skill stub" | `D8` | Stub file | Expand or merge |
| "Tone feels off" | `D9` | `SOUL.md` + offender | Cross-patch |
| "Unsafe instruction" | `D10` | `RULES.md` | Hotfix |
| "Not in manifest" | `D11` | `SKILLS-MANIFEST.md` | Registry sync |
| "Ambiguous trigger" | `D12` | Manifest trigger index | Arbitration |

---

## 8. Repair Completion Checklist

### 8.1 P0 Gate (All Required)

- [ ] No `RULES.md` violations remain in touched files
- [ ] Harmful instructions neutralized
- [ ] Abbreviated trigger sim (≥3 cases) passed

### 8.2 Standard Gate (P1–P3)

- [ ] Triage summary documented
- [ ] Root cause stated in causal chain format
- [ ] Repair plan followed (or deviation explained)
- [ ] Manifest synchronized with filesystem
- [ ] `SKILL.md` routing updated if triggers changed
- [ ] L1–L4 verification passed
- [ ] Repair report delivered (§7.1)
- [ ] Prevention recommendation included
- [ ] Follow-ups logged with priority

### 8.3 Quality Gate (Production-Grade Module)

- [ ] Every touched `skills/*.md` meets §5.3 minimum structure
- [ ] No paragraph without behavioral effect
- [ ] ≥1 decision table or checklist per major workflow phase
- [ ] Integration § lists explicit handoffs
- [ ] Pitfalls table ≥5 rows

---

## 9. Glossary (Maintenance Engineer)

| Term | Definition |
|:---|:---|
| **Pluggable skill** | `skills/*.md` module invocable via triggers without reloading entire Soul |
| **Cross-patch** | Coordinated edits across multiple modules to resolve one causal chain |
| **Registry** | `SKILLS-MANIFEST.md` authoritative index |
| **Trigger arbitration** | Resolving competing keyword ownership between skills |
| **Topology map** | Filesystem + manifest + cross-ref graph from Scout phase |
| **Identity drift** | Module voice diverges from `SOUL.md` without intentional evolution |
| **Orchestration** | `SKILL.md` module loading and path routing logic |
| **Hotfix lane** | Accelerated P0 repair path with abbreviated verify |

---

*End of `skills/module-repair.md` — nanoclaw Modular Soul Maintenance Engineer*