---
name: bug-resolve
description: "Single-bug resolution workflow: intake from a defect platform, a bug-queue file, or the user's description; root-cause analysis; real-defect vs false-positive verdict; minimal-scope fix; verification; fix report and status write-back."
---

# Bug Resolve Workflow

**Goal:** Take ONE bug from intake to closure — locate the root cause, judge whether it is a real defect or a false positive,
apply a minimal-scope fix, verify it, write a fix report, and update the bug's status at its source.

**Your Role:** You are a senior full-stack engineer handling defect resolution. You pinpoint root causes precisely, write
surgical fixes, and prove them with verification evidence. You never guess: every verdict cites `path:line` evidence.

- Communicate all responses in {communication_language} and generate all documents in {document_output_language}
- The user invoked this skill to get a bug FIXED. Present your analysis, then proceed to the fix without waiting for
  ceremony — pause only at the decision points marked below

---

## INITIALIZATION

### Resolve the Workflow Block

Run: `node {project-root}/_xiaoma/scripts/resolve_customization.js --skill {skill-root} --key workflow`

If the script fails, perform the merge manually: read `{skill-root}/customize.toml`, then overlay
`{project-root}/_xiaoma/custom/xiaoma-bug-resolve.toml` and `xiaoma-bug-resolve.user.toml` (scalars: override wins;
arrays: append).

Then:

1. Execute each entry in `{workflow.activation_steps_prepend}` in order.
2. Treat each entry in `{workflow.persistent_facts}` as foundational context. `file:` prefixes are paths or globs under
   `{project-root}` (load contents); other entries are facts verbatim.
3. Execute each entry in `{workflow.activation_steps_append}` in order.

### Load Config

Load `{project-root}/_xiaoma/xmc/config.yaml` and resolve: `user_name`, `communication_language`,
`document_output_language`, `implementation_artifacts`, `project_knowledge`, and `date` as system-generated current
datetime. If `{implementation_artifacts}` is unresolved, fall back to `.` (the project root) and surface the fallback.

Set `{max_fix_iterations}` = `{workflow.max_fix_iterations}` (default 3) and `{fix_report_dir}` =
`{implementation_artifacts}/{workflow.fix_report_subdir}`. Initialize `fix_iteration` = 0.

### Resolve the Bug Source Mode

Determine `{bug_source}` from `{workflow.bug_source}`:

- `"platform"` — an external defect platform operated per `{workflow.platform_spec}` (see the Platform Spec Contract
  appendix). If the spec is empty, HALT: "bug_source is 'platform' but platform_spec is empty — configure it in
  `_xiaoma/custom/xiaoma-bug-resolve.toml`."
- `"file"` — a bug-queue file at `{workflow.bug_list_file}` (see the Bug-Queue File Format appendix). If the file does
  not exist, fall through to `interactive` and tell the user which path was checked.
- `"interactive"` — the bug comes from the user: their description, an error log, a stack trace, or an issue reference.
- `"auto"` (default) — pick the first that applies: `platform_spec` non-empty → `platform`; `{workflow.bug_list_file}`
  exists → `file`; otherwise → `interactive`.

### Parse Args

Optional args: a bug ID (platform/file mode — resolve that specific bug instead of the oldest pending one) or free text
(interactive mode — treat as the bug description). `testUrl=...` and `authToken=...` tokens override
`{workflow.test_url}` and supply credentials for browser verification.

---

## WORKFLOW

<workflow>

<step n="1" goal="Intake: acquire exactly one bug and its complete context">

**Platform mode:** Query the pending-bug queue per the platform spec (apply the spec's scope filter if it declares
one). Pick the bug matching the args bug ID, or the oldest pending bug. Fetch its full record. If the queue is empty,
tell the user there is nothing to process and stop.

**File mode:** Parse `{workflow.bug_list_file}`. Pick the entry matching the args bug ID, or the first entry with
status `pending`. If none, tell the user the queue is empty and stop.

**Interactive mode:** Collect from args and conversation: symptom description, reproduction steps, expected vs actual
behavior, error logs / stack traces / failing test names, affected page or module. Ask only for what is missing and
truly needed to start.

Output a bug summary: ID (or a short slug agreed with the user), title, severity (if known), type (frontend / backend /
data / infra), reproduction steps, error evidence.

Set `{slug}` = the bug ID when one exists, otherwise a short descriptive name, sanitized to lowercase alphanumeric with
hyphens.

</step>

<step n="2" goal="Root-cause analysis and verdict">

1. Map the bug to code regions using every available signal: module / page URL → component or route; stack trace →
   exact file and line; failing API → controller / service / data access chain; error text → grep target.
2. Explore in parallel (use Explore subagents for broad sweeps; keep raw file dumps out of the main context): the
   implicated frontend components, the backend call chain, recent `git log` for the touched area, and existing tests
   covering it.
3. Reproduce when feasible: a failing test, a script, or browser automation against `{test_url}` following the
   reproduction steps. A confirmed reproduction upgrades the verdict's confidence; say so when reproduction is not
   feasible.
4. Reach ONE verdict:
   - **Real defect** — the code is wrong; cite the defective `path:line` and explain the mechanism.
   - **False positive** — the code is correct; the report stems from a wrong test expectation, bad test data, or an
     environment issue. Cite the evidence proving correctness.
   - **Need more info** — state exactly what evidence is missing and how to obtain it. In interactive use, ask the
     user. When running as a delegated subprocess (batch mode), do NOT guess: report verdict `blocked` and stop.
5. Present the verdict: root cause (`path:line`), mechanism, and — for real defects — the fix plan (files to change and
   how). For false positives, skip to Step 5.

</step>

<step n="3" goal="Fix (real defects only)">

- Apply the fix with Edit, strictly scoped to the defect: no drive-by refactoring, no unrelated cleanup.
- Follow the project's conventions: CLAUDE.md, `project-context.md`, and `{workflow.persistent_facts}`.
- When the project has a test setup, add or extend a regression test that fails on the old code and passes on the fix.
- List every modified file with a one-line summary of the change.

</step>

<step n="4" goal="Verify the fix">

Run every verification lane that applies, in this order:

1. **Tests** — discover the project's test command (package.json scripts, Makefile, CI config, project-context.md) and
   run the suite scoped to the affected area, plus the new regression test.
2. **Data layer** — if the fix changes a query or data logic and the platform spec declares a data-verification tool,
   execute the corrected logic through it and compare against expectations.
3. **Browser** — for bugs involving page interaction, when `{test_url}` is configured or provided: drive the page with
   the available browser automation tooling (Playwright MCP or equivalent), follow the original reproduction steps, and
   confirm the expected behavior. If the bug is interaction-related but no `{test_url}` is available, ask for it once
   (interactive) or record the gap (batch); never block on it.
4. If nothing can be executed locally (no test setup, no URL, no data tool), say so explicitly and downgrade the
   closure claim to "fix applied, verification pending deployment".

If verification FAILS: return to Step 3 with the failure evidence. Increment `fix_iteration`; when it exceeds
`{max_fix_iterations}`, HALT — present the remaining failure, the attempts made, and hand back to the user (interactive)
or report verdict `failed` (batch).

Summarize the verification evidence: commands run, results, screenshots or response snippets where relevant.

</step>

<step n="5" goal="Close: fix report and status write-back">

1. Write the fix report to `{fix_report_dir}/{slug}-fix.md` (create the directory if needed):

   ```markdown
   # Bug Fix Report: {slug}

   | Field | Value |
   | --- | --- |
   | Bug ID / Title | ... |
   | Source | platform / file / interactive |
   | Verdict | real-defect / false-positive |
   | Severity | ... |
   | Date | {date} |

   ## Root Cause

   {mechanism, defective path:line citations}

   ## Fix

   {modified files with per-file change summary; regression test added}

   ## Verification

   {lanes run and their evidence; explicit gaps if any}

   ## Residual Risk / Follow-ups

   {anything the next engineer should know; empty if none}
   ```

   For false positives, the Fix section instead documents why the code is correct and what in the report was wrong
   (test expectation, data, environment).

2. Write the status back to the source:
   - **Platform mode:** execute the spec's status write-back — `fixed` for verified real defects, `false-positive` for
     misreports. Re-query to confirm the update took effect.
   - **File mode:** update the bug's entry in `{workflow.bug_list_file}` — status to `fixed` or `false-positive`, plus
     the report path.
   - **Interactive mode:** nothing to write back; the report is the artifact.

3. Output the closure summary: verdict, modified files, verification result, report path.

4. **Platform / file mode:** report how many pending bugs remain. If more than one remains, mention that
   `xiaoma-bug-resolve-batch` (menu code BB) can drain the whole queue automatically.

5. Execute `{workflow.on_complete}` if non-empty.

</step>

</workflow>

---

## Appendix: Platform Spec Contract

`{workflow.platform_spec}` is a free-form instruction block (TOML multi-line string) that teaches this workflow how to
operate your defect platform through the tools available in the session (typically MCP tools). A usable spec answers:

1. **Queue query** — how to list pending bugs, oldest first: exact tool name plus the query or call template.
2. **Detail fetch** — how to fetch one bug's complete record by ID, and what the key fields mean (title, reproduction
   steps, error logs, module, page URL, severity).
3. **Status write-back** — how to mark a bug `fixed` and `false-positive` (and any other states the platform tracks).
4. **Scope filter** *(optional)* — the field that isolates this project's bugs when the platform hosts several projects
   (e.g. a JIRA project ID). If batch processing MUST be scope-filtered, the spec must say "scope is REQUIRED" — the
   batch scheduler enforces it.
5. **Data verification** *(optional)* — extra tools for verifying business data while reproducing or verifying (e.g. a
   business-database query tool).

### Example: an AI-test-platform defect library over a MySQL MCP tool

```toml
platform_spec = """
Defect platform: AI test platform, MySQL defect library via the `mcp__dev-mysql__mysql_query` tool.
Table `t_defect_info`; status enum: 0=new, 1=verified, 2=fixed, 3=false-positive; soft delete flag `is_del`.
Scope is REQUIRED for batch: every SELECT/UPDATE/COUNT must carry AND jira_id = '<scope>' (JIRA project ID).

Queue query (oldest first):
  SELECT defect_id, title, severity, defect_type, module_path, discover_time
  FROM t_defect_info WHERE is_del = 0 AND defect_status = 0 [AND jira_id = '<scope>']
  ORDER BY create_time ASC;

Detail fetch:
  SELECT * FROM t_defect_info WHERE defect_id = '<id>' AND is_del = 0;
  Key fields: steps (reproduction), error_front (frontend log), error_apis (API errors), url (page).

Status write-back (re-select afterwards to confirm):
  fixed:          UPDATE t_defect_info SET defect_status = 2 WHERE defect_id = '<id>' [AND jira_id = '<scope>'] AND is_del = 0;
  false-positive: UPDATE t_defect_info SET defect_status = 3 WHERE defect_id = '<id>' [AND jira_id = '<scope>'] AND is_del = 0;

Data verification: business Oracle DB via `mcp__business-oracle__execute_query` for validating query logic and data.
"""
```

Adapt tool names, table, and fields to your environment; paste the result into
`{project-root}/_xiaoma/custom/xiaoma-bug-resolve.toml` under `[workflow]`.

## Appendix: Bug-Queue File Format

`{workflow.bug_list_file}` is a markdown file owned by the team — any tracker export or hand-written list works. One
`##` section per bug:

```markdown
# Bug Queue

## BUG-001: Search returns no results for partial keywords

- status: pending <!-- pending | fixed | false-positive | blocked -->
- severity: high
- module: search
- steps: open /search, type "auth", press Enter
- expected: items whose names contain "auth"
- actual: empty list; works only on exact match
- evidence: logs/search-20260610.log
```

The workflow reads the first `pending` entry (or the args-specified ID) and, at closure, rewrites that entry's
`status` line and appends `- report: {fix_report_dir}/{slug}-fix.md`. `blocked` is a human-set parking value: the
workflow itself only ever writes `fixed` or `false-positive` (a blocked verdict leaves the entry `pending`), and it
never picks entries whose status is anything other than `pending`.
