# Refactor sweep: research, scan, analysis, scoring and plan detail

<!-- toc -->
- [Plan bands](#plan-bands)
- [Step 0: best-practices research](#step-0-best-practices-research)
- [Step 0c: why the toolkit is in scope](#step-0c-why-the-toolkit-is-in-scope)
- [Step 0e: why a backlog band](#step-0e-why-a-backlog-band)
- [Step 1: scan checklist](#step-1-scan-checklist)
- [Step 2a: the 10 categories](#step-2a-the-10-categories)
- [Step 2b: bug hunt](#step-2b-bug-hunt)
- [Step 3: score table](#step-3-score-table)
- [Step 4: plan table](#step-4-plan-table)
- [Step 6: per-item loop](#step-6-per-item-loop)
- [Step 7: verify commands](#step-7-verify-commands)
- [Focus filter](#focus-filter)
<!-- /toc -->

Reference for `/multi-agent:refactor`. The command file carries the step skeleton and its hard rules; this file carries the procedures, output tables and catalogs each step points at.

## Plan bands

All bands feed the single Step 4 table:

- **A - Best-practice**: the best field approaches, adapted so they actually fit this repo.
- **B - Bug**: real defects found in the code (correctness, security, data-loss, crashes).
- **C - Improvement**: quality/perf/DX gaps surfaced by the 10-category analysis.
- **D - Drift**: upstream updates to skills we derived from an external source.
- **E - Dev-toolkit**: current-practice gaps in the companion multi-agent MCP server (the pipeline's device and browser hands), applied in that repo.
- **F - Run-errors**: recurring real failures the pipeline actually hit across past runs, read from the local run-error ledger. These are lived evidence, not speculation - a failure that recurs across users or tasks is a prioritized improvement area.
- **G - Backlog**: open observations recorded mid-task (Step 0e).

## Step 0: best-practices research

The goal is the best *approaches*, reshaped so they are applicable to THIS project's stack, size, and constraints.

1. **Identify the domain** of the current project (read README + package/build manifests): what kind of project is it (CLI, SDK, app, pipeline, library), what stack, who uses it.
2. **Research the best-in-class** for that exact domain. When `ai-analyst-toolkit` is enabled, run the first three bullets through its skills (`evidence-github`, `evidence-registry`, `signal-community`) rather than ad-hoc searching: they carry the query forms and the citation format, and they keep the evidence / signal line straight - a GitHub PR is a fact, a forum thread is one person's experience. Not enabled is a recorded no-op and the manual searches below still apply.
   - **GitHub**: search the domain terms + `stars:>50`; read the top repos' READMEs, architecture docs, CI configs, test layout.
   - **X / Twitter**: search the domain terms + "best practices" / "we switched to" / "lesson learned"; capture what practitioners and tool authors actually recommend right now (WebFetch/WebSearch on `x.com` / `twitter.com` threads).
   - **Reddit**: relevant subreddits for real-world pain points and adopted patterns.
   - **Web**: "<domain> best practices <current-year>", official style guides, and the platform's own guidance.
3. **For each candidate approach, record**:
   - what it is, who does it well (source link)
   - the concrete benefit
   - **adaptation**: exactly how it would look in OUR repo (which file/dir/script), and what has to change for it to fit - not a generic "add tests" but "add a flow-assertion helper in `test/helpers/`"
   - effort (Low/Med/High) and impact (Low/Med/High/Critical)
4. **Discard** approaches that do not fit our stack, our scale, or our constraints - and say WHY (so the user sees the filter working, not just the survivors).

Output (plan band A):

```
| Source | Approach | Adaptation to our repo | Effort | Impact | In plan? |
|--------|----------|------------------------|--------|--------|----------|
| <repo> | <what>   | <concrete change here> | Low    | High   | Yes (P1) |
| <repo> | <what>   | does not fit: <reason> | -      | -      | No       |
```

Roll the high-impact + low/med-effort survivors into the Step 4 plan as band-A items.

## Step 0c: why the toolkit is in scope

The pipeline's hands on devices and browsers are MCP tools served by a companion repo (`multi-agent-mcp`): Phase 3 test, `manual-test`, `design-check` and `apple-archive-compliance` all call them, and several pipeline skills declare a minimum toolkit version (see `cross-cli-contract.md`). That repo therefore has to track the MCP field, not just its own README. The procedure is `refactor/toolkit-research.md`.

## Step 0e: why a backlog band

Every other band derives its findings from scratch, which is right for a sweep and has one consequence: a friction noticed mid-task is gone by the next run unless it was fixed within the hour. Most are not, because stopping mid-task to fix them is the wrong call. So they are written down when noticed and decided here. Sibling surfaces matter because a command is authored in `commands/`, mirrored into `skills/shared/core/`, and installed again into three host trees, so a fix applied to one copy drifts from the rest with every gate still green.

## Step 1: scan checklist

```
- file count, LOC (cloc or wc -l)
- package.json / Package.swift / build.gradle analysis
- dependency count (runtime vs dev)
- Is there a CI/CD pipeline? (.github/workflows/, fastlane/, Makefile)
- Is there test infrastructure? How many tests? Coverage?
- Is a linter/formatter config in place?
- Do README, LICENSE, SECURITY.md, CHANGELOG.md exist?
- Git state: branch count, last commit date, tags
```

## Step 2a: the 10 categories

| # | Category | What to check |
|---|----------|---------------|
| 1 | **Architecture** | Layer separation, modularity, SOLID, dependency direction |
| 2 | **Code Quality** | Naming, magic numbers, dead code, complexity, DRY |
| 3 | **Security** | Hardcoded secrets, input validation, Keychain, ATS, ATT |
| 4 | **Tests** | Coverage, test pyramid, edge cases, mock/stub quality |
| 5 | **CI/CD** | Build matrix, lint job, release automation, artifact caching |
| 6 | **Docs** | README quality, JSDoc / Swift docs, API docs, CHANGELOG |
| 7 | **Performance** | Bundle size, lazy loading, memory leaks, unnecessary re-renders |
| 8 | **Accessibility** | a11y labels, tap targets, VoiceOver, Dynamic Type |
| 9 | **Dependency Management** | Outdated deps, vulnerability scan, lockfile, version pinning |
| 10 | **DevEx** | Onboarding time, script ergonomics, error messages, debug tooling |

## Step 2b: bug hunt

Dispatch focused review agents (Agent tool, `code-reviewer` persona where available) over the highest-risk surfaces: recently changed files, error/edge-path handling, concurrency, external input parsing, resource cleanup, off-by-one boundaries. For each candidate defect, record **file:line**, the concrete failure scenario (inputs/state -> wrong output/crash), and severity.

Output (plan band B) - every confirmed defect becomes a P0/P1 item:

```
| # | Severity | File:line | Defect | Failure scenario |
|---|----------|-----------|--------|------------------|
| 1 | Blocking | src/x.ts:42 | unchecked nil deref | empty response -> crash |
```

## Step 3: score table

```
+---------------------+-------+
| Category            | Score |
+---------------------+-------+
| Architecture        | 9/10  |
| Code Quality        | 8/10  |
| Security            | 9/10  |
| Tests               | 7/10  |
| CI/CD               | 8/10  |
| Docs                | 7/10  |
| Performance         | 9/10  |
| Accessibility       | 6/10  |
| Dependency Mgmt     | 8/10  |
| DevEx               | 9/10  |
+---------------------+-------+
| TOTAL               | 80/100|
+---------------------+-------+
```

## Step 4: plan table

```
| # | Priority | Band | Category | Item | Impact |
|---|----------|------|----------|------|--------|
| 1 | P0 | B | Security | Remove hardcoded API key (src/x:12) | Critical |
| 2 | P0 | B | Tests | Fix nil-deref on empty response (src/y:42) | High |
| 3 | P1 | A | CI/CD | Adopt matrix build (adapt: .github/workflows/ci.yml) | Medium |
| 4 | P1 | D | Skills | Port upstream <plugin> 0.3.0 fixes into <localPath> | Medium |
| 5 | P1 | E | Toolkit | Add read-only annotations to the multi-agent-mcp device tools | Medium |
| 6 | P2 | C | DevEx | Rename npm scripts for consistency | Low |
```

Priority levels:

- **P0**: bugs, security holes, broken functionality - must fix
- **P1**: clear quality improvement or high-value adopted best-practice / drift port - should be done
- **P2**: nice-to-have - if time allows

## Step 6: per-item loop

1. For each item:
   - apply the change (for band D, port the upstream diff into `localPath`, then bump that entry's `derivedFromVersion` in preferences)
   - band-E items are applied inside the toolkit repo, never mirrored here: edit there, re-run its gates (`node --check`, the `tools/list` handshake, advertised tool count matching reality), then commit there with that repo's own convention. Publishing is `/multi-agent:sync` Step 3d - do not publish from this step.
   - run the relevant tests
   - on success, move to the next
   - on failure, roll back and notify the user
2. After all changes are done: run the full lint + test suite; on success, commit.

## Step 7: verify commands

```bash
# Lint
npm run lint 2>/dev/null || swift build 2>/dev/null

# Test
npm test 2>/dev/null || swift test 2>/dev/null || xcodebuild test 2>/dev/null

# Result
echo "Lint: PASS/FAIL"
echo "Test: PASS/FAIL (X/Y passed)"
```

If any band-E item was applied, verify the toolkit repo too - syntax check every file it loads, handshake the server and confirm `tools/list` still answers, and confirm the advertised tool counts (README header, `package.json` description) match the count the server reports.

## Focus filter

| Input | Focus |
|-------|-------|
| `backlog` | Backlog band only (band G, Step 0e) |
| `bugs` | Bug hunt only (band B) |
| `best-practices` | Field research + adapted plan only (band A) |
| `drift` | Upstream derived-skill drift only (band D) |
| `multi-agent-mcp` | Companion MCP toolkit research + audit only (band E) |
| `run-errors` | Run-error ledger only (band F) |
| `security` | Security analysis only |
| `tests` | Test coverage and quality only |
| `performance` | Performance optimisation only |
| `docs` | Docs only |
| `ci` | CI/CD pipeline only |
| `deps` | Dependency updates only |
| (empty) | Everything (default) |
