---
name: loom-pipeline-selector
description: >
  Analyze user request + collect signals (file scope, keywords, worktree state, spec existence),
  then select pipeline steps via rule short-circuit / AI fallback / rule-based fallback.
  Select steps first, expose the choice to the user, and persist selected dynamic_steps only after explicit user confirmation; pipeline-plan.md is optional for manual review.
  Use when: user is unsure which pipeline type to pick, or wants AI to choose steps automatically.
when_to_use: Select safe pipeline steps for a development request, then wait for explicit confirmation before persisting them.
argument-hint: <user request>
user-invocable: true
---

# AI 自主流程选择

## 触发条件

- 用户未明确指定 `--type`，或显式要求 AI 选择流程。
- 用户描述需求时包含模糊信号（既非明显 typo 也非明显新功能）。
- `loom run --auto` 或 MCP `loom_select_pipeline` 调用时。

## 职责边界

`loom-pipeline-selector` 是开发流水线步骤选择器，不是通用入口 router。它只在请求已经被判断为开发型任务，或用户明确要求自动选择流水线时使用。

- 入口分流、解释“该用哪个 loom 能力”由 `loom-router` 负责。
- 具体选择 `dynamic_steps`、展示来源/风险/步骤、等待确认后写入 `pipeline.state.json` 由本 skill 负责。
- 本 skill 不处理 QA 验收、审查反馈、分支收尾、loom 使用咨询等非开发流水线入口，除非它们被明确纳入某个开发 pipeline。

## 执行流程

### Step 1：收集信号

读取以下信号（由 `PipelineSelector._collectSignals` 完成）：

- `keywords`：需求中的风险关键词（重构/跨模块/新功能/typo/依赖升级等）
- `fileScope`：估计影响文件数（1/3/5/10）
- `hasSpecExists`：specDir 是否已有 spec.md
- `hasSpecAndReqs`：specDir 是否同时已有 spec.md 和 requirements.json
- `hasRootCause`：是否提到"根因""已定位"
- `inWorktree`：是否已在 git worktree 内

### Step 2：规则短路

按 `workflow.yaml > selection_rules.short_circuits` 顺序匹配：

| 规则名               | 关键词                                    | file_scope_max | 步骤                                                |
| -------------------- | ----------------------------------------- | -------------- | --------------------------------------------------- |
| quickfix             | typo/错别字/单文件/小修复                 | ≤1             | executing, verification                             |
| chore                | 依赖升级/npm update/配置调整/bump version | —              | executing, verification                             |
| hotfix               | 生产紧急/线上故障/P0/hotfix               | —              | approved, executing, verification                   |
| bugfix-no-brainstorm | bug/修复/fix + 根因明确                   | ≤5             | planning, approved, executing, verification, code-review-request, review-gate, code-review-response, synced |

命中即返回，不调 AI。

### Step 3：AI fallback（可选）

信号模糊 + 注入 aiClient 时，调 AI 传入 `step_catalog` + `selection_rules` 作 context，AI 返回 `{ steps, reasoning }`。

未注入 aiClient 或 AI 失败 → 走 Step 4。

### Step 4：规则兜底

按风险等级生成基础流程，并按增强/mandatory 信号追加结构化质量门：

- **low**：executing → verification
- **medium**：planning → approved → executing → verification → code-review-request → review-gate → code-review-response → synced
- **high**：brainstorming（若 spec 不存在）→ planning → approved → git-worktree（若不在 worktree）→ executing → verification → code-review-request → review-gate → code-review-response → synced

#### 增强模块与结构化 mandatory

`_collectSignals` 额外采集 `optionalTriggers`（由 `_detectOptionalTriggers` 检测），命中即在基础流程的固定位置插入对应增强模块；若已有 `spec.md` + `requirements.json`，这些结构化质量门按 mandatory 语义自动补齐：

| 增强模块            | 插入位置                          | 触发关键词信号                                                                 |
| ------------------- | --------------------------------- | ------------------------------------------------------------------------------ |
| detail-expansion    | brainstorming 后、planning 前     | 输入校验/权限/并发/原子性/安全/性能/可观测/幂等/兼容/恢复/边界/非法输入/状态迁移 |
| analyze-artifacts   | planning 后、approved 前          | 跨模块/架构/重构/多文件协同/契约变更/接口变更                                  |
| converge            | executing 后、verification 前     | 多任务/并行/跨模块/集成回归/需求覆盖/行为义务                                  |

> `loom-omission-hunter` 不是独立 step，由 converge 在内部按需触发，不出现在主线的 `dynamic_steps` 中。

追加规则：
- 已有 `spec.md` + `requirements.json` 时，detail-expansion、analyze-artifacts、converge 必须出现在结构化流程中。
- quickfix/chore 短路显式 `skip_closure`/`skip_gate`/`skip_mandatory`，保持 executing → verification 的轻量流程。
- 同一分支可叠加多个增强模块，按上表固定位置各自插入。

### Step 5：校验与修正（`_validateAndFix`）

护栏强制：

- `must_include`：executing + verification 必须在列
- `dependency_closure`：选 executing 但无 plan.md → 自动补 planning；选 planning 但无 spec.md → 自动补 brainstorming
- `never_skip_gates`：planning 后必插 approved（显式轻量 short-circuit 除外）
- `mandatory`：executing、verification 不可省；已有 spec.md + requirements.json 的结构化流程不可省 detail-expansion、analyze-artifacts、converge
- `max_steps: 13`：增强模块参与完整顺序校验；仅超限时按 `OPTIONAL_TRIM_ORDER = ['detail-expansion', 'analyze-artifacts', 'converge']`（converge 靠近验证关口，最后裁）裁剪可裁模块，仍超则报错

### Step 6：输出与确认门禁

默认路径是先只返回选择结果，不初始化状态。调用方必须把选择结果告知用户，并等待用户明确确认后，才能在初始化时写入 `pipeline.state.json` 的 `dynamic_steps`；`progress.md` 会由 state-store 自动生成/更新，记录当前阶段和动态步骤。需要人工审查或手动调整时，可在 specDir 写 `pipeline-plan.md`：

```markdown
# Pipeline Plan

> Auto-generated by loom-pipeline-selector. Do not edit manually.

## 用户需求

<原需求>

## AI 分析

- 风险等级: <low|medium|high>
- 关键词: <keywords>
- 影响文件: <fileScope>
- 已有 spec.md: <是|否>
- 已在 worktree: <是|否>

## 选择步骤

1. brainstorming — <理由>
2. planning — <理由>
   ...

## 跳过步骤

- git-worktree — <理由>

## 来源

<short-circuit:quickfix | ai | fallback:high-risk>

## 理由

<详细推理>
```

### Step 7：确认后继续执行

默认模式：向用户说明来源、风险、步骤和理由，等待用户明确确认后，才可以初始化并继续执行。首次选择禁止调用 `loom run --auto` 或 MCP `loom_select_pipeline initialize=true`，避免在用户看到流水线前写入状态并开始执行。若使用 `pipeline-plan.md` 审查模式，则提示用户：

- `loom run --spec-dir <dir> --approve-pipeline` 确认并初始化
- 或手动调整 `pipeline-plan.md` 后再确认
- 已确认且无需 `pipeline-plan.md` 时，可调用 MCP `loom_select_pipeline initialize=true` 或执行 `loom run --spec-dir <dir> --auto --request "<需求>"`

初始化后必须能通过 `pipeline.state.json` 的 `dynamic_steps` 和 `progress.md` 在无对话上下文时恢复执行。

## 约束

- **不跳 mandatory step**：executing、verification 不可省；已有 spec.md + requirements.json 时 detail-expansion、analyze-artifacts、converge 不可省
- **不跳 gate**：approved（human-approval）必须保留
- **依赖闭包**：选 step 必须带 producer
- **max_steps**：≤13

## 失败处理

- AI 调用失败 → 自动降级到规则兜底
- 校验抛 `max_steps` 错 → 先按 `OPTIONAL_TRIM_ORDER` 裁可裁增强模块，仍超则提示用户拆分需求
- specDir 无写权限 → 仅返回 JSON，不初始化状态

## 参考

- `references/step-catalog.md`：完整步骤池说明
- `assets/pipeline-plan-template.md`：pipeline-plan.md 模板
- `src/core/pipeline-selector.js`：选择器实现
