---
name: cancel
description: 取消任何处于活动状态的 OMC 模式（autopilot、ralph、ultrawork、ultraqa、swarm、ultrapilot、pipeline、team）
level: 2
---

# 取消技能

智能取消机制，可检测并取消当前活动的 OMC 模式。

**cancel 技能是完成并退出任何 OMC 模式的标准方式。**
当 stop hook 检测到工作已完成时，它会指示 LLM 调用
此技能，以便正确清理状态。如果 cancel 失败或被中断，
请重试并使用 `--force` 标志，或者在万不得已时等待 2 小时的陈旧超时。

## 它的作用

自动检测当前处于活动状态的模式并取消它：
- **Autopilot**: 停止工作流，保留进度以便恢复
- **Ralph**: 停止持久化循环，并在适用时清理关联的 ultrawork
- **Ultrawork**: 停止并行执行（独立或关联模式）
- **UltraQA**: 停止 QA 循环工作流
- **Swarm**: 停止协同代理 swarm，并释放已认领的任务
- **Ultrapilot**: 停止并行 autopilot workers
- **Pipeline**: 停止顺序代理流水线
- **Team**: 向所有队友发送 shutdown_request，等待响应，调用 TeamDelete，并在存在关联 ralph 时一并清理
- **Team+Ralph (linked)**: 先取消 team（优雅关闭），然后清理 ralph 状态。当 ralph 处于关联状态时取消它，也会先取消 team。

## 用法

```
/oh-my-claudecode:cancel
```

或者说："cancelomc"、"stopomc"

## 关键：延迟工具处理

状态管理工具（`state_clear`、`state_read`、`state_write`、`state_list_active`、
`state_get_status`）可能会被 Claude Code 注册为**延迟工具**。在调用
任何状态工具之前，你**必须**先通过 `ToolSearch` 加载它们全部：

```
ToolSearch(query="select:mcp__plugin_oh-my-claudecode_t__state_clear,mcp__plugin_oh-my-claudecode_t__state_read,mcp__plugin_oh-my-claudecode_t__state_write,mcp__plugin_oh-my-claudecode_t__state_list_active,mcp__plugin_oh-my-claudecode_t__state_get_status")
```

如果 `state_clear` 不可用或调用失败，请使用这个 **bash fallback** 作为
**从 stop hook 循环中紧急脱困** 的手段。这**不是** cancel 流程的完整替代方案，
它只会删除状态文件以解除当前会话阻塞。关联模式（例如 ralph→ultrawork、
autopilot→ralph/ultraqa）必须分别清理，即每个模式各运行一次 fallback。

将 `MODE` 替换为具体的模式（例如 `ralplan`、`ralph`、`ultrawork`、`ultraqa`）。

**警告：** 不要将此 fallback 用于 `autopilot` 或 `omc-teams`。Autopilot 需要
通过 `state_write(active=false)` 保留恢复数据。omc-teams 需要清理 tmux session，
这无法仅靠删除文件完成。

```bash
# Fallback: direct file removal when state_clear MCP tool is unavailable
SESSION_ID="${CLAUDE_SESSION_ID:-${CLAUDECODE_SESSION_ID:-}}"
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || { d="$PWD"; while [ "$d" != "/" ] && [ ! -d "$d/.omc" ]; do d="$(dirname "$d")"; done; echo "$d"; })"

# Cross-platform SHA-256 (macOS: shasum, Linux: sha256sum)
sha256portable() { printf '%s' "$1" | (sha256sum 2>/dev/null || shasum -a 256) | cut -c1-16; }

# Resolve state directory (supports OMC_STATE_DIR centralized storage)
if [ -n "${OMC_STATE_DIR:-}" ]; then
  # Mirror getProjectIdentifier() from worktree-paths.ts
  SOURCE="$(git remote get-url origin 2>/dev/null || echo "$REPO_ROOT")"
  HASH="$(sha256portable "$SOURCE")"
  DIR_NAME="$(basename "$REPO_ROOT" | sed 's/[^a-zA-Z0-9_-]/_/g')"
  OMC_STATE="$OMC_STATE_DIR/${DIR_NAME}-${HASH}/state"
  [ ! -d "$OMC_STATE" ] && { echo "ERROR: State dir not found at $OMC_STATE" >&2; exit 1; }
elif [ "$REPO_ROOT" != "/" ] && [ -d "$REPO_ROOT/.omc" ]; then
  OMC_STATE="$REPO_ROOT/.omc/state"
else
  echo "ERROR: Could not locate .omc state directory" >&2
  exit 1
fi
MODE="ralplan"  # <-- replace with the target mode

# Clear session-scoped state for the specific mode
if [ -n "$SESSION_ID" ] && [ -d "$OMC_STATE/sessions/$SESSION_ID" ]; then
  rm -f "$OMC_STATE/sessions/$SESSION_ID/${MODE}-state.json"
  rm -f "$OMC_STATE/sessions/$SESSION_ID/${MODE}-stop-breaker.json"
  # Write cancel signal so stop hook detects cancellation in progress
  NOW_ISO="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
  printf '{"active":true,"requested_at":"%s","mode":"%s","source":"bash_fallback"}' \
    "$NOW_ISO" "$MODE" > "$OMC_STATE/sessions/$SESSION_ID/cancel-signal-state.json"
fi

# Clear legacy state only if no session ID (avoid clearing another session's state)
if [ -z "$SESSION_ID" ]; then
  rm -f "$OMC_STATE/${MODE}-state.json"
fi
```

## 自动检测

`/oh-my-claudecode:cancel` 遵循会话感知的状态契约：
- 默认情况下，该命令会通过 `state_list_active` 和 `state_get_status` 检查当前会话，遍历 `.omc/state/sessions/{sessionId}/…` 以发现哪个模式处于活动状态。
- 当提供了 session id 或已知 session id 时，该会话作用域路径是权威来源。只有在 session id 缺失或为空时，才会将 `.omc/state/*.json` 中的旧版文件作为兼容性 fallback 进行查询。
- Swarm 是共享的 SQLite/marker 模式（`.omc/state/swarm.db` / `.omc/state/swarm-active.marker`），不属于 session-scoped。
- 默认清理流程会携带 session id 调用 `state_clear`，仅移除匹配当前会话的文件；各模式保持绑定在其原始会话上。

活动模式仍按依赖顺序取消：
1. Autopilot（包含关联的 ralph/ultraqa/ 清理）
2. Ralph（清理其关联的 ultrawork 或 ）
3. Ultrawork（独立）
4. UltraQA（独立）
5. Swarm（独立）
6. Ultrapilot（独立）
7. Pipeline（独立）
8. Team（Claude Code 原生）
9. OMC Teams（tmux CLI workers）
10. Plan Consensus（独立）

## 强制清理全部

当你需要清除所有 session 以及旧版兼容遗留物时，请使用 `--force` 或 `--all`，例如彻底重置整个工作区。

```
/oh-my-claudecode:cancel --force
```

```
/oh-my-claudecode:cancel --all
```

底层步骤如下：
1. `state_list_active` 枚举 `.omc/state/sessions/{sessionId}/…`，找出所有已知 session。
2. `state_clear` 针对每个 session 各执行一次，删除该 session 的文件。
3. 不带 `session_id` 的全局 `state_clear` 会移除 `.omc/state/*.json`、`.omc/state/swarm*.db` 以及兼容性遗留物（见下方列表）。
4. Team 相关遗留物（`~/.claude/teams/*/`、`~/.claude/tasks/*/`、`.omc/state/team-state.json`）会作为旧版 fallback 的一部分尽力清理。
   - 原生 team 的 cancel 不会影响 omc-teams 的状态，反之亦然。

每个 `state_clear` 命令都会遵守 `session_id` 参数，因此即使在强制模式下，也会先使用会话感知路径，再删除旧版文件。

旧版兼容清单（仅在 `--force`/`--all` 下移除）：
- `.omc/state/autopilot-state.json`
- `.omc/state/ralph-state.json`
- `.omc/state/ralph-plan-state.json`
- `.omc/state/ralph-verification.json`
- `.omc/state/ultrawork-state.json`
- `.omc/state/ultraqa-state.json`
- `.omc/state/swarm.db`
- `.omc/state/swarm.db-wal`
- `.omc/state/swarm.db-shm`
- `.omc/state/swarm-active.marker`
- `.omc/state/swarm-tasks.db`
- `.omc/state/ultrapilot-state.json`
- `.omc/state/ultrapilot-ownership.json`
- `.omc/state/pipeline-state.json`
- `.omc/state/omc-teams-state.json`
- `.omc/state/plan-consensus.json`
- `.omc/state/ralplan-state.json`
- `.omc/state/boulder.json`
- `.omc/state/hud-state.json`
- `.omc/state/subagent-tracking.json`
- `.omc/state/subagent-tracker.lock`
- `.omc/state/rate-limit-daemon.pid`
- `.omc/state/rate-limit-daemon.log`
- `.omc/state/checkpoints/`（目录）
- `.omc/state/sessions/`（清理 session 后对空目录进行清理）

## 实现步骤

当你调用此技能时：

### 1. 解析参数

```bash
# Check for --force or --all flags
FORCE_MODE=false
if [[ "$*" == *"--force"* ]] || [[ "$*" == *"--all"* ]]; then
  FORCE_MODE=true
fi
```

### 2. 检测活动模式

该技能现在依赖会话感知的状态契约，而不是硬编码文件路径：
1. 调用 `state_list_active` 枚举 `.omc/state/sessions/{sessionId}/…`，发现所有活动 session。
2. 对每个 session id，调用 `state_get_status` 以了解正在运行的模式（`autopilot`、`ralph`、`ultrawork` 等）以及是否存在依赖模式。
3. 如果向 `/oh-my-claudecode:cancel` 提供了 `session_id`，则完全跳过旧版 fallback，只在该 session 路径内操作；否则，仅当状态工具未报告任何活动 session 时，才查询 `.omc/state/*.json` 中的旧版文件。Swarm 仍是 session 作用域之外的共享 SQLite/marker 模式。
4. 本文档中的任何取消逻辑都遵循由状态工具发现的依赖顺序（autopilot → ralph → …）。

### 3A. 强制模式（如果使用 --force 或 --all）

使用强制模式可通过 `state_clear` 清除所有 session 以及旧版兼容遗留物。只有当状态工具报告没有活动 session 时，才会使用直接删除文件的方式进行旧版清理。

### 3B. 智能取消（默认）

#### 如果 Team 处于活动状态（Claude Code 原生）

通过检查 `~/.claude/teams/` 中的配置文件来检测 Teams：

```bash
# Check for active teams
TEAM_CONFIGS=$(find ~/.claude/teams -name config.json -maxdepth 2 2>/dev/null)
```

**两阶段取消协议：**

**第一阶段：优雅关闭**
```
For each team found in ~/.claude/teams/:
  1. Read config.json to get team_name and members list
  2. For each non-lead member:
     a. Send shutdown_request via SendMessage
     b. Wait up to 15 seconds for shutdown_response
     c. If response received: member terminates and is auto-removed
     d. If timeout: mark member as unresponsive, continue to next
  3. Log: "Graceful pass: X/Y members responded"
```

**第二阶段：协调收敛**
```
After graceful pass:
  1. Re-read config.json to check remaining members
  2. If only lead remains (or config is empty): proceed to TeamDelete
  3. If unresponsive members remain:
     a. Wait 5 more seconds (they may still be processing)
     b. Re-read config.json again
     c. If still stuck: attempt TeamDelete anyway
     d. If TeamDelete fails: report manual cleanup path
```

**TeamDelete + 清理：**
```
  1. Call TeamDelete() — removes ~/.claude/teams/{name}/ and ~/.claude/tasks/{name}/
  2. Clear team state: state_clear(mode="team")
  3. Check for linked ralph: state_read(mode="ralph") — if linked_team is true:
     a. Clear ralph state: state_clear(mode="ralph")
     b. Clear linked ultrawork if present: state_clear(mode="ultrawork")
  4. Run orphan scan (see below)
  5. Emit structured cancel report
```

**孤儿进程检测（清理后）：**

在 TeamDelete 之后，确认没有代理进程残留：
```bash
node "${CLAUDE_PLUGIN_ROOT}/scripts/cleanup-orphans.mjs" --team-name "{team_name}"
```

孤儿扫描器会：
1. 检查 `ps aux`（Unix）或 `tasklist`（Windows），查找 `--team-name` 与已删除 team 匹配的进程
2. 对于 team 配置已不存在的每个孤儿进程：发送 SIGTERM，等待 5 秒，如果仍存活则发送 SIGKILL
3. 以 JSON 形式报告清理结果

使用 `--dry-run` 可只检查而不杀掉进程。该扫描器可以安全地重复运行多次。

**结构化取消报告：**
```
Team "{team_name}" cancelled:
  - Members signaled: N
  - Responses received: M
  - Unresponsive: K (list names if any)
  - TeamDelete: success/failed
  - Manual cleanup needed: yes/no
    Path: ~/.claude/teams/{name}/ and ~/.claude/tasks/{name}/
```

**实现说明：** cancel 技能由 LLM 执行，而不是作为 bash 脚本执行。当你检测到活动 team 时：
1. 读取 `~/.claude/teams/*/config.json` 以查找活动 teams
2. 如果存在多个 teams，先取消最旧的一个（按 `createdAt`）
3. 对每个非 lead 成员，调用 `SendMessage(type: "shutdown_request", recipient: member-name, content: "Cancelling")`
4. 简短等待 shutdown 响应（每个成员超时 15 秒）
5. 重新读取 config.json 以检查剩余成员（协调收敛阶段）
6. 调用 `TeamDelete()` 进行清理
7. 清理 team 状态：`state_clear(mode="team", session_id)`
8. 向用户报告结构化摘要

#### 如果 Autopilot 处于活动状态

Autopilot 会自行处理清理，包括关联的 ralph 和 ultraqa。

1. 通过 `state_read(mode="autopilot", session_id)` 读取 autopilot 状态，获取当前 phase
2. 通过 `state_read(mode="ralph", session_id)` 检查是否存在关联 ralph：
   - 如果 ralph 处于活动状态且有 `linked_ultrawork: true`，先清理 ultrawork：`state_clear(mode="ultrawork", session_id)`
   - 清理 ralph：`state_clear(mode="ralph", session_id)`
3. 通过 `state_read(mode="ultraqa", session_id)` 检查是否存在关联 ultraqa：
   - 如果处于活动状态，则清理它：`state_clear(mode="ultraqa", session_id)`
4. 通过 `state_write(mode="autopilot", session_id, state={active: false, ...existing})` 将 autopilot 标记为 inactive（保留状态以便恢复）

#### 如果 Ralph 处于活动状态（但不是 Autopilot）

1. 通过 `state_read(mode="ralph", session_id)` 读取 ralph 状态，检查是否有关联的 ultrawork
2. 如果 `linked_ultrawork: true`：
   - 读取 ultrawork 状态以确认 `linked_to_ralph: true`
   - 如果已关联，则清理 ultrawork：`state_clear(mode="ultrawork", session_id)`
3. 清理 ralph：`state_clear(mode="ralph", session_id)`

#### 如果 Ultrawork 处于活动状态（独立，未关联）

1. 通过 `state_read(mode="ultrawork", session_id)` 读取 ultrawork 状态
2. 如果 `linked_to_ralph: true`，提示用户改为取消 ralph（会级联清理）
3. 否则直接清理：`state_clear(mode="ultrawork", session_id)`

#### 如果 UltraQA 处于活动状态（独立）

直接清理：`state_clear(mode="ultraqa", session_id)`

#### 没有活动模式

报告："No active OMC modes detected. Use --force to clear all state files anyway."

## 实现说明

cancel 技能运行方式如下：
1. 解析 `--force` / `--all` 标志，跟踪清理应覆盖所有 session，还是仅限定在当前 session id。
2. 使用 `state_list_active` 枚举已知的 session id，并使用 `state_get_status` 了解每个 session 的活动模式（`autopilot`、`ralph`、`ultrawork` 等）。
3. 在默认模式下，使用该 `session_id` 调用 `state_clear`，只移除该 session 的文件，然后根据状态工具信号执行模式特定清理（autopilot → ralph → …）。
4. 在强制模式下，遍历所有活动 session，对每个 session 调用 `state_clear`，然后执行一次不带 `session_id` 的全局 `state_clear`，删除旧版文件（`.omc/state/*.json`、兼容性遗留物）并报告成功。Swarm 仍然是 session 作用域之外的共享 SQLite/marker 模式。
5. Team 相关遗留物（`~/.claude/teams/*/`、`~/.claude/tasks/*/`、`.omc/state/team-state.json`）仍作为旧版/全局阶段中的尽力清理项。

状态工具始终遵守 `session_id` 参数，因此即使在强制模式下，也会先清理 session-scoped 路径，再删除仅用于兼容的旧版状态。

下面各模式的专属小节描述了在全局状态操作完成后，每个处理器还会执行哪些额外清理。
## 消息参考

| Mode | Success Message |
|------|-----------------|
| Autopilot | "Autopilot cancelled at phase: {phase}. Progress preserved for resume." |
| Ralph | "Ralph cancelled. Persistent mode deactivated." |
| Ultrawork | "Ultrawork cancelled. Parallel execution mode deactivated." |
| UltraQA | "UltraQA cancelled. QA cycling workflow stopped." |
| Swarm | "Swarm cancelled. Coordinated agents stopped." |
| Ultrapilot | "Ultrapilot cancelled. Parallel autopilot workers stopped." |
| Pipeline | "Pipeline cancelled. Sequential agent chain stopped." |
| Team | "Team cancelled. Teammates shut down and cleaned up." |
| Plan Consensus | "Plan Consensus cancelled. Planning session ended." |
| Force | "All OMC modes cleared. You are free to start fresh." |
| None | "No active OMC modes detected." |

## 会保留什么

| Mode | State Preserved | Resume Command |
|------|-----------------|----------------|
| Autopilot | Yes (phase, files, spec, plan, verdicts) | `/oh-my-claudecode:autopilot` |
| Ralph | No | N/A |
| Ultrawork | No | N/A |
| UltraQA | No | N/A |
| Swarm | No | N/A |
| Ultrapilot | No | N/A |
| Pipeline | No | N/A |
| Plan Consensus | Yes (plan file path preserved) | N/A |

## 备注

- **具备依赖感知能力**：取消 Autopilot 时会一并清理 Ralph 和 UltraQA
- **具备关联感知能力**：取消 Ralph 时会一并清理其关联的 Ultrawork
- **安全**：只清理已关联的 Ultrawork，保留独立的 Ultrawork
- **仅限本地**：清理 `.omc/state/` 目录中的状态文件
- **便于恢复**：Autopilot 状态会被保留，以便无缝恢复
- **具备 Team 感知能力**：可检测原生 Claude Code teams 并执行优雅关闭

## MCP Worker Cleanup

当取消可能已生成 MCP workers（team bridge daemons）的模式时，cancel 技能还应：

1. **检查活动的 MCP workers**：查找 `.omc/state/team-bridge/{team}/*.heartbeat.json` 下的 heartbeat 文件
2. **发送关闭信号**：为每个活动 worker 写入 shutdown signal 文件
3. **终止 tmux sessions**：对每个 worker 运行 `tmux kill-session -t omc-team-{team}-{worker}`
4. **清理 heartbeat 文件**：删除该 team 的所有 heartbeat 文件
5. **清理 shadow registry**：删除 `.omc/state/team-mcp-workers.json`

### 强制清理补充

当使用 `--force` 时，还要清理：
```bash
rm -rf .omc/state/team-bridge/       # Heartbeat files
rm -f .omc/state/team-mcp-workers.json  # Shadow registry
# Kill all omc-team-* tmux sessions
tmux list-sessions -F '#{session_name}' 2>/dev/null | grep '^omc-team-' | while read s; do tmux kill-session -t "$s" 2>/dev/null; done
```
