export declare const REFACTOR_TEMPLATE = "# Intelligent Refactor Command\n\n## Usage\n```\n/refactor <refactoring-target> [--scope=<file|module|project>] [--strategy=<safe|aggressive>]\n\nArguments:\n  refactoring-target: What to refactor. Can be:\n    - File path: src/auth/handler.ts\n    - Symbol name: \"AuthService class\"\n    - Pattern: \"all functions using deprecated API\"\n    - Description: \"extract validation logic into separate module\"\n\nOptions:\n  --scope: Refactoring scope (default: module)\n    - file: Single file only\n    - module: Module/directory scope\n    - project: Entire codebase\n\n  --strategy: Risk tolerance (default: safe)\n    - safe: Conservative, maximum test coverage required\n    - aggressive: Allow broader changes with adequate coverage\n```\n\n## What This Command Does\n\nPerforms intelligent, deterministic refactoring with full codebase awareness. Unlike blind search-and-replace, this command:\n\n1. **Understands your intent** - Analyzes what you actually want to achieve\n2. **Maps the codebase** - Builds a definitive codemap before touching anything\n3. **Assesses risk** - Evaluates test coverage and determines verification strategy\n4. **Plans meticulously** - Creates a detailed plan with Plan agent\n5. **Executes precisely** - Step-by-step refactoring with LSP and AST-grep\n6. **Verifies constantly** - Runs tests after each change to ensure zero regression\n\n---\n\n# PHASE 0: INTENT GATE (MANDATORY FIRST STEP)\n\n**BEFORE ANY ACTION, classify and validate the request.**\n\n## Step 0.1: Parse Request Type\n\n| Signal | Classification | Action |\n|--------|----------------|--------|\n| Specific file/symbol | Explicit | Proceed to codebase analysis |\n| \"Refactor X to Y\" | Clear transformation | Proceed to codebase analysis |\n| \"Improve\", \"Clean up\" | Open-ended | **MUST ask**: \"What specific improvement?\" |\n| Ambiguous scope | Uncertain | **MUST ask**: \"Which modules/files?\" |\n| Missing context | Incomplete | **MUST ask**: \"What's the desired outcome?\" |\n\n## Step 0.2: Validate Understanding\n\nBefore proceeding, confirm:\n- [ ] Target is clearly identified\n- [ ] Desired outcome is understood\n- [ ] Scope is defined (file/module/project)\n- [ ] Success criteria can be articulated\n\n**If ANY of above is unclear, ASK CLARIFYING QUESTION:**\n\n```\nI want to make sure I understand the refactoring goal correctly.\n\n**What I understood**: [interpretation]\n**What I'm unsure about**: [specific ambiguity]\n\nOptions I see:\n1. [Option A] - [implications]\n2. [Option B] - [implications]\n\n**My recommendation**: [suggestion with reasoning]\n\nShould I proceed with [recommendation], or would you prefer differently?\n```\n\n## Step 0.3: Create Initial Todos\n\n**IMMEDIATELY after understanding the request, create todos:**\n\n```\nTodoWrite([\n  {\"id\": \"phase-1\", \"content\": \"PHASE 1: Codebase Analysis - launch parallel explore agents\", \"status\": \"pending\", \"priority\": \"high\"},\n  {\"id\": \"phase-2\", \"content\": \"PHASE 2: Build Codemap - map dependencies and impact zones\", \"status\": \"pending\", \"priority\": \"high\"},\n  {\"id\": \"phase-3\", \"content\": \"PHASE 3: Test Assessment - analyze test coverage and verification strategy\", \"status\": \"pending\", \"priority\": \"high\"},\n  {\"id\": \"phase-4\", \"content\": \"PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan\", \"status\": \"pending\", \"priority\": \"high\"},\n  {\"id\": \"phase-5\", \"content\": \"PHASE 5: Execute Refactoring - step-by-step with continuous verification\", \"status\": \"pending\", \"priority\": \"high\"},\n  {\"id\": \"phase-6\", \"content\": \"PHASE 6: Final Verification - full test suite and regression check\", \"status\": \"pending\", \"priority\": \"high\"}\n])\n```\n\n---\n\n# PHASE 1: CODEBASE ANALYSIS (PARALLEL EXPLORATION)\n\n**Mark phase-1 as in_progress.**\n\n## 1.1: Launch Parallel Explore Agents (BACKGROUND)\n\nFire ALL of these simultaneously using `call_omo_agent`:\n\n```\n// Agent 1: Find the refactoring target\ncall_omo_agent(\n  subagent_type=\"explore\",\n  run_in_background=true,\n  prompt=\"Find all occurrences and definitions of [TARGET]. \n  Report: file paths, line numbers, usage patterns.\"\n)\n\n// Agent 2: Find related code\ncall_omo_agent(\n  subagent_type=\"explore\", \n  run_in_background=true,\n  prompt=\"Find all code that imports, uses, or depends on [TARGET].\n  Report: dependency chains, import graphs.\"\n)\n\n// Agent 3: Find similar patterns\ncall_omo_agent(\n  subagent_type=\"explore\",\n  run_in_background=true,\n  prompt=\"Find similar code patterns to [TARGET] in the codebase.\n  Report: analogous implementations, established conventions.\"\n)\n\n// Agent 4: Find tests\ncall_omo_agent(\n  subagent_type=\"explore\",\n  run_in_background=true,\n  prompt=\"Find all test files related to [TARGET].\n  Report: test file paths, test case names, coverage indicators.\"\n)\n\n// Agent 5: Architecture context\ncall_omo_agent(\n  subagent_type=\"explore\",\n  run_in_background=true,\n  prompt=\"Find architectural patterns and module organization around [TARGET].\n  Report: module boundaries, layer structure, design patterns in use.\"\n)\n```\n\n## 1.2: Direct Tool Exploration (WHILE AGENTS RUN)\n\nWhile background agents are running, use direct tools:\n\n### LSP Tools for Precise Analysis:\n\n```typescript\n// Find definition(s)\nLspGotoDefinition(filePath, line, character)  // Where is it defined?\n\n// Find ALL usages across workspace\nLspFindReferences(filePath, line, character, includeDeclaration=true)\n\n// Get file structure\nLspDocumentSymbols(filePath)  // Hierarchical outline\nLspWorkspaceSymbols(filePath, query=\"[target_symbol]\")  // Search by name\n\n// Get current diagnostics\nlsp_diagnostics(filePath)  // Errors, warnings before we start\n```\n\n### AST-Grep for Pattern Analysis:\n\n```typescript\n// Find structural patterns\nast_grep_search(\n  pattern=\"function $NAME($$$) { $$$ }\",  // or relevant pattern\n  lang=\"typescript\",  // or relevant language\n  paths=[\"src/\"]\n)\n\n// Preview refactoring (DRY RUN)\nast_grep_replace(\n  pattern=\"[old_pattern]\",\n  rewrite=\"[new_pattern]\",\n  lang=\"[language]\",\n  dryRun=true  // ALWAYS preview first\n)\n```\n\n### Grep for Text Patterns:\n\n```\ngrep(pattern=\"[search_term]\", path=\"src/\", include=\"*.ts\")\n```\n\n## 1.3: Collect Background Results\n\n```\nbackground_output(task_id=\"[agent_1_id]\")\nbackground_output(task_id=\"[agent_2_id]\")\n...\n```\n\n**Mark phase-1 as completed after all results collected.**\n\n---\n\n# PHASE 2: BUILD CODEMAP (DEPENDENCY MAPPING)\n\n**Mark phase-2 as in_progress.**\n\n## 2.1: Construct Definitive Codemap\n\nBased on Phase 1 results, build:\n\n```\n## CODEMAP: [TARGET]\n\n### Core Files (Direct Impact)\n- `path/to/file.ts:L10-L50` - Primary definition\n- `path/to/file2.ts:L25` - Key usage\n\n### Dependency Graph\n```\n[TARGET] \n\u251C\u2500\u2500 imports from: \n\u2502   \u251C\u2500\u2500 module-a (types)\n\u2502   \u2514\u2500\u2500 module-b (utils)\n\u251C\u2500\u2500 imported by:\n\u2502   \u251C\u2500\u2500 consumer-1.ts\n\u2502   \u251C\u2500\u2500 consumer-2.ts\n\u2502   \u2514\u2500\u2500 consumer-3.ts\n\u2514\u2500\u2500 used by:\n    \u251C\u2500\u2500 handler.ts (direct call)\n    \u2514\u2500\u2500 service.ts (dependency injection)\n```\n\n### Impact Zones\n| Zone | Risk Level | Files Affected | Test Coverage |\n|------|------------|----------------|---------------|\n| Core | HIGH | 3 files | 85% covered |\n| Consumers | MEDIUM | 8 files | 70% covered |\n| Edge | LOW | 2 files | 50% covered |\n\n### Established Patterns\n- Pattern A: [description] - used in N places\n- Pattern B: [description] - established convention\n```\n\n## 2.2: Identify Refactoring Constraints\n\nBased on codemap:\n- **MUST follow**: [existing patterns identified]\n- **MUST NOT break**: [critical dependencies]\n- **Safe to change**: [isolated code zones]\n- **Requires migration**: [breaking changes impact]\n\n**Mark phase-2 as completed.**\n\n---\n\n# PHASE 3: TEST ASSESSMENT (VERIFICATION STRATEGY)\n\n**Mark phase-3 as in_progress.**\n\n## 3.1: Detect Test Infrastructure\n\n```bash\n# Check for test commands\ncat package.json | jq '.scripts | keys[] | select(test(\"test\"))'\n\n# Or for Python\nls -la pytest.ini pyproject.toml setup.cfg\n\n# Or for Go\nls -la *_test.go\n```\n\n## 3.2: Analyze Test Coverage\n\n```\n// Find all tests related to target\ncall_omo_agent(\n  subagent_type=\"explore\",\n  run_in_background=false,  // Need this synchronously\n  prompt=\"Analyze test coverage for [TARGET]:\n  1. Which test files cover this code?\n  2. What test cases exist?\n  3. Are there integration tests?\n  4. What edge cases are tested?\n  5. Estimated coverage percentage?\"\n)\n```\n\n## 3.3: Determine Verification Strategy\n\nBased on test analysis:\n\n| Coverage Level | Strategy |\n|----------------|----------|\n| HIGH (>80%) | Run existing tests after each step |\n| MEDIUM (50-80%) | Run tests + add safety assertions |\n| LOW (<50%) | **PAUSE**: Propose adding tests first |\n| NONE | **BLOCK**: Refuse aggressive refactoring |\n\n**If coverage is LOW or NONE, ask user:**\n\n```\nTest coverage for [TARGET] is [LEVEL].\n\n**Risk Assessment**: Refactoring without adequate tests is dangerous.\n\nOptions:\n1. Add tests first, then refactor (RECOMMENDED)\n2. Proceed with extra caution, manual verification required\n3. Abort refactoring\n\nWhich approach do you prefer?\n```\n\n## 3.4: Document Verification Plan\n\n```\n## VERIFICATION PLAN\n\n### Test Commands\n- Unit: `bun test` / `npm test` / `pytest` / etc.\n- Integration: [command if exists]\n- Type check: `tsc --noEmit` / `pyright` / etc.\n\n### Verification Checkpoints\nAfter each refactoring step:\n1. lsp_diagnostics \u2192 zero new errors\n2. Run test command \u2192 all pass\n3. Type check \u2192 clean\n\n### Regression Indicators\n- [Specific test that must pass]\n- [Behavior that must be preserved]\n- [API contract that must not change]\n```\n\n**Mark phase-3 as completed.**\n\n---\n\n# PHASE 4: PLAN GENERATION (PLAN AGENT)\n\n**Mark phase-4 as in_progress.**\n\n## 4.1: Invoke Plan Agent\n\n```\nTask(\n  subagent_type=\"plan\",\n  prompt=\"Create a detailed refactoring plan:\n\n  ## Refactoring Goal\n  [User's original request]\n\n  ## Codemap (from Phase 2)\n  [Insert codemap here]\n\n  ## Test Coverage (from Phase 3)\n  [Insert verification plan here]\n\n  ## Constraints\n  - MUST follow existing patterns: [list]\n  - MUST NOT break: [critical paths]\n  - MUST run tests after each step\n\n  ## Requirements\n  1. Break down into atomic refactoring steps\n  2. Each step must be independently verifiable\n  3. Order steps by dependency (what must happen first)\n  4. Specify exact files and line ranges for each step\n  5. Include rollback strategy for each step\n  6. Define commit checkpoints\"\n)\n```\n\n## 4.2: Review and Validate Plan\n\nAfter receiving plan from Plan agent:\n\n1. **Verify completeness**: All identified files addressed?\n2. **Verify safety**: Each step reversible?\n3. **Verify order**: Dependencies respected?\n4. **Verify verification**: Test commands specified?\n\n## 4.3: Register Detailed Todos\n\nConvert Plan agent output into granular todos:\n\n```\nTodoWrite([\n  // Each step from the plan becomes a todo\n  {\"id\": \"refactor-1\", \"content\": \"Step 1: [description]\", \"status\": \"pending\", \"priority\": \"high\"},\n  {\"id\": \"verify-1\", \"content\": \"Verify Step 1: run tests\", \"status\": \"pending\", \"priority\": \"high\"},\n  {\"id\": \"refactor-2\", \"content\": \"Step 2: [description]\", \"status\": \"pending\", \"priority\": \"medium\"},\n  {\"id\": \"verify-2\", \"content\": \"Verify Step 2: run tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n  // ... continue for all steps\n])\n```\n\n**Mark phase-4 as completed.**\n\n---\n\n# PHASE 5: EXECUTE REFACTORING (DETERMINISTIC EXECUTION)\n\n**Mark phase-5 as in_progress.**\n\n## 5.1: Execution Protocol\n\nFor EACH refactoring step:\n\n### Pre-Step\n1. Mark step todo as `in_progress`\n2. Read current file state\n3. Verify lsp_diagnostics is baseline\n\n### Execute Step\nUse appropriate tool:\n\n**For Symbol Renames:**\n```typescript\nlsp_prepare_rename(filePath, line, character)  // Validate rename is possible\nlsp_rename(filePath, line, character, newName)  // Execute rename\n```\n\n**For Pattern Transformations:**\n```typescript\n// Preview first\nast_grep_replace(pattern, rewrite, lang, dryRun=true)\n\n// If preview looks good, execute\nast_grep_replace(pattern, rewrite, lang, dryRun=false)\n```\n\n**For Structural Changes:**\n```typescript\n// Use Edit tool for precise changes\nedit(filePath, oldString, newString)\n```\n\n### Post-Step Verification (MANDATORY)\n\n```typescript\n// 1. Check diagnostics\nlsp_diagnostics(filePath)  // Must be clean or same as baseline\n\n// 2. Run tests\nbash(\"bun test\")  // Or appropriate test command\n\n// 3. Type check\nbash(\"tsc --noEmit\")  // Or appropriate type check\n```\n\n### Step Completion\n1. If verification passes \u2192 Mark step todo as `completed`\n2. If verification fails \u2192 **STOP AND FIX**\n\n## 5.2: Failure Recovery Protocol\n\nIf ANY verification fails:\n\n1. **STOP** immediately\n2. **REVERT** the failed change\n3. **DIAGNOSE** what went wrong\n4. **OPTIONS**:\n   - Fix the issue and retry\n   - Skip this step (if optional)\n   - Consult oracle agent for help\n   - Ask user for guidance\n\n**NEVER proceed to next step with broken tests.**\n\n## 5.3: Commit Checkpoints\n\nAfter each logical group of changes:\n\n```bash\ngit add [changed-files]\ngit commit -m \"refactor(scope): description\n\n[details of what was changed and why]\"\n```\n\n**Mark phase-5 as completed when all refactoring steps done.**\n\n---\n\n# PHASE 6: FINAL VERIFICATION (REGRESSION CHECK)\n\n**Mark phase-6 as in_progress.**\n\n## 6.1: Full Test Suite\n\n```bash\n# Run complete test suite\nbun test  # or npm test, pytest, go test, etc.\n```\n\n## 6.2: Type Check\n\n```bash\n# Full type check\ntsc --noEmit  # or equivalent\n```\n\n## 6.3: Lint Check\n\n```bash\n# Run linter\neslint .  # or equivalent\n```\n\n## 6.4: Build Verification (if applicable)\n\n```bash\n# Ensure build still works\nbun run build  # or npm run build, etc.\n```\n\n## 6.5: Final Diagnostics\n\n```typescript\n// Check all changed files\nfor (file of changedFiles) {\n  lsp_diagnostics(file)  // Must all be clean\n}\n```\n\n## 6.6: Generate Summary\n\n```markdown\n## Refactoring Complete\n\n### What Changed\n- [List of changes made]\n\n### Files Modified\n- `path/to/file.ts` - [what changed]\n- `path/to/file2.ts` - [what changed]\n\n### Verification Results\n- Tests: PASSED (X/Y passing)\n- Type Check: CLEAN\n- Lint: CLEAN\n- Build: SUCCESS\n\n### No Regressions Detected\nAll existing tests pass. No new errors introduced.\n```\n\n**Mark phase-6 as completed.**\n\n---\n\n# CRITICAL RULES\n\n## NEVER DO\n- Skip lsp_diagnostics check after changes\n- Proceed with failing tests\n- Make changes without understanding impact\n- Use `as any`, `@ts-ignore`, `@ts-expect-error`\n- Delete tests to make them pass\n- Commit broken code\n- Refactor without understanding existing patterns\n\n## ALWAYS DO\n- Understand before changing\n- Preview before applying (ast_grep dryRun=true)\n- Verify after every change\n- Follow existing codebase patterns\n- Keep todos updated in real-time\n- Commit at logical checkpoints\n- Report issues immediately\n\n## ABORT CONDITIONS\nIf any of these occur, **STOP and consult user**:\n- Test coverage is zero for target code\n- Changes would break public API\n- Refactoring scope is unclear\n- 3 consecutive verification failures\n- User-defined constraints violated\n\n---\n\n# Tool Usage Philosophy\n\nYou already know these tools. Use them intelligently:\n\n## LSP Tools\nLeverage LSP tools for precision analysis. Key patterns:\n- **Understand before changing**: `LspGotoDefinition` to grasp context\n- **Impact analysis**: `LspFindReferences` to map all usages before modification\n- **Safe refactoring**: `lsp_prepare_rename` \u2192 `lsp_rename` for symbol renames\n- **Continuous verification**: `lsp_diagnostics` after every change\n\n## AST-Grep\nUse `ast_grep_search` and `ast_grep_replace` for structural transformations.\n**Critical**: Always `dryRun=true` first, review, then execute.\n\n## Agents\n- `explore`: Parallel codebase pattern discovery\n- `plan`: Detailed refactoring plan generation\n- `oracle`: Read-only consultation for complex architectural decisions and debugging\n- `librarian`: **Use proactively** when encountering deprecated methods or library migration tasks. Query official docs and OSS examples for modern replacements.\n\n## Deprecated Code & Library Migration\nWhen you encounter deprecated methods/APIs during refactoring:\n1. Fire `librarian` to find the recommended modern alternative\n2. **DO NOT auto-upgrade to latest version** unless user explicitly requests migration\n3. If user requests library migration, use `librarian` to fetch latest API docs before making changes\n\n---\n\n**Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.**\n\n<user-request>\n$ARGUMENTS\n</user-request>\n";
export declare const REFACTOR_TEAM_MODE_ADDENDUM = "\n---\n\n# Team Mode Protocol (active when team_* tools are present)\n\nTeam mode is enabled for this session. The rules below **override Phase 4-6** above. Follow this protocol instead of the in-session step-by-step execution.\n\n## Phase 4 override: Plan agent staffing requirement\n\nWhen invoking the Plan agent in Phase 4.1, append this additional requirement to the prompt:\n\n```\n7. (REQUIRED when team mode is active) Output a Team Staffing Recommendation section with these fields \u2014 missing fields fail Phase 5.0:\n   - total_atomic_steps: integer\n   - file_independent_steps: integer (parallelizable, no cross-file blocker)\n   - cross_file_dependent_steps: integer (has blockers)\n   - per_step_assignment: [{step_id, assigned_to: 'quick' | 'unspecified-low', blockedBy: [step_ids], rationale}]\n   - dispatch_path_recommendation: 'team' | 'legacy' with reason\n   - rationale for the composition\n```\n\n**Classification rules** the plan agent must apply to each step:\n- `quick`: mechanical edits \u2014 LSP rename, extract variable, inline, simple move, signature change without call-site logic.\n- `unspecified-low`: logic-preserving refactors that need reasoning \u2014 extract function, restructure conditional, pattern transformation, cross-file API change.\n- Recommend `team` path when `file_independent_steps >= 3`; recommend `legacy` otherwise.\n\n## Phase 5 override: Dispatch path selection\n\nRead the Team Staffing Recommendation from Phase 4. If any required field is missing, fail here and re-request the plan with the exact missing field names. Do not proceed with a partial plan.\n\nThen choose the path:\n\n- **Team path (5.1-T)**: when the plan recommends `team` AND `file_independent_steps >= 3`. Members execute in parallel, Lead orchestrates, a `deep` verifier lives outside the team.\n- **Legacy path (5.1-L)**: otherwise. Use the original 5.1 / 5.2 / 5.3 flow from above.\n\nRecord the chosen path in the TodoWrite list.\n\n## Phase 5.1-T: `refactor-squad` team execution\n\n**Precondition checks** (fail hard if any step fails):\n\n1. Load the `team-mode` skill via the `skill` tool for lifecycle, message protocol, and limits.\n2. Call `team_list` and verify no active `refactor-squad` run exists; if one does, shutdown + delete the orphan before proceeding.\n3. If `~/.omo/teams/refactor-squad/config.json` is missing, write it using the spec below.\n\n**Team spec** (`~/.omo/teams/refactor-squad/config.json`):\n\n```json\n{\n  \"name\": \"refactor-squad\",\n  \"lead\": { \"kind\": \"subagent_type\", \"subagent_type\": \"sisyphus\" },\n  \"members\": [\n    {\n      \"kind\": \"category\",\n      \"category\": \"quick\",\n      \"prompt\": \"You handle mechanical refactoring steps (LSP rename, extract variable, inline, simple move, signature change). Use LSP tools for correctness. Apply the task description's per-step instructions verbatim \u2014 no scope expansion. After edits, run lsp_diagnostics on touched files. Report via team_send_message(teamRunId=<id>, to=\"lead\", summary=<files touched>, body=<lsp status + diff summary>) + team_task_update(status=completed). Never run tests \u2014 the external verifier handles that. Never git add, never --continue.\"\n    },\n    { \"kind\": \"category\", \"category\": \"quick\", \"prompt\": \"Same contract as peer quick worker.\" },\n    {\n      \"kind\": \"category\",\n      \"category\": \"unspecified-low\",\n      \"prompt\": \"You handle logic-preserving refactors that need reasoning (extract function, restructure conditional, pattern transformation, cross-file API change). Read the task description's plan step carefully. Use ast_grep_replace with dryRun=true first, review the preview, then execute. If the step is ambiguous or would require out-of-scope changes, STOP and send team_send_message(teamRunId=<id>, to=\"lead\", summary=\"UNCLEAR\", body=<reason>) + team_task_update(status=pending). Same reporting contract as peer quick workers. Never run tests.\"\n    },\n    { \"kind\": \"category\", \"category\": \"unspecified-low\", \"prompt\": \"Same contract as peer unspecified-low worker.\" }\n  ]\n}\n```\n\nRationale for this composition:\n- **4 workers = team mode's parallel cap.** 5+ just queues.\n- **No verifier team member.** Verification needs `deep` reasoning (or `unspecified-high` fallback). In-team category routing downcasts to sisyphus-junior, which is weaker than required \u2014 the verifier runs OUTSIDE the team as a `task(category=\"deep\")`.\n- **quick \u00D7 2** for mechanical edits, **unspecified-low \u00D7 2** for reasoning edits \u2014 mirrors the plan's split.\n\n**Team lifecycle** (one team, reused until Phase 6 cleanup):\n\n1. `team_create(teamName=\"refactor-squad\")`. Record `teamRunId`.\n2. Broadcast the refactor Intent Card ONCE (keep task descriptions slim):\n   ```\n   team_send_message(\n     teamRunId=<id>, to=\"*\", kind=\"announcement\",\n     summary=\"refactor-intent\",\n     body=<codemap summary + constraints + established patterns from Phase 2>\n   )\n   ```\n3. Broadcast the verification spec ONCE:\n   ```\n   team_send_message(\n     teamRunId=<id>, to=\"*\", kind=\"announcement\",\n     summary=\"verify-spec\",\n     body=<exact test/typecheck/lint commands + expected pass counts + regression indicators from Phase 3.4>\n   )\n   ```\n4. For each plan step, `team_task_create(teamRunId=<id>, subject=\"refactor step <N>: <short>\", description=<per-step instructions from plan, including target files and line ranges, rollback strategy>, blockedBy=<from plan's per_step_assignment>)`.\n\n**Lead monitoring loop**:\n\nWhile any team task is `pending | claimed | in_progress`:\n\n- Wait for `<system-reminder>` or member messages. Avoid tight polling; a single `team_status` check is acceptable if no notification arrives within roughly 10 seconds of expected completion.\n- On a worker completion report, immediately dispatch an **external verifier** \u2014 verification runs OUTSIDE the team because team-member category routing downcasts to sisyphus-junior:\n  ```\n  task(\n    category=\"deep\",\n    load_skills=[],\n    run_in_background=true,\n    description=\"verify step <N>\",\n    prompt=<files touched + verify-spec commands + instruction to return \"PASS\" or \"FAIL:<failing test + specific error + suggested revert hunks>\">\n  )\n  ```\n  If `deep` is unavailable, fall back to `category=\"unspecified-high\"`. Do not create a commit checkpoint until the verifier returns PASS.\n- On a verifier PASS: make the commit checkpoint for that step (see original 5.3). Proceed.\n- On a verifier FAIL: Lead decides:\n  - **Retry with fix hint**: `team_task_update(status=pending)` on the original step + `team_send_message(teamRunId=<id>, to=<original member>, summary=\"retry\", body=<specific failure from verifier>)`. Runtime reassigns.\n  - **Escalate**: after three FAIL cycles on the same step, STOP and consult the user with full evidence.\n- On a member UNCLEAR message: re-harvest context via a targeted `task()` outside the team, broadcast an updated Intent Card fragment, then reassign.\n\nProceed to Phase 6 only when every team task is `completed` AND every paired verifier task returned PASS.\n\n## Phase 6 override: Team cleanup before summary\n\nIf Phase 5 used the team path, dismantle `refactor-squad` BEFORE producing the 6.6 summary. Every exit path \u2014 success, escalation, abort \u2014 must cleanup; orphan teams poison the next session's precondition check.\n\n1. `team_shutdown_request` for each member, then `team_approve_shutdown` if members do not self-approve within a reasonable window.\n2. `team_delete(teamRunId=<id>)`.\n3. `team_list` to confirm no residual `refactor-squad` run.\n\nThe `~/.omo/teams/refactor-squad/config.json` declaration stays on disk; next session reuses it.\n\nAppend to the 6.6 summary a \"Dispatch path\" line and, when team path was used, team metrics (teamRunId, tasks created, verifier runs, team lifetime).\n\n## MUST NOT (team mode)\n\n- Lead never edits files directly \u2014 orchestrate only.\n- Do not inline the Intent Card or verify-spec into task descriptions \u2014 rely on the broadcasts.\n- Do not recreate the team mid-session.\n- Do not run tests from Lead \u2014 the external verifier owns that lane.\n- Do not put `oracle` / `librarian` / `deep` into the team spec \u2014 oracle/librarian are team-ineligible, and `deep` under category routing downcasts to sisyphus-junior. Use them via `task()` outside the team when needed.\n";
