config-audit/commands/discover.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

148 lines
5.3 KiB
Markdown

---
name: config-audit:discover
description: Phase 1 - Initialize session, auto-detect scope, and discover config files
argument-hint: "[current|repo|home|full] [--delta]"
allowed-tools: Read, Write, Edit, Glob, Grep, Agent, AskUserQuestion, Bash
model: opus
---
# Config-Audit: Discover (Phase 1)
Initialize a new audit session and discover all Claude Code configuration files.
## Usage
```
/config-audit discover # Auto-detect scope
/config-audit discover current # Force current directory scope
/config-audit discover repo # Force git repository scope
/config-audit discover home # Force home/global scope
/config-audit discover full # Force full machine scope
/config-audit discover --delta # Incremental re-scan (changed files only)
```
## Implementation
### Step 1: Initialize session and greet
Generate session ID (`YYYYMMDD_HHmmss`), create directories:
```bash
mkdir -p ~/.claude/config-audit/sessions/{session-id}/findings 2>/dev/null
```
### Step 2: Determine scope
If the user provided a scope argument, use it. Otherwise, auto-detect:
1. Run `git rev-parse --show-toplevel 2>/dev/null`
2. If inside a git repo → **repo** scope
3. If pwd is `$HOME`**home** scope
4. Otherwise → **current** directory scope
Tell the user:
```
## Configuration Discovery
**Scope:** {Repository|Home|Current directory|Full machine} — `{path}`
Finding all Claude Code configuration files (CLAUDE.md, settings, hooks, rules, MCP servers)...
```
### Step 3: Resolve paths
| Scope | What gets scanned |
|-------|-------------------|
| `current` | Current directory + parent CLAUDE.md files up to root + `~/.claude/` |
| `repo` | Git repo root + `~/.claude/` |
| `home` | `~/.claude/` only |
| `full` | `~/.claude/` (depth 10), managed paths, all dev dirs under $HOME |
### Step 4: Delta mode (if --delta)
If `--delta` flag:
1. Find previous baseline from `~/.claude/config-audit/sessions/*/discovery.json`
2. If no previous: "No previous scan found. Running full discovery instead."
3. Compare file mtimes/sizes to classify as changed/new/deleted/unchanged
4. Only scan changed + new files
### Step 5: Run discovery
Run the scan orchestrator silently to discover and scan files. Default mode emits humanized JSON — each finding in `scan-results.json` carries `userImpactCategory`, `userActionLanguage`, and `relevanceContext` alongside the v5.0.0 fields. Pass `--raw` through if the user requested it (produces v5.0.0 verbatim envelope; humanizer fields absent).
```bash
RAW_FLAG=""
if echo "$ARGUMENTS" | grep -q -- "--raw"; then RAW_FLAG="--raw"; fi
# Set to the flag itself for full/home scope, otherwise leave empty. Never pass
# a placeholder wrapped in square brackets: it does not start with a dash, so
# the orchestrator's arg loop takes it as the SCAN TARGET and silently scans a
# path that does not exist.
SCOPE_FLAGS="" # e.g. SCOPE_FLAGS="--full-machine" or SCOPE_FLAGS="--global"
node ${CLAUDE_PLUGIN_ROOT}/scanners/scan-orchestrator.mjs <target-path> --output-file ~/.claude/config-audit/sessions/{session-id}/findings/scan-results.json $SCOPE_FLAGS $RAW_FLAG 2>/dev/null; echo $?
```
Check exit code: 0/1/2 → normal. 3 → "Discovery encountered an error. Try a narrower scope."
### Step 6: Save scope and state
Write `scope.yaml` and `state.yaml` to session directory. Update state with `current_phase: "discover"`, `next_phase: "analyze"`.
### Step 7: Present summary
Read the scan results file using the Read tool. When you surface initial findings, group them by `userImpactCategory` and lead each line with `userActionLanguage` rather than raw severity prefiks — the humanizer already mapped severity to plain-language phrasing ("Fix this now", "Fix soon", "Fix when convenient", "Optional cleanup", "FYI") so the rest of the toolchain sees consistent wording.
**Full scan:**
```markdown
### Discovery Complete
**{scope_type}** scope — found {total_files} configuration files:
| Type | Count |
|------|-------|
| CLAUDE.md | {n} |
| Settings | {n} |
| MCP configs | {n} |
| Rules | {n} |
| Hooks | {n} |
| Other | {n} |
Initial scan found {finding_count} items to review (grouped by impact: {comma-separated counts per userImpactCategory}).
**Next:** Run `/config-audit analyze` to generate your analysis report.
```
**Delta scan:**
```markdown
### Delta Discovery Complete
Compared against baseline from {previous-session-id}:
| Status | Files |
|--------|-------|
| Changed | {n} |
| New | {n} |
| Deleted | {n} |
| Unchanged | {n} |
Only {changed+new} file(s) scanned (vs {total} full scan).
**Next:** Run `/config-audit analyze` to generate your analysis report.
```
## Config File Patterns
| Pattern | Description |
|---------|-------------|
| `**/CLAUDE.md` | Project instructions |
| `**/CLAUDE.local.md` | Local overrides |
| `**/.claude/settings.json` | Project settings |
| `**/.mcp.json` | MCP servers |
| `**/.claude/rules/*.md` | Modular rules |
For global: `~/.claude/CLAUDE.md`, `~/.claude/settings.json`, `~/.claude.json`, `~/.claude/agents/*.md`
## Error Handling
- If scanner fails, report to user in plain language and suggest narrower scope
- If path doesn't exist, tell user and suggest alternatives
- If git command fails for `repo` scope, silently fall back to `current`
- If no config files found, explain: "No Claude Code configuration files found. Start with `/config-audit feature-gap` to see what's recommended."