---
name: gmd:resolve-gap
description: Resolve a detected workflow gap by authoring, testing, and promoting a new skill. User-invoked only.
argument-hint: "[gap-id]"
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Glob
  - Grep
  - Task
---

<objective>
Orchestrate the full gap resolution lifecycle: select gap from GAPS.md, author a skill to .drafted/, validate via /gmd:test-skill adversarial testing, get user approval, promote with atomic git commit and tag, update SKILLS.md and GAPS.md registries. Supports rollback via `--rollback {skill-name}`.

Requirements satisfied: EVOLVE-01 (skill authoring), EVOLVE-04 (automatic creation pipeline), EVOLVE-05 (lifecycle with rollback).
</objective>

## Hard Constraints

- Only **utility** and **reference** skills can be auto-authored. Behavioral skills require human authoring.
- **Single-file skills only.** Each skill is a single SKILL.md -- no supporting files (templates, patterns, references).
- **User approval required before promotion.** The skill must pass adversarial testing AND receive explicit user confirmation.
- **Flat orchestration:** the only Task tool usage in this command is dispatching `/gmd:test-skill`. No nested subagents beyond that single level.

## Rollback Mode

When invoked as `/gmd:resolve-gap --rollback {skill-name}`:

1. Find existing git tags matching `skill/{skill-name}/v*`
2. Determine the current (latest) and previous version tags
3. If no previous version exists, inform the user: "No previous version exists for {skill-name}. Remove the skill manually if needed." and STOP.
4. Restore the previous version:
   ```bash
   git show "{prev-tag}:skills/{skill-name}/SKILL.md" > "skills/{skill-name}/SKILL.md"
   ```
5. Update `.planning/SKILLS.md`: change the skill's status to `rolled-back`
6. Commit the rollback:
   ```bash
   git add "skills/{skill-name}/SKILL.md" ".planning/SKILLS.md"
   git commit -m "fix(skill): rollback {skill-name} to {prev-tag}"
   ```
7. Inform the user: "Rolled back {skill-name} to {prev-tag}."

If `--rollback` is NOT present, proceed with the full resolution pipeline below.

---

## Step 1: Select Gap

1. Read `.planning/GAPS.md`
2. If a `gap-id` argument was provided (e.g., `GAP-003`), locate that gap entry.
   - If the gap does not exist or is not status `open`, inform the user and STOP.
3. If no `gap-id` argument was provided, list all open gaps (ID, severity, description) and ask the user to select one.
4. If no open gaps exist, inform the user: "No open gaps found in GAPS.md. Nothing to resolve." and STOP.
5. Display the selected gap's full details: ID, agent, trigger, severity, description, suggested-skill name.

## Step 2: Design Skill

1. Read `references/skill-schema.md` to understand the SKILL.md format requirements (frontmatter fields, type enum, tier structure).
2. Based on the gap description and suggested-skill name, design a utility or reference skill.

**Guardrail: Type restriction**
Auto-authored skills are LIMITED to `type: utility` or `type: reference`. If this gap requires a behavioral skill (`discipline: rigid`, iron laws, red flag tables), inform the user:

> "This gap requires a behavioral skill which must be authored manually. See `references/skill-schema.md` for the format."

and STOP.

**Guardrail: Single-file restriction**
Auto-authored skills are LIMITED to single-file SKILL.md. If the gap requires supporting files (templates, patterns, references beyond what fits in one file), inform the user:

> "This gap requires a multi-file skill which must be authored manually."

and STOP.

3. Determine the skill name: use the gap's `suggested-skill` field if present. Otherwise, derive a kebab-case name from the gap description.

## Step 3: Author Skill

1. Create the directory `skills/{skill-name}/.drafted/` if it does not exist.
   - The `.drafted/` subdirectory ensures the SessionStart discovery hook does NOT discover this skill during authoring. The hook only reads `skills/{name}/SKILL.md` at one level deep.
2. Write `skills/{skill-name}/.drafted/SKILL.md` with:
   - Valid YAML frontmatter per `references/skill-schema.md`:
     - `name`: the skill name (kebab-case)
     - `version`: `"0.1.0"` (draft version)
     - `type`: `utility` or `reference` (determined in Step 2)
     - `description`: concise description addressing the gap
     - `tags`: relevant keywords
   - Body content addressing the gap description with:
     - Clear rules and guidance
     - Specific examples where applicable
     - Scope boundaries (what this skill covers and does not cover)
3. The authored skill should directly address the gap's root cause as described in GAPS.md.

## Step 4: Validate via Adversarial Testing

1. Temporarily copy the drafted skill to the expected test location:
   ```bash
   cp "skills/{skill-name}/.drafted/SKILL.md" "skills/{skill-name}/SKILL.md"
   ```
2. Dispatch `/gmd:test-skill {skill-name}` using the Task tool.
   - test-skill spawns 2 subagents: one baseline (no skill) and one with the skill loaded.
   - It returns a structured comparison with PASS/FAIL and behavioral divergence analysis.
3. After test results return, restore the pre-test state:
   ```bash
   rm "skills/{skill-name}/SKILL.md"
   ```
4. Evaluate results:
   - **PASS**: The skill measurably changed agent behavior under adversarial pressure. Proceed to Step 5.
   - **FAIL**: Present the test results and comparison data to the user. Ask:
     > "Adversarial test FAILED -- the skill did not measurably change behavior. Options: [revise] to update the skill and re-test, or [abandon] to discard. Choose one."
     - If **revise**: incorporate test feedback, return to Step 3 with improvements.
     - If **abandon**: clean up the `.drafted/` directory (`rm -rf "skills/{skill-name}/.drafted/"`) and STOP.

## Step 5: User Approval Gate

Present a summary to the user:
- Gap ID and description
- Skill name, type, and version
- Adversarial test result (PASS with key behavioral differences observed)
- Preview of the SKILL.md content (first 30 lines or key sections)

Ask the user:

> "Adversarial test passed. Promote this skill to production? [yes / no / revise]"

- **yes**: Proceed to Step 6.
- **no**: Clean up the `.drafted/` directory and STOP with message: "Skill discarded. Gap remains open."
- **revise**: Return to Step 3 with user's feedback for revisions.

## Step 6: Promote Skill

Execute the following promotion steps atomically:

1. **Move skill to production path:**
   ```bash
   mv "skills/{skill-name}/.drafted/SKILL.md" "skills/{skill-name}/SKILL.md"
   rmdir "skills/{skill-name}/.drafted/"
   ```

2. **Determine version number:**
   Check for existing `skill/{skill-name}/v*` git tags. If none exist, this is `v1`. Otherwise, increment: `max_existing + 1`.

3. **Update `.planning/SKILLS.md`:**
   Add or update a row in the registry table:
   | Name | Type | Status | Version | Origin | Last Validated |
   | {skill-name} | {type} | promoted | v{N} | auto-gap/{GAP-ID} | {today's date} |

4. **Update `.planning/GAPS.md`:**
   Change the gap's status from `open` to `resolved`. Add resolution date.

5. **Archive the resolved gap:**
   Create `.planning/gaps/` directory if it does not exist.
   Write `.planning/gaps/{GAP-ID}.md` with Obsidian-compatible frontmatter:
   ```yaml
   ---
   tags: [gap, resolved]
   resolved_by: skill/{skill-name}
   resolved_date: {today's date}
   gap_id: {GAP-ID}
   severity: {severity}
   ---
   ```
   Include the full gap details (agent, trigger, description) in the body.

6. **Atomic git commit:**
   ```bash
   git add "skills/{skill-name}/SKILL.md" ".planning/SKILLS.md" ".planning/GAPS.md" ".planning/gaps/{GAP-ID}.md"
   git commit -m "feat(skill): promote {skill-name} v{N} from {GAP-ID}"
   ```

7. **Create git tag:**
   ```bash
   git tag "skill/{skill-name}/v{N}" HEAD
   ```

## Step 7: Post-Promotion

After successful promotion, inform the user:

> "Skill `{skill-name}` v{N} promoted from {GAP-ID}."
>
> "To rollback: `/gmd:resolve-gap --rollback {skill-name}`"
>
> "The skill will be discovered by the SessionStart hook on next session. To use it immediately, invoke via the Skill tool: `Skill('{skill-name}')`."

---

## How This Relates to Gap Detection

Gaps are detected automatically during plan execution by two agents:

- **gmd-executor** detects gaps when: (1) the agent encounters a workflow pattern not covered by any existing skill, and (2) the agent has to improvise a workaround that should be codified.
- **gmd-verifier** detects gaps when: (3) verification reveals that an agent's behavior diverged from expected discipline, suggesting a missing or insufficient skill.

Both agents log detected gaps to `.planning/GAPS.md` with severity, trigger context, and a suggested skill name. This command (`/gmd:resolve-gap`) is the user's tool to act on those detected gaps -- turning observations into validated, version-controlled skills.

The full lifecycle: **detect** (automatic, during execution) -> **resolve** (user-invoked, this command) -> **validate** (adversarial, via /gmd:test-skill) -> **promote** (user-approved, with git tag) -> **rollback** (if needed, via --rollback flag).
