config-audit/commands/feature-gap.md
Kjell Tore Guttormsen b85919f2ec fix(commands): close the promises the command templates could not keep
DEL B chunk `interview` (+ discover/status/cleanup/help). Fasit written before
the run predicted 8 defects and refuted 4 candidates; all 8 confirmed, all 4
refutations held, and three predictions turned out too narrow.

- M-BUG-36: `drift --list` reached the command as 0 bytes. drift-cli accepted
  --output-file but list mode ignored it, and the listing goes to stderr, which
  the command discards per ux-rules rule 2. Fixing the caller alone would not
  have helped.
- M-BUG-37: feature-gap's "Create backup" step ran fix-cli without --apply.
  Dry-run is the default, so no backup existed (backupId: null) while the
  command went on to edit config believing it could roll back.
- M-BUG-38: fix-cli told users to recover with scanners/rollback-cli.mjs, which
  does not exist. Dead reference in the one message read after a bad fix.
- M-BUG-21 fourth arm: five templates carried literal [--global]/[--full-machine]
  inside executable bash blocks. A bracketed placeholder does not start with a
  dash, so every scanner's arg loop takes it as the scan target.
- interview and analyze never said which session they act on; interview could
  rewind a finished session; cleanup interpolated an unvalidated id into rm -rf
  (an empty id deletes every session); status advertised a `resume` command that
  does not exist and documented an `all` argument it never parsed.

TDD: 9 red tests first, including a machine sweep for dead /config-audit
references and for bracketed flags in bash blocks. Suite 1432 -> 1441/0.
Frozen v5.0.0 snapshots untouched; --raw/--json contracts unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UGvA1uUQn2hPBPMaCKK6x3
2026-07-31 21:27:07 +02:00

199 lines
8 KiB
Markdown

---
name: config-audit:feature-gap
description: Context-aware feature recommendations — what could enhance your setup and why
argument-hint: "[path]"
allowed-tools: Read, Write, Edit, Glob, Grep, Bash, Agent, AskUserQuestion
model: opus
---
# Config-Audit: Feature Opportunities
Context-aware analysis of Claude Code features that could benefit your specific project — with the option to implement selected recommendations on the spot.
## What the user gets
- Project context detection (language, size, existing configuration)
- Numbered recommendations grouped by impact (high / worth considering / explore)
- Each recommendation backed by evidence (Anthropic docs, proven issues)
- **Interactive selection: "Which would you like to implement?"**
- Direct implementation with backup for selected items
## Implementation
### Step 1: Determine target and flags
Split `$ARGUMENTS` into a path and flags. Path is the first non-flag argument (default: current working directory). Recognized flags:
- `--raw` — pass-through to the scanner; produces v5.0.0 verbatim envelope (bypasses the humanizer). When `--raw` is set, render with v5.0.0 finding-field shape only — humanizer fields are absent in raw output.
Tell the user:
```
## Feature Opportunities
Analyzing which Claude Code features could benefit your workflow...
```
### Step 2: Create session and run posture
Generate session ID (`YYYYMMDD_HHmmss`) if no active session exists.
```bash
mkdir -p ~/.claude/config-audit/sessions/{session-id}/findings 2>/dev/null
RAW_FLAG=""
if echo "$ARGUMENTS" | grep -q -- "--raw"; then RAW_FLAG="--raw"; fi
node ${CLAUDE_PLUGIN_ROOT}/scanners/posture.mjs <target-path> --output-file ~/.claude/config-audit/sessions/{session-id}/posture.json $RAW_FLAG 2>/dev/null; echo $?
```
If exit code is non-zero: "Assessment couldn't run. Check that the path exists and contains configuration files."
### Step 3: Read posture data and detect project context
Read `~/.claude/config-audit/sessions/{session-id}/posture.json` using the Read tool.
Extract GAP findings from `scannerEnvelope.scanners` (find scanner with `scanner === 'GAP'`).
Detect project context:
```bash
test -f <target-path>/package.json && echo "has_package_json" || echo "no_package_json"
ls <target-path>/*.py <target-path>/requirements.txt <target-path>/pyproject.toml 2>/dev/null | head -3
```
### Step 4: Build numbered recommendations
Read `${CLAUDE_PLUGIN_ROOT}/knowledge/gap-closure-templates.md` for implementation templates.
Group GAP findings by their humanized fields rather than re-deriving tier-to-prose mappings. In default mode (no `--raw`) each finding carries:
- `userImpactCategory` (e.g., "Missed opportunity") — the impact bucket
- `userActionLanguage` (e.g., "Fix soon", "Fix when convenient", "Optional cleanup", "FYI") — the urgency phrasing the rest of the toolchain uses
- `relevanceContext` ("affects-everyone" / "affects-this-machine-only" / "test-fixture-no-impact") — the scope so the user knows whether the change touches shared config or just their own machine
Group findings into three sections by `userActionLanguage`: "Fix this now" + "Fix soon" → **High Impact**, "Fix when convenient" → **Worth Considering**, "Optional cleanup" + "FYI" → **Explore When Ready**. Number sequentially across sections. Skip findings whose `relevanceContext === "test-fixture-no-impact"` unless the user explicitly asked to include fixtures.
The humanizer has already replaced jargon-heavy strings with plain-language equivalents in `title`, `description`, and `recommendation` — render those verbatim. Do not paraphrase. Do not introduce inline tier-to-prose tables ("Tier 1 means…"); the categories are pre-translated.
If `--raw` was passed, the v5.0.0 envelope is in effect — humanizer fields are absent. Fall back to grouping by `category` ("t1"/"t2"/"t3"/"t4") and render `title` + `recommendation` directly.
Render shape (default mode):
```markdown
### High Impact
{For each finding where userActionLanguage is "Fix this now" or "Fix soon":}
**{N}.** {title}
→ {description}
→ {recommendation}
→ Effort: {from gap-closure-templates.md}
### Worth Considering
{For each finding where userActionLanguage is "Fix when convenient":}
**{N}.** {title}
→ {description}
→ {recommendation}
### Explore When Ready
{For each finding where userActionLanguage is "Optional cleanup" or "FYI":}
**{N}.** {title}
→ {recommendation}
```
Each recommendation MUST have:
- A number
- The humanizer-provided `title`
- The humanizer-provided `description` (where shown)
- An effort estimate looked up from the templates
### Step 5: Ask what to implement
```
AskUserQuestion:
question: "Which would you like to implement? I'll create a backup first."
options:
- "All high impact (1-2)"
- "Pick specific: e.g. 1,3,5"
- "None — just wanted to see the recommendations"
```
If "None": show the full report location and exit.
If the user picks numbers: parse the selection and proceed to Step 6.
### Step 6: Implement selected recommendations
For each selected recommendation:
1. **Create backup** of any files that will be modified.
Do **not** reach for `fix-cli.mjs` here. It is dry-run by default, so calling
it without `--apply` creates no backup at all and returns `backupId: null`
and calling it *with* `--apply` would execute unrelated auto-fixes that the
user never selected. Copy the files yourself:
```bash
BACKUP_DIR=~/.claude/config-audit/backups/$(date +%Y%m%d_%H%M%S)/files
mkdir -p "$BACKUP_DIR" 2>/dev/null
# repeat per file that will be touched:
cp "<file-to-modify>" "$BACKUP_DIR/" 2>/dev/null; echo $?
```
Tell the user where the copies landed. These are plain file copies — they are
restored by copying them back, **not** by `/config-audit rollback`, which only
knows about backups written by `fix` and `implement`.
2. **Apply the template** from gap-closure-templates.md. Use the Write or Edit tool to create or modify the relevant configuration file.
3. **Show progress** as each item is done:
```
Implementing 3 recommendations...
✓ 1. permissions.deny — added to .claude/settings.json
✓ 3. Modular CLAUDE.md — created .claude/rules/testing.md, added @import
✓ 5. Keybindings — created ~/.claude/keybindings.json
```
4. **Verify** by re-running posture:
```bash
node ${CLAUDE_PLUGIN_ROOT}/scanners/posture.mjs <target-path> --json --output-file /tmp/config-audit-verify-$$.json 2>/dev/null
```
### Step 7: Show results
```markdown
### Done
**{N} recommendations implemented** | Backup created
{If health grade changed:}
Health: {old_grade} → {new_grade} (+{delta} points)
{Show remaining opportunities if any:}
{remaining} more opportunities available — run `/config-audit feature-gap` again anytime.
**Rollback:** If anything looks wrong, run `/config-audit rollback` to restore.
```
## Implementation Guidelines
When implementing recommendations, be smart about context:
- **permissions.deny**: Look at the project for common sensitive paths (`.env`, `secrets/`, `.git/config`, `*.pem`). Don't just copy a template blindly — check what actually exists.
- **hooks**: Start with a simple, useful hook. Don't scaffold 5 hooks at once.
- **path-scoped rules**: Look at the project's file structure to determine meaningful scopes (e.g., `tests/**/*.ts` vs `src/**/*.ts`).
- **CLAUDE.md modularization**: Only suggest splitting if the file is over 100 lines. Read it first to find natural section boundaries.
- **MCP setup**: Only relevant if the user actually has external tools to connect. Ask before creating.
- **Custom plugin**: Too complex for inline implementation — suggest `/config-audit plan` instead.
For items that genuinely need user input (e.g., "which MCP servers do you use?"), ask briefly during implementation rather than skipping them.
## Safety
- **Backup mandatory** — always create before modifying
- **Show what's changing** — the user sees each change as it happens
- **Rollback available** — `/config-audit rollback` at any time
- **Non-destructive** — only create new files or add to existing; never delete content