## Detection Wave Orchestration Strategy

> This file defines the orchestration workflow for the defect detection stage — how the main task schedules subtasks, the subtask execution template, and input/output contracts.

### Main Task Responsibilities (Orchestrator)

#### 1. Restore Context

1. Read `<output_dir>/.draft-01-change-analysis.md` (scan file list + project environment)
2. Create the `<output_dir>/.draft-02-detection/` directory
3. Write the initial version of `<output_dir>/.draft-02-detection/manifest.json`:
```json
{
  "version": 1,
  "stage": "detection",
  "status": "in_progress",
  "scan_mode": "<branch|file|directory>",
  "source_branch": "<source_branch>",
  "target_branch": "<target_branch>",
  "files": [],
  "skipped_files": [],
  "defects": [
    {
      "id": "D001",
      "severity": "high/medium/low",
      "type": "static defect/security vulnerability/logic defect/memory issue",
      "title": "Defect title",
      "file": "Original file path",
      "location": "file path:start line-end line",
      "source_file": "Flattened per-file output filename (path / replaced with -)",
      "detection_types": ["Matched detection types"]
    }
  ],
  "summary": {
    "total_files": 0,
    "completed_files": 0,
    "total_defects": 0,
    "by_type": {},
    "by_severity": {}
  }
}
```

#### 2. Exclude Files Not Requiring Scanning

From the scan file list in `.draft-01-change-analysis.md`, exclude the following file types:
- Pure configuration files (JSON, YAML, TOML, .env)
- Pure style files (CSS, SCSS, LESS)
- Pure static assets (images, fonts)

Record the excluded files and reasons in the `files` array of `manifest.json` (`status: "skipped"`).

#### 3. Per-File Scheduling

For each file in `.draft-01-change-analysis.md` that requires detection, execute in sequence:

##### 3.1 Trigger Signal-Based Detection Type Assignment

For each file, the main task first reads the file content, matches trigger signals, and precisely determines the detection types:

1. **Read file**: use `Read` to obtain the file content (in file scan mode, read the specified line range)
2. **Match trigger signals**: sequentially read the following routing.md files and match code characteristics:
   - `<skill-root>/references/detection/static-defects/routing.md`
   - `<skill-root>/references/detection/security-vulnerabilities/routing.md`
   - `<skill-root>/references/detection/logical-defects/routing.md`
   - `<skill-root>/references/detection/memory-issues/routing.md`
3. **Determine detection types**: use the detection types corresponding to the matched trigger signals as the detection assignment for this file
4. **Record assignment results**: record the file path and assigned detection types in the `files` array of `manifest.json`


##### 3.2 Launch Subtask

Based on the assigned detection types, launch an Agent subtask, passing in the **subtask execution template** (see below) and filling in the following variables:
   - `<file-path>`: file path
   - `<detection_types>`: detection type list determined by trigger signal matching in step 3.1
   - `<project_env>`: project environment information extracted from `.draft-01-change-analysis.md`
   - `<output_dir>`: output directory path
   - `<skill-root>`: skill root path
3. Wait for the subtask to complete
4. Update the `files` array in `manifest.json` (add the file entry, set `status: "completed"`)
5. Update TodoWrite

#### 4. Aggregation

After all files have been detected:

1. Read all output files in the `.draft-02-detection/` directory
2. In file order, extract defects by sequence number from each per-file output
3. Assign a globally unique ID to each defect (D001, D002, ...), constructing a defect object:
   - `id`: D-series ID
   - `severity`, `type`, `title`: extracted from the per-file output detection results table
   - `file`: original file path
   - `location`: extracted from the detection results table (e.g., `file:15-18`)
   - `source_file`: the flattened filename of the current per-file output (path `/` replaced with `-`, with `.md` suffix)
   - `detection_types`: the detection type list assigned to this file
4. Write all defect objects to the `defects` array of `manifest.json`
5. Calculate `summary` (by_type, by_severity)
6. Set `manifest.json` `status: "completed"`

### Subtask Execution Template

---

## Role
You are a code defect detection expert.

## Input
- **File path**: `<file-path>`
- **Detection types**: <detection_types>
- **Project environment**: <project_env>

## Execution Steps

**Warning (mandatory): Use the TodoWrite tool to organize the execution workflow**

### Step 1: Data-Flow Analysis

1. Read `<skill-root>/references/tools/lsp.md` to obtain the LSP tool usage strategy
2. Read the file `<file-path>`
3. Identify data input sources (API parameters, database queries, external calls)
4. Trace key data flows (**at most 5 call levels up/down**)
5. Identify sensitive operation points (database writes, permission checks, state changes)
6. Use LSP tools to assist analysis: `find_definition` to verify symbol definitions, `find_references` to trace data flows

### Step 2: Defect Detection

For each assigned detection type, execute sequentially:
   - **static-defects** (if assigned): read `<skill-root>/references/detection/static-defects/routing.md`, match trigger signals, load the corresponding sub-file, and execute according to the sub-file detection specification
   - **security-vulnerabilities** (if assigned): read `<skill-root>/references/detection/security-vulnerabilities/routing.md`, match trigger signals, load the corresponding sub-file, and execute according to the sub-file detection specification
   - **logical-defects** (if assigned): read `<skill-root>/references/detection/logical-defects/routing.md`, match trigger signals, load the corresponding sub-file, and execute according to the sub-file detection specification
   - **memory-issues** (if assigned): read `<skill-root>/references/detection/memory-issues/routing.md`, match trigger signals, load the corresponding sub-file, and execute according to the sub-file detection specification

## Output Format

Write to `<output_dir>/.draft-02-detection/<flattened-path>.md` (`<flattened-path>` replaces `/` in the original file path with `-`, e.g., `src/utils/helper.ts` → `src-utils-helper.ts.md`):

```
### <File Path>

#### Data-Flow Analysis
- **Detection types**: security vulnerabilities / logical defects
- **Data input sources**: ...
- **Data flow**: ...
- **Sensitive operation points**: ...

#### Detection Results

| # | Severity | Defect Type | Code Location | Defect Title |
|---|----------|-------------|---------------|--------------|
| 1 | High | Security Vulnerabilities | `file:line-line` | Brief title |

**[1] Brief title**
- **Analysis**: Root cause and trigger conditions of the issue
- **Impact**: Business impact and exploitation method
- **Issue code**:
```code_language
Issue code snippet
```
- **Fix code**:
```code_language
Fix code snippet (optional)
```
- **Evidence chain**:
```mermaid
graph LR
    A["Source code location 1<br>file:line"] -->|"Data flow / call relationship"| B["Source code location 2<br>file:line"]
    B -->|"Data flow / call relationship"| C["Dangerous operation<br>file:line"]
```

Security vulnerabilities evidence chain pattern: Source (user input) -> Propagation (data passing) -> Sink (dangerous operation)
Static defects evidence chain pattern: Declaration -> Usage -> Error point
Logical defects evidence chain pattern: Business operation -> State change -> Constraint violation
Memory issues evidence chain pattern: Allocation -> Usage -> Deallocation (or missing)
```

If a detection type has no trigger signal match or no findings, output "No findings" for that section.
