---
name: issue:discover-by-prompt
description: Discover issues from user prompt with Gemini-planned iterative multi-agent exploration. Uses ACE semantic search for context gathering and supports cross-module comparison (e.g., frontend vs backend API contracts).
argument-hint: "[-y|--yes] <prompt> [--scope=src/**] [--depth=standard|deep] [--max-iterations=5]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Task(*), AskUserQuestion(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*), mcp__exa__search(*)
---

## Auto Mode

When `--yes` or `-y`: Auto-continue all iterations, skip confirmations.

# Issue Discovery by Prompt

## Quick Start

```bash
# Discover issues based on user description
/issue:discover-by-prompt "Check if frontend API calls match backend implementations"

# Compare specific modules
/issue:discover-by-prompt "Verify auth flow consistency between mobile and web clients" --scope=src/auth/**,src/mobile/**

# Deep exploration with more iterations
/issue:discover-by-prompt "Find all places where error handling is inconsistent" --depth=deep --max-iterations=8

# Focused backend-frontend contract check
/issue:discover-by-prompt "Compare REST API definitions with frontend fetch calls"
```

**Core Difference from `/issue:discover`**:
- `discover`: Pre-defined perspectives (bug, security, etc.), parallel execution
- `discover-by-prompt`: User-driven prompt, Gemini-planned strategy, iterative exploration

## What & Why

### Core Concept

Prompt-driven issue discovery with intelligent planning. Instead of fixed perspectives, this command:

1. **Analyzes user intent** via Gemini to understand what to find
2. **Plans exploration strategy** dynamically based on codebase structure
3. **Executes iterative multi-agent exploration** with feedback loops
4. **Performs cross-module comparison** when detecting comparison intent

### Value Proposition

1. **Natural Language Input**: Describe what you want to find, not how to find it
2. **Intelligent Planning**: Gemini designs optimal exploration strategy
3. **Iterative Refinement**: Each round builds on previous discoveries
4. **Cross-Module Analysis**: Compare frontend/backend, mobile/web, old/new implementations
5. **Adaptive Exploration**: Adjusts direction based on findings

### Use Cases

| Scenario | Example Prompt |
|----------|----------------|
| API Contract | "Check if frontend calls match backend endpoints" |
| Error Handling | "Find inconsistent error handling patterns" |
| Migration Gap | "Compare old auth with new auth implementation" |
| Feature Parity | "Verify mobile has all web features" |
| Schema Drift | "Check if TypeScript types match API responses" |
| Integration | "Find mismatches between service A and service B" |

## How It Works

### Execution Flow

```
Phase 1: Prompt Analysis & Initialization
   ├─ Parse user prompt and flags
   ├─ Detect exploration intent (comparison/search/verification)
   └─ Initialize discovery session

Phase 1.5: ACE Context Gathering
   ├─ Use ACE semantic search to understand codebase structure
   ├─ Identify relevant modules based on prompt keywords
   ├─ Collect architecture context for Gemini planning
   └─ Build initial context package

Phase 2: Gemini Strategy Planning
   ├─ Feed ACE context + prompt to Gemini CLI
   ├─ Gemini analyzes and generates exploration strategy
   ├─ Create exploration dimensions with search targets
   ├─ Define comparison matrix (if comparison intent)
   └─ Set success criteria and iteration limits

Phase 3: Iterative Agent Exploration (with ACE)
   ├─ Iteration 1: Initial exploration by assigned agents
   │   ├─ Agent A: ACE search + explore dimension 1
   │   ├─ Agent B: ACE search + explore dimension 2
   │   └─ Collect findings, update shared context
   ├─ Iteration 2-N: Refined exploration
   │   ├─ Analyze previous findings
   │   ├─ ACE search for related code paths
   │   ├─ Execute targeted exploration
   │   └─ Update cumulative findings
   └─ Termination: Max iterations or convergence

Phase 4: Cross-Analysis & Synthesis
   ├─ Compare findings across dimensions
   ├─ Identify discrepancies and issues
   ├─ Calculate confidence scores
   └─ Generate issue candidates

Phase 5: Issue Generation & Summary
   ├─ Convert findings to issue format
   ├─ Write discovery outputs
   └─ Prompt user for next action
```

### Exploration Dimensions

Dimensions are **dynamically generated by Gemini** based on the user prompt. Not limited to predefined categories.

**Examples**:

| Prompt | Generated Dimensions |
|--------|---------------------|
| "Check API contracts" | frontend-calls, backend-handlers |
| "Find auth issues" | auth-module (single dimension) |
| "Compare old/new implementations" | legacy-code, new-code |
| "Audit payment flow" | payment-service, validation, logging |
| "Find error handling gaps" | error-handlers, error-types, recovery-logic |

Gemini analyzes the prompt + ACE context to determine:
- How many dimensions are needed (1 to N)
- What each dimension should focus on
- Whether comparison is needed between dimensions

### Iteration Strategy

```
┌─────────────────────────────────────────────────────────────┐
│                    Iteration Loop                           │
├─────────────────────────────────────────────────────────────┤
│  1. Plan: What to explore this iteration                    │
│     └─ Based on: previous findings + unexplored areas       │
│                                                             │
│  2. Execute: Launch agents for this iteration               │
│     └─ Each agent: explore → collect → return summary       │
│                                                             │
│  3. Analyze: Process iteration results                      │
│     └─ New findings? Gaps? Contradictions?                  │
│                                                             │
│  4. Decide: Continue or terminate                           │
│     └─ Terminate if: max iterations OR convergence OR       │
│                      high confidence on all questions       │
└─────────────────────────────────────────────────────────────┘
```

## Core Responsibilities

### Phase 1: Prompt Analysis & Initialization

```javascript
// Step 1: Parse arguments
const { prompt, scope, depth, maxIterations } = parseArgs(args);

// Step 2: Generate discovery ID
const discoveryId = `DBP-${formatDate(new Date(), 'YYYYMMDD-HHmmss')}`;

// Step 3: Create output directory
const outputDir = `.workflow/issues/discoveries/${discoveryId}`;
await mkdir(outputDir, { recursive: true });
await mkdir(`${outputDir}/iterations`, { recursive: true });

// Step 4: Detect intent type from prompt
const intentType = detectIntent(prompt);
// Returns: 'comparison' | 'search' | 'verification' | 'audit'

// Step 5: Initialize discovery state
await writeJson(`${outputDir}/discovery-state.json`, {
  discovery_id: discoveryId,
  type: 'prompt-driven',
  prompt: prompt,
  intent_type: intentType,
  scope: scope || '**/*',
  depth: depth || 'standard',
  max_iterations: maxIterations || 5,
  phase: 'initialization',
  created_at: new Date().toISOString(),
  iterations: [],
  cumulative_findings: [],
  comparison_matrix: null  // filled for comparison intent
});
```

### Phase 1.5: ACE Context Gathering

**Purpose**: Use ACE semantic search to gather codebase context before Gemini planning.

```javascript
// Step 1: Extract keywords from prompt for semantic search
const keywords = extractKeywords(prompt);
// e.g., "frontend API calls match backend" → ["frontend", "API", "backend", "endpoints"]

// Step 2: Use ACE to understand codebase structure
const aceQueries = [
  `Project architecture and module structure for ${keywords.join(', ')}`,
  `Where are ${keywords[0]} implementations located?`,
  `How does ${keywords.slice(0, 2).join(' ')} work in this codebase?`
];

const aceResults = [];
for (const query of aceQueries) {
  const result = await mcp__ace-tool__search_context({
    project_root_path: process.cwd(),
    query: query
  });
  aceResults.push({ query, result });
}

// Step 3: Build context package for Gemini (kept in memory)
const aceContext = {
  prompt_keywords: keywords,
  codebase_structure: aceResults[0].result,
  relevant_modules: aceResults.slice(1).map(r => r.result),
  detected_patterns: extractPatterns(aceResults)
};

// Step 4: Update state (no separate file)
await updateDiscoveryState(outputDir, {
  phase: 'context-gathered',
  ace_context: {
    queries_executed: aceQueries.length,
    modules_identified: aceContext.relevant_modules.length
  }
});

// aceContext passed to Phase 2 in memory
```

**ACE Query Strategy by Intent Type**:

| Intent | ACE Queries |
|--------|-------------|
| **comparison** | "frontend API calls", "backend API handlers", "API contract definitions" |
| **search** | "{keyword} implementations", "{keyword} usage patterns" |
| **verification** | "expected behavior for {feature}", "test coverage for {feature}" |
| **audit** | "all {category} patterns", "{category} security concerns" |

### Phase 2: Gemini Strategy Planning

**Purpose**: Gemini analyzes user prompt + ACE context to design optimal exploration strategy.

```javascript
// Step 1: Load ACE context gathered in Phase 1.5
const aceContext = await readJson(`${outputDir}/ace-context.json`);

// Step 2: Build Gemini planning prompt with ACE context
const planningPrompt = `
PURPOSE: Analyze discovery prompt and create exploration strategy based on codebase context
TASK:
• Parse user intent from prompt: "${prompt}"
• Use codebase context to identify specific modules and files to explore
• Create exploration dimensions with precise search targets
• Define comparison matrix structure (if comparison intent)
• Set success criteria and iteration strategy
MODE: analysis
CONTEXT: @${scope || '**/*'} | Discovery type: ${intentType}

## Codebase Context (from ACE semantic search)
${JSON.stringify(aceContext, null, 2)}

EXPECTED: JSON exploration plan following exploration-plan-schema.json:
{
  "intent_analysis": { "type": "${intentType}", "primary_question": "...", "sub_questions": [...] },
  "dimensions": [{ "name": "...", "description": "...", "search_targets": [...], "focus_areas": [...], "agent_prompt": "..." }],
  "comparison_matrix": { "dimension_a": "...", "dimension_b": "...", "comparison_points": [...] },
  "success_criteria": [...],
  "estimated_iterations": N,
  "termination_conditions": [...]
}
CONSTRAINTS: Use ACE context to inform targets | Focus on actionable plan
`;

// Step 3: Execute Gemini planning
Bash({
  command: `ccw cli -p "${planningPrompt}" --tool gemini --mode analysis`,
  run_in_background: true,
  timeout: 300000
});

// Step 4: Parse Gemini output and validate against schema
const explorationPlan = await parseGeminiPlanOutput(geminiResult);
validateAgainstSchema(explorationPlan, 'exploration-plan-schema.json');

// Step 5: Enhance plan with ACE-discovered file paths
explorationPlan.dimensions = explorationPlan.dimensions.map(dim => ({
  ...dim,
  ace_suggested_files: aceContext.relevant_modules
    .filter(m => m.relevance_to === dim.name)
    .map(m => m.file_path)
}));

// Step 6: Update state (plan kept in memory, not persisted)
await updateDiscoveryState(outputDir, {
  phase: 'planned',
  exploration_plan: {
    dimensions_count: explorationPlan.dimensions.length,
    has_comparison_matrix: !!explorationPlan.comparison_matrix,
    estimated_iterations: explorationPlan.estimated_iterations
  }
});

// explorationPlan passed to Phase 3 in memory
```

**Gemini Planning Responsibilities**:

| Responsibility | Input | Output |
|----------------|-------|--------|
| Intent Analysis | User prompt | type, primary_question, sub_questions |
| Dimension Design | ACE context + prompt | dimensions with search_targets |
| Comparison Matrix | Intent type + modules | comparison_points (if applicable) |
| Iteration Strategy | Depth setting | estimated_iterations, termination_conditions |

**Gemini Planning Output Schema**:

```json
{
  "intent_analysis": {
    "type": "comparison|search|verification|audit",
    "primary_question": "string",
    "sub_questions": ["string"]
  },
  "dimensions": [
    {
      "name": "frontend",
      "description": "Client-side API calls and error handling",
      "search_targets": ["src/api/**", "src/hooks/**"],
      "focus_areas": ["fetch calls", "error boundaries", "response parsing"],
      "agent_prompt": "Explore frontend API consumption patterns..."
    },
    {
      "name": "backend",
      "description": "Server-side API implementations",
      "search_targets": ["src/server/**", "src/routes/**"],
      "focus_areas": ["endpoint handlers", "response schemas", "error responses"],
      "agent_prompt": "Explore backend API implementations..."
    }
  ],
  "comparison_matrix": {
    "dimension_a": "frontend",
    "dimension_b": "backend",
    "comparison_points": [
      {"aspect": "endpoints", "frontend_check": "fetch URLs", "backend_check": "route paths"},
      {"aspect": "methods", "frontend_check": "HTTP methods used", "backend_check": "methods accepted"},
      {"aspect": "payloads", "frontend_check": "request body structure", "backend_check": "expected schema"},
      {"aspect": "responses", "frontend_check": "response parsing", "backend_check": "response format"},
      {"aspect": "errors", "frontend_check": "error handling", "backend_check": "error responses"}
    ]
  },
  "success_criteria": [
    "All API endpoints mapped between frontend and backend",
    "Discrepancies identified with file:line references",
    "Each finding includes remediation suggestion"
  ],
  "estimated_iterations": 3,
  "termination_conditions": [
    "All comparison points verified",
    "No new findings in last iteration",
    "Confidence > 0.8 on primary question"
  ]
}
```

### Phase 3: Iterative Agent Exploration (with ACE)

**Purpose**: Multi-agent iterative exploration using ACE for semantic search within each iteration.

```javascript
let iteration = 0;
let cumulativeFindings = [];
let sharedContext = { aceDiscoveries: [], crossReferences: [] };
let shouldContinue = true;

while (shouldContinue && iteration < maxIterations) {
  iteration++;
  const iterationDir = `${outputDir}/iterations/${iteration}`;
  await mkdir(iterationDir, { recursive: true });

  // Step 1: ACE-assisted iteration planning
  // Use previous findings to guide ACE queries for this iteration
  const iterationAceQueries = iteration === 1
    ? explorationPlan.dimensions.map(d => d.focus_areas[0])  // Initial queries from plan
    : deriveQueriesFromFindings(cumulativeFindings);         // Follow-up queries from findings

  // Execute ACE searches to find related code
  const iterationAceResults = [];
  for (const query of iterationAceQueries) {
    const result = await mcp__ace-tool__search_context({
      project_root_path: process.cwd(),
      query: `${query} in ${explorationPlan.scope}`
    });
    iterationAceResults.push({ query, result });
  }

  // Update shared context with ACE discoveries
  sharedContext.aceDiscoveries.push(...iterationAceResults);

  // Step 2: Plan this iteration based on ACE results
  const iterationPlan = planIteration(iteration, explorationPlan, cumulativeFindings, iterationAceResults);

  // Step 3: Launch dimension agents with ACE context
  const agentPromises = iterationPlan.dimensions.map(dimension =>
    Task({
      subagent_type: "cli-explore-agent",
      run_in_background: false,
      description: `Explore ${dimension.name} (iteration ${iteration})`,
      prompt: buildDimensionPromptWithACE(dimension, iteration, cumulativeFindings, iterationAceResults, iterationDir)
    })
  );

  // Wait for iteration agents
  const iterationResults = await Promise.all(agentPromises);

  // Step 4: Collect and analyze iteration findings
  const iterationFindings = await collectIterationFindings(iterationDir, iterationPlan.dimensions);

  // Step 5: Cross-reference findings between dimensions
  if (iterationPlan.dimensions.length > 1) {
    const crossRefs = findCrossReferences(iterationFindings, iterationPlan.dimensions);
    sharedContext.crossReferences.push(...crossRefs);
  }

  cumulativeFindings.push(...iterationFindings);

  // Step 6: Decide whether to continue
  const convergenceCheck = checkConvergence(iterationFindings, cumulativeFindings, explorationPlan);
  shouldContinue = !convergenceCheck.converged;

  // Step 7: Update state (iteration summary embedded in state)
  await updateDiscoveryState(outputDir, {
    iterations: [...state.iterations, {
      number: iteration,
      findings_count: iterationFindings.length,
      ace_queries: iterationAceQueries.length,
      cross_references: sharedContext.crossReferences.length,
      new_discoveries: convergenceCheck.newDiscoveries,
      confidence: convergenceCheck.confidence,
      continued: shouldContinue
    }],
    cumulative_findings: cumulativeFindings
  });
}
```

**ACE in Iteration Loop**:

```
Iteration N
    │
    ├─→ ACE Search (based on previous findings)
    │   └─ Query: "related code paths for {finding.category}"
    │   └─ Result: Additional files to explore
    │
    ├─→ Agent Exploration (with ACE context)
    │   └─ Agent receives: dimension targets + ACE suggestions
    │   └─ Agent can call ACE for deeper search
    │
    ├─→ Cross-Reference Analysis
    │   └─ Compare findings between dimensions
    │   └─ Identify discrepancies
    │
    └─→ Convergence Check
        └─ New findings? Continue
        └─ No new findings? Terminate
```

**Dimension Agent Prompt Template (with ACE)**:

```javascript
function buildDimensionPromptWithACE(dimension, iteration, previousFindings, aceResults, outputDir) {
  // Filter ACE results relevant to this dimension
  const relevantAceResults = aceResults.filter(r =>
    r.query.includes(dimension.name) || dimension.focus_areas.some(fa => r.query.includes(fa))
  );

  return `
    ## Task Objective
    Explore ${dimension.name} dimension for issue discovery (Iteration ${iteration})

    ## Context
    - Dimension: ${dimension.name}
    - Description: ${dimension.description}
    - Search Targets: ${dimension.search_targets.join(', ')}
    - Focus Areas: ${dimension.focus_areas.join(', ')}

    ## ACE Semantic Search Results (Pre-gathered)
    The following files/code sections were identified by ACE as relevant to this dimension:
    ${JSON.stringify(relevantAceResults.map(r => ({ query: r.query, files: r.result.slice(0, 5) })), null, 2)}

    **Use ACE for deeper exploration**: You have access to mcp__ace-tool__search_context.
    When you find something interesting, use ACE to find related code:
    - mcp__ace-tool__search_context({ project_root_path: ".", query: "related to {finding}" })

    ${iteration > 1 ? `
    ## Previous Findings to Build Upon
    ${summarizePreviousFindings(previousFindings, dimension.name)}

    ## This Iteration Focus
    - Explore areas not yet covered (check ACE results for new files)
    - Verify/deepen previous findings
    - Follow leads from previous discoveries
    - Use ACE to find cross-references between dimensions
    ` : ''}

    ## MANDATORY FIRST STEPS
    1. Read exploration plan: ${outputDir}/../exploration-plan.json
    2. Read schema: ~/.claude/workflows/cli-templates/schemas/discovery-finding-schema.json
    3. Review ACE results above for starting points
    4. Explore files identified by ACE

    ## Exploration Instructions
    ${dimension.agent_prompt}

    ## ACE Usage Guidelines
    - Use ACE when you need to find:
      - Where a function/class is used
      - Related implementations in other modules
      - Cross-module dependencies
      - Similar patterns elsewhere in codebase
    - Query format: Natural language, be specific
    - Example: "Where is UserService.authenticate called from?"

    ## Output Requirements

    **1. Write JSON file**: ${outputDir}/${dimension.name}.json
    Follow discovery-finding-schema.json:
    - findings: [{id, title, category, description, file, line, snippet, confidence, related_dimension}]
    - coverage: {files_explored, areas_covered, areas_remaining}
    - leads: [{description, suggested_search}] // for next iteration
    - ace_queries_used: [{query, result_count}] // track ACE usage

    **2. Return summary**:
    - Total findings this iteration
    - Key discoveries
    - ACE queries that revealed important code
    - Recommended next exploration areas

    ## Success Criteria
    - [ ] JSON written to ${outputDir}/${dimension.name}.json
    - [ ] Each finding has file:line reference
    - [ ] ACE used for cross-references where applicable
    - [ ] Coverage report included
    - [ ] Leads for next iteration identified
  `;
}
```

### Phase 4: Cross-Analysis & Synthesis

```javascript
// For comparison intent, perform cross-analysis
if (intentType === 'comparison' && explorationPlan.comparison_matrix) {
  const comparisonResults = [];

  for (const point of explorationPlan.comparison_matrix.comparison_points) {
    const dimensionAFindings = cumulativeFindings.filter(f =>
      f.related_dimension === explorationPlan.comparison_matrix.dimension_a &&
      f.category.includes(point.aspect)
    );

    const dimensionBFindings = cumulativeFindings.filter(f =>
      f.related_dimension === explorationPlan.comparison_matrix.dimension_b &&
      f.category.includes(point.aspect)
    );

    // Compare and find discrepancies
    const discrepancies = findDiscrepancies(dimensionAFindings, dimensionBFindings, point);

    comparisonResults.push({
      aspect: point.aspect,
      dimension_a_count: dimensionAFindings.length,
      dimension_b_count: dimensionBFindings.length,
      discrepancies: discrepancies,
      match_rate: calculateMatchRate(dimensionAFindings, dimensionBFindings)
    });
  }

  // Write comparison analysis
  await writeJson(`${outputDir}/comparison-analysis.json`, {
    matrix: explorationPlan.comparison_matrix,
    results: comparisonResults,
    summary: {
      total_discrepancies: comparisonResults.reduce((sum, r) => sum + r.discrepancies.length, 0),
      overall_match_rate: average(comparisonResults.map(r => r.match_rate)),
      critical_mismatches: comparisonResults.filter(r => r.match_rate < 0.5)
    }
  });
}

// Prioritize all findings
const prioritizedFindings = prioritizeFindings(cumulativeFindings, explorationPlan);
```

### Phase 5: Issue Generation & Summary

```javascript
// Convert high-confidence findings to issues
const issueWorthy = prioritizedFindings.filter(f =>
  f.confidence >= 0.7 || f.priority === 'critical' || f.priority === 'high'
);

const issues = issueWorthy.map(finding => ({
  id: `ISS-${discoveryId}-${finding.id}`,
  title: finding.title,
  description: finding.description,
  source: {
    discovery_id: discoveryId,
    finding_id: finding.id,
    dimension: finding.related_dimension
  },
  file: finding.file,
  line: finding.line,
  priority: finding.priority,
  category: finding.category,
  suggested_fix: finding.suggested_fix,
  confidence: finding.confidence,
  status: 'discovered',
  created_at: new Date().toISOString()
}));

// Write issues
await writeJsonl(`${outputDir}/discovery-issues.jsonl`, issues);

// Update final state (summary embedded in state, no separate file)
await updateDiscoveryState(outputDir, {
  phase: 'complete',
  updated_at: new Date().toISOString(),
  results: {
    total_iterations: iteration,
    total_findings: cumulativeFindings.length,
    issues_generated: issues.length,
    comparison_match_rate: comparisonResults
      ? average(comparisonResults.map(r => r.match_rate))
      : null
  }
});

// Prompt user for next action
await AskUserQuestion({
  questions: [{
    question: `Discovery complete: ${issues.length} issues from ${cumulativeFindings.length} findings across ${iteration} iterations. What next?`,
    header: "Next Step",
    multiSelect: false,
    options: [
      { label: "Export to Issues (Recommended)", description: `Export ${issues.length} issues for planning` },
      { label: "Review Details", description: "View comparison analysis and iteration details" },
      { label: "Run Deeper", description: "Continue with more iterations" },
      { label: "Skip", description: "Complete without exporting" }
    ]
  }]
});
```

## Output File Structure

```
.workflow/issues/discoveries/
└── {DBP-YYYYMMDD-HHmmss}/
    ├── discovery-state.json          # Session state with iteration tracking
    ├── iterations/
    │   ├── 1/
    │   │   └── {dimension}.json      # Dimension findings
    │   ├── 2/
    │   │   └── {dimension}.json
    │   └── ...
    ├── comparison-analysis.json      # Cross-dimension comparison (if applicable)
    └── discovery-issues.jsonl        # Generated issue candidates
```

**Simplified Design**:
- ACE context and Gemini plan kept in memory, not persisted
- Iteration summaries embedded in state
- No separate summary.md (state.json contains all needed info)

## Schema References

| Schema | Path | Used By |
|--------|------|---------|
| **Discovery State** | `discovery-state-schema.json` | Orchestrator (state tracking) |
| **Discovery Finding** | `discovery-finding-schema.json` | Dimension agents (output) |
| **Exploration Plan** | `exploration-plan-schema.json` | Gemini output validation (memory only) |

## Configuration Options

| Flag | Default | Description |
|------|---------|-------------|
| `--scope` | `**/*` | File pattern to explore |
| `--depth` | `standard` | `standard` (3 iterations) or `deep` (5+ iterations) |
| `--max-iterations` | 5 | Maximum exploration iterations |
| `--tool` | `gemini` | Planning tool (gemini/qwen) |
| `--plan-only` | `false` | Stop after Phase 2 (Gemini planning), show plan for user review |

## Examples

### Example 1: Single Module Deep Dive

```bash
/issue:discover-by-prompt "Find all potential issues in the auth module" --scope=src/auth/**
```

**Gemini plans** (single dimension):
- Dimension: auth-module
- Focus: security vulnerabilities, edge cases, error handling, test gaps

**Iterations**: 2-3 (until no new findings)

### Example 2: API Contract Comparison

```bash
/issue:discover-by-prompt "Check if API calls match implementations" --scope=src/**
```

**Gemini plans** (comparison):
- Dimension 1: api-consumers (fetch calls, hooks, services)
- Dimension 2: api-providers (handlers, routes, controllers)
- Comparison matrix: endpoints, methods, payloads, responses

### Example 3: Multi-Module Audit

```bash
/issue:discover-by-prompt "Audit the payment flow for issues" --scope=src/payment/**
```

**Gemini plans** (multi-dimension):
- Dimension 1: payment-logic (calculations, state transitions)
- Dimension 2: validation (input checks, business rules)
- Dimension 3: error-handling (failure modes, recovery)

### Example 4: Plan Only Mode

```bash
/issue:discover-by-prompt "Find inconsistent patterns" --plan-only
```

Stops after Gemini planning, outputs:
```
Gemini Plan:
- Intent: search
- Dimensions: 2 (pattern-definitions, pattern-usages)
- Estimated iterations: 3

Continue with exploration? [Y/n]
```

## Related Commands

```bash
# After discovery, plan solutions
/issue:plan DBP-001-01,DBP-001-02

# View all discoveries
/issue:manage

# Standard perspective-based discovery
/issue:discover src/auth/** --perspectives=security,bug
```

## Best Practices

1. **Be Specific in Prompts**: More specific prompts lead to better Gemini planning
2. **Scope Appropriately**: Narrow scope for focused comparison, wider for audits
3. **Review Exploration Plan**: Check `exploration-plan.json` before long explorations
4. **Use Standard Depth First**: Start with standard, go deep only if needed
5. **Combine with `/issue:discover`**: Use prompt-based for comparisons, perspective-based for audits
