---
name: bug-resolve-batch
description: "Batch bug resolution scheduler with Agent subprocess isolation. Drains all pending bugs from the defect platform or bug-queue file, each resolved in an independent full-tool Agent context."
---

# Bug Resolve — Batch Mode (Agent Subprocess Isolation)

**Goal:** Process ALL pending bugs in the queue — each one resolved end-to-end (analyze → fix → verify → close) in an
**independent Agent subprocess** — fully automatic from start to finish, zero human intervention until the queue is
empty.

**Your Role:** Bug Batch Scheduler. You coordinate the loop and delegate each bug's full lifecycle to an independent
Agent subprocess. You stay lightweight — query queue, launch Agent, read results, continue or finalize.

- Communicate all responses in {communication_language} and generate all documents in {document_output_language}
- Absolutely DO NOT stop because of "milestones", "significant progress", or "session boundaries". Continue in a single
  execution until ALL bugs are processed or a HALT condition is triggered
- **Fully automatic, no human intervention** — from start to finish, the user needs no commands

---

## Core Architecture: Agent-Isolated Processing

Each bug is delegated to an **independent Agent subprocess**. Agents naturally have isolated context spaces, releasing
upon completion without polluting the main conversation — no `/clear` needed. The main conversation only handles the
lightweight scheduling loop.

```text
Main conversation (scheduler, minimal context)
  ├── Agent #1 → Resolve Bug A (isolated context, released after completion)
  ├── Agent #2 → Resolve Bug B (isolated context, released after completion)
  ├── Agent #3 → Resolve Bug C (isolated context, released after completion)
  └── ...until the queue is empty
```

### Core Rules (Strictly Follow)

1. **Each bug processed by an independent Agent** — Use the Agent tool to launch a **general-purpose subprocess with
   FULL tool-execution capability** (the complete tool set: file read/write/edit, shell/command execution, and test
   running — **NOT** a restricted or read-only subagent such as an explore/plan/search-only type). Pass complete bug
   info and processing instructions; the Agent independently completes analyze → fix → verify → close
2. **Main loop stays lightweight** — the scheduler only: queries the queue → launches an Agent → reads results →
   queries remaining → continues or ends
3. **Serial processing** — one bug at a time; wait for Agent completion before the next, avoiding concurrent
   modification conflicts
4. **Scope is a hard isolation boundary** — when a scope filter is in effect, EVERY queue query, detail fetch, and
   status write-back (scheduler-side and Agent-side) must carry it

---

## INITIALIZATION

### Resolve Configuration

1. **Single-bug workflow block** (the single source of truth for bug-source settings):
   run `node {project-root}/_xiaoma/scripts/resolve_customization.js --skill {skill-root}/../xiaoma-bug-resolve --key workflow`
   → yields `bug_source`, `bug_list_file`, `platform_spec`, `test_url`, `max_fix_iterations`, `fix_report_subdir`, and
   the sibling's `persistent_facts` (project knowledge destined for every Agent subprocess — resolve `file:` entries
   to their contents now, keep literal entries verbatim).
2. **Own workflow block:** run the same script with `--skill {skill-root}` → yields this scheduler's
   `activation_steps_*`, `persistent_facts`, `on_complete`. Execute prepend steps, load facts, execute append steps.
3. 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 the resolver script fails, perform the merges manually (customize.toml + `_xiaoma/custom/<skill-name>.toml` +
`<skill-name>.user.toml`; scalars override, arrays append).

### Paths

- `single_bug_workflow` = `{skill-root}/../xiaoma-bug-resolve/workflow.md` (the sibling single-bug skill — each Agent
  subprocess follows its Step 2–5 procedure)
- `batch_status_file` = `{implementation_artifacts}/bug-batch-status.json`

### Parse Args

This scheduler accepts at most ONE positional token: the **scope filter** (e.g. a JIRA project ID isolating this
project's bugs on a shared platform). Rules:

- A token containing `=` is NOT a scope — treat scope as not provided and tell the user (key=value args such as
  `testUrl=...` belong to the single-bug skill, not to batch mode). If args contain more than one token, HALT and
  explain that batch mode takes a single scope token only.
- If `{platform_spec}` declares "scope is REQUIRED" and no scope token was provided: HALT —
  "This platform requires a scope filter. Re-run as: `/xiaoma-bug-resolve-batch <scope>` (e.g. a JIRA project ID)."
- When a scope is in effect, it is a hard constraint inherited by every query and every Agent subprocess.
- File mode ignores scope (a bug-queue file is already project-local).

---

## WORKFLOW

<workflow>

<step n="1" goal="Validate the source is batchable and display the queue overview">

1. Resolve the bug source exactly as the single-bug workflow does (`auto`: platform_spec non-empty → platform; else
   bug_list_file exists → file). **Interactive is not batchable** — if neither platform nor file resolves, HALT:
   "Batch mode needs a queue: configure platform_spec or create {bug_list_file}. For a single described bug, use
   xiaoma-bug-resolve (BR)."
2. Query queue statistics (scope-filtered when in effect): pending / fixed / false-positive counts.
3. If pending == 0: go to Step 3 (final report).
4. List the pending bugs (ID, title, severity, module) oldest first.
5. Output the overview — include the scope line whenever a scope is in effect:

   ```text
   ===============================================
     Bug Resolve — Batch Mode
     (Agent Subprocess Isolation)
   ===============================================
   Scope: {scope or "—"}
   Pending: {pending} | Fixed: {fixed} | False-positive: {false_positive}

   Processing all {pending} bugs sequentially, each in an
   independent Agent subprocess. Starting now...
   -----------------------------------------------
   ```

6. Initialize tracking: `bugs_fixed` = 0, `bugs_false_positive` = 0, `bugs_failed` = 0, `failed_bug_keys` = [],
   `bug_results` = [].

</step>

<step n="2" goal="Loop: resolve each bug in an independent Agent subprocess (fully automatic)">

### 2.1 Find the Next Pending Bug

Query the queue fresh (scope-filtered when in effect), oldest first, skipping any key in `failed_bug_keys`. If no
processable bug remains, go to Step 3. Fetch the bug's complete record (platform detail fetch / full file entry).

Output: `Processing bug: {bug_key} — {title}`

### 2.2 Launch the Independent Agent Subprocess

<critical>

Use the Agent tool to launch a **general-purpose subprocess with FULL tool-execution capability** to resolve this bug.
This subprocess **MUST** have the complete tool set enabled — file read/write/edit, shell/command execution, and test
execution — because it runs the entire bug lifecycle (analyze → fix → verify → close). Do **NOT** delegate to a
restricted or read-only subagent (e.g. an explore-, plan-, or search-only type): such agents cannot edit files or run
commands, so the lifecycle would fail. When the host tool exposes a subagent-type selector, choose the type whose
toolset is the full/unrestricted set (in Claude Code this is the `general-purpose` type).

The Agent's prompt MUST contain, so it can work fully independently:

**1. Bug record:** every field fetched in 2.1 (ID, title, reproduction steps, error logs, module, page URL, severity,
type) — pass actual content, not references. **Plus the scope value as a hard constraint when in effect: every
platform query and status write-back must carry it.**

**2. Configuration (inline all resolved values):** `communication_language`, `document_output_language`,
`implementation_artifacts`, `max_fix_iterations`, `fix_report_subdir`, `test_url`, the resolved bug-source mode, and —
verbatim — `platform_spec` (platform mode) or the `bug_list_file` path (file mode).

**3. Procedure:** read `{single_bug_workflow}` and execute its Step 2 (root-cause analysis and verdict), Step 3 (fix —
real defects only), Step 4 (verify), and Step 5 items 1–3 ONLY (fix report, status write-back, closure summary — skip
items 4–5: queue reporting and `on_complete` belong to this scheduler). Intake (Step 1) is already done — the record
above is authoritative. Operating constraints:

- You are running unattended: never wait for a user. Where the single-bug workflow says "ask the user", instead record
  the gap; if the verdict cannot be reached without missing evidence, return verdict `blocked` — do NOT guess
- Fix strictly within the defect's scope; follow project conventions (CLAUDE.md, project-context.md)
- Track every file you modify. If you finish with verdict `blocked` or `failed`, restore the files you modified to
  their pre-run state (leave files that already had unrelated local changes alone) and say so in `error` — the next
  bug must start from a clean tree
- Write the fix report and execute the status write-back exactly as Step 5 specifies (status updates carry the scope
  when in effect)

**4. Project context:** include the content of `project-context.md` if it exists (actual content, not just the path),
plus the sibling `persistent_facts` resolved during INITIALIZATION (file contents inlined, literal entries verbatim).

**5. Return format** — when done, return exactly:

```text
BUG_RESULT:
- bug_key: {bug_key}
- verdict: fixed | false-positive | blocked | failed
- files_modified: [list of files, empty for false-positive/blocked]
- report_file: {path to the fix report, empty if not written}
- verification: {one-line verification outcome or gap}
- summary: {one-line description of what was done}
- error: {message if blocked/failed, empty otherwise}
```

</critical>

### 2.3 Read the Agent Result and Handle Errors

- `verdict: fixed` → increment `bugs_fixed`
- `verdict: false-positive` → increment `bugs_false_positive`
- `verdict: blocked`, `failed`, or no parseable BUG_RESULT → increment `bugs_failed`, append the bug key to
  `failed_bug_keys` (prevents re-selecting it this run — its source status stays pending, so a later run can retry),
  output `Bug {bug_key} blocked/failed — skipping and continuing.` — do NOT halt the batch
- Append the result to `bug_results`; output a one-line result for this bug

### 2.4 Refresh and Continue

Re-query the queue statistics (fresh, scope-filtered when in effect) and output a checkpoint:

```text
--- Batch checkpoint: fixed {bugs_fixed} | false-positive {bugs_false_positive} | failed {bugs_failed} | remaining {pending} ---
```

If a processable bug remains (pending minus `failed_bug_keys`): return to 2.1. Otherwise go to Step 3.

</step>

<step n="3" goal="Final report and machine-readable batch status">

1. Query the final queue state (scope-filtered when in effect).
2. Write `{batch_status_file}` atomically (write `.tmp`, then rename):

   ```json
   {
     "pipeline": "bug-resolve-batch",
     "date": "{date}",
     "scope": "{scope_or_empty}",
     "source_mode": "platform|file",
     "bugs_fixed": 0,
     "bugs_false_positive": 0,
     "bugs_failed": 0,
     "failed_bug_keys": [],
     "bug_results": [
       {
         "bug_key": "...",
         "verdict": "fixed|false-positive|blocked|failed",
         "files_modified": ["..."],
         "report_file": "...",
         "verification": "...",
         "summary": "...",
         "error": ""
       }
     ]
   }
   ```

   If the batch is halted early, still write this file — the partial run is auditable.

3. Output the final report:

   ```text
   ===============================================
     Bug Resolve Batch — COMPLETE
   ===============================================
   Scope: {scope or "—"}

   Fixed: {bugs_fixed}
   False-positive: {bugs_false_positive}
   Blocked/Failed (skipped, still pending at source): {bugs_failed}
   Remaining pending: {pending}

   Details:
   | Bug | Verdict | Files | Report |
   |-----|---------|-------|--------|
   | ... | ...     | ...   | ...    |

   Batch status: {batch_status_file}
   ===============================================
   ```

4. If `bugs_failed` > 0: list each failed/blocked bug with its `error` and what evidence or access would unblock it.
5. Execute `{workflow.on_complete}` if non-empty. **HALT** — batch complete.

</step>

</workflow>

---

## Important Notes

1. **Agent isolation is key** — each bug runs in an independent subprocess with isolated context; bugs never interfere
2. **Serial safety** — one bug at a time avoids concurrent modifications to the same codebase
3. **No infinite retries** — blocked/failed bugs go into `failed_bug_keys` and are skipped for the rest of THIS run;
   their source status remains pending so the next run (or a human) can pick them up with fresh context
4. **Scope discipline** — on shared defect platforms, running without the required scope would pull other projects'
   bugs and mis-edit code and statuses; that is why the platform spec can make scope mandatory
5. **Agent prompt quality** — each subprocess prompt must carry the complete bug record + resolved config + the
   platform spec or file path + the return format, so it can work with zero callbacks
