---
name: ship
description: 任务完成后的一键收尾：代码审查 → 提交 → 标记完成 → 同步计划。将 /code-review + /commit + /done + /sync-plans 串联为单一流程。Phase 1: 增加状态机和 max_retry 限制。
---

# 任务交付工作流 (/ship)

当你完成了某个任务的编码，执行此流程完成交付闭环。

## Phase 1 增强：状态机 + 重试控制

**状态流转**：`PLAN → EXECUTE → LINT → REVIEW → COMMIT → DONE → CONTEXT_CLEANUP → ENTROPY_SCAN → KNOWLEDGE_LINT → DOC_GARDENING → PUBLISH_DOCS → CLEAN`

**关键特性**：
- ✅ **Phase Gate 检查**：每个转换有硬性前置条件
- ✅ **Max Retry 限制**：每个阶段最多重试 2 次（来自 `reasoning-config.yml`）
- ✅ **Auto Rollback**：失败时自动回滚到上一稳定状态
- ✅ **成本可控**：基于 `cost_mode` 选择模型（balanced 模式默认）

## Task Pipeline Integration

Before running, `/ship` reads `.agent/tasks/<task-id>.json` and `.agent/tasks/README.md`. When a task record exists, task pipeline gates are authoritative for stage advancement; `task-progress.md` remains the human roadmap. `/ship` must start at stage `implement` and must not write `plan -> implement`; `/start-task` exclusively owns that gate. Preserve the legacy flow for old tasks without records, but report that the task pipeline is not enabled and never fabricate passed gates.

Map the state machine to task stages as follows:

| `/ship` state | Task stage / artifact action |
| :--- | :--- |
| Entry | Require `/start-task` to have moved the task to `implement`; `/ship` neither rechecks nor rewrites `plan -> implement`. |
| `EXECUTE -> LINT` | First write an existing Artifact Bus envelope or execution-report file whose payload records commit IDs, a diff summary, and changed paths. The final task `implementation.ref` references only that file. After the file exists and its ref is in gate `evidence_refs`, pass `implement -> validate`. |
| `LINT -> REVIEW` | After lint, tests, and security checks pass, append a final `validation` artifact and pass `validate -> review`. On failure, mark the gate `blocked` and keep stage `validate`. |
| `REVIEW -> COMMIT` | Append a final `review` artifact. Must Fix findings keep stage `review` and block progress; `--no-review` records a `waived` gate and reason only when explicitly chosen by the user. |
| `COMMIT -> DONE` | Check the review verdict, commit evidence, and conditional `release-note` / `published-doc` requirements. When a condition is not applicable, record the decision in gate `reason` and cite final `decision` evidence without waiving the whole gate; after `review -> done` passes, set `status: completed`. |
| `PUBLISH_DOCS` | Receive either a final `published-doc` ref or failure evidence from `/publish-docs`. `/ship` verifies that the referenced file exists, adds the final artifact to the task, and updates completion-gate `evidence_refs`; on failure, `/ship` keeps the gate `blocked`. |

Synchronize the task file, `.agent/tasks/index.json`, `updated_at`, and gate `evidence_refs` after each mutation. Artifact bodies stay under `.agent/artifacts/<task-id>/` or their original source of truth; task files store only canonical kinds and references. After failure, append remediation artifacts and recheck the current gate without regressing the stage, overwriting old artifacts, or mutating tasks through Management API.

## 使用方式

```
/ship T-001
/ship T-001 T-002        （同时交付多个任务）
/ship T-001 --no-review  （跳过代码审查，直接提交）
```

## 执行步骤（状态机模式）

### Phase 0: PLAN（可选，如果任务已有明确计划则跳过）

**Gate Check**: `phase-gate --from START --to PLAN`
- ✅ 任务描述存在
- ✅ 架构约束已加载（`.agent/rules/architecture-design.md`）

**输出**: 实施计划（如已存在则跳过）

---

### Phase 1: EXECUTE

**Gate Check**: `phase-gate --from PLAN --to EXECUTE`
- ✅ For a recorded task, `/start-task` has already advanced stage to `implement`
- ✅ The `plan -> implement` gate passed; `/ship` does not mutate it

**Execution**: Collect evidence for the completed implementation and create an Artifact Bus envelope or execution-report file. Store commit IDs, the diff summary, and changed paths only in its payload.

**Max Retry**: 2 次（若连续 2 次实现失败，阻断并请求人工介入）

---

### Phase 2: LINT

**Gate Check**: `phase-gate --from EXECUTE --to LINT`
- ✅ 代码文件已写入/编辑
- ✅ git status 显示改动

**执行**: 运行 `.agent/hooks/pre-commit-check.sh`
- Linter 检查（ESLint, Ruff 等）
- 密钥扫描

**Blocking Condition**: Linter 失败 → 阻断，提示修复

**Max Retry**: 2 次（连续 2 次 lint 失败 → 请求人工检查规则或手动修复）

---

### Phase 3: REVIEW

**Gate Check**: `phase-gate --from LINT --to REVIEW`
- ✅ Linter 检查通过（exit code 0）
- ✅ 无安全漏洞检测

**执行**: 调用 `code-reviewer` sub-agent
- 输入隔离：只看 plan + diff + previous reports
- 架构合规性检查（`architecture-guard`）
- 代码质量评分（`code-evaluation`）
- 安全扫描（`security-scan`）

**输出格式**:
```
## Review Report
### ✅ Passed
### ⚠️ Suggestions
### ❌ Must Fix
### Summary
```

**Blocking Condition**: "❌ Must Fix" 非空 → 阻断，回滚到 EXECUTE 阶段

**Max Retry**: 2 次

---

### Phase 4: COMMIT

**Gate Check**: `phase-gate --from REVIEW --to COMMIT`
- ✅ 代码审查完成
- ✅ 无阻断性问题（"❌ Must Fix" 为空）

**执行**: 调用 `/commit` 逻辑
- 分析 git diff 生成 Conventional Commits 消息
- 用户确认后执行 `git commit`

**Max Retry**: 1 次（提交失败通常是环境问题，不应反复重试）

---

### Phase 5: DONE

**Gate Check**: `phase-gate --from COMMIT --to DONE`
- ✅ 改动已提交（`git log -1` 显示新提交）

**执行**:
- 更新 `task-progress.md`（标记完成）
- 同步关联任务状态（`/sync-plans` 逻辑）
- 生成交付报告

---

### Phase 6: CONTEXT_CLEANUP（自动执行，无需用户介入）

DONE 状态达成后，执行上下文清洗，防止任务间上下文污染：

**归档任务产物**（移动，不删除，保留复盘能力）：

```
.agent/plans/T-xxx/plan_summary.json      → .agent/archive/T-xxx/plan_summary.json
.agent/plans/T-xxx/execution_report.json  → .agent/archive/T-xxx/execution_report.json
.agent/plans/T-xxx/review_verdict.json    → .agent/archive/T-xxx/review_verdict.json
```

**保留**（不归档，后续任务仍需访问）：
- `task-progress.md`（任务状态全局记录）
- `context-manifest.json`（本次上下文分配记录，供 entropy-scanner 参考）

**清洗完成标志**：创建 `.agent/archive/T-xxx/cleanup.marker`，内容为完成时间戳。

> 若 `.agent/archive/` 目录不存在，先创建再归档。
> 若任务产物文件不存在（如跳过了某阶段），跳过对应归档步骤，不报错。

**状态流转**：`CONTEXT_CLEANUP` → `ENTROPY_SCAN`

---

### Phase 7: ENTROPY_SCAN（自动执行）

CONTEXT_CLEANUP 完成后，调用 `entropy-scanner` sub-agent 做 L0 + L1 扫描：

- **L0**：自动修复 context-index.json 偏差（已删模块条目、orphan_plans）
- **L1**：标记 stale_refs 和 missing_refs（不修复内容，只标记状态）

输出 `.agent/entropy-report.json`，包含本次健康度评分。

**State transition**: `ENTROPY_SCAN` → `KNOWLEDGE_LINT`

---

### Phase 8: KNOWLEDGE_LINT (automatic)

After `ENTROPY_SCAN`, run lightweight knowledge lint to refresh knowledge health:

**Command**:

```bash
node .agent/skills/knowledge-lint/scripts/index.js
```

**Output**:

- `.agent/metrics/knowledge-health.json`

**Checks**:

- Broken Markdown links
- Invalid anchors
- Missing README files in key knowledge directories
- Plan lifecycle issues
- Reference drift between `docs/architecture.md` and the actual repo structure

**Execution policy**:

- Deterministic checks only
- Do not automatically rewrite large documentation blocks
- Record findings in `knowledge-health.json`
- Do not block `CLEAN` by default, but surface high-priority findings in the delivery report

**State transition**: `KNOWLEDGE_LINT` → `DOC_GARDENING`

---

### Phase 9: DOC_GARDENING (automatic, advisory only)

After `KNOWLEDGE_LINT`, generate low-risk documentation maintenance suggestions for `/briefing` and later upkeep:

**Command**:

```bash
node .agent/skills/doc-gardening/scripts/index.js
```

**Output**:

- `.agent/metrics/doc-gardening-report.json`

**Execution policy**:

- Suggestions only; do not automatically rewrite large documentation blocks
- Prioritize quick wins and structural sync items that need human judgment
- Do not block `CLEAN` by default
- If `P0` items exist, call them out in the delivery report

**State transition**: `DOC_GARDENING` → `PUBLISH_DOCS`

---

### Phase 10: PUBLISH_DOCS (optional)

After `DOC_GARDENING`, decide whether this delivery affects developer-facing docs:

- Public capabilities, module boundaries, architecture decisions, development commands, or deployment behavior changed
- `.agent/references/` was refreshed by `/scan-project` or `/update-refs` and should be synced to `docs/`
- The user explicitly requested PRD, architecture, module, or developer manual updates

If matched, run `/publish-docs` or `/publish-docs --architecture`. If not matched, record that no developer docs need publishing and continue.

`/publish-docs` returns only a final `published-doc` ref or failure evidence. `/ship` is the only workflow that verifies the referenced file, writes task `artifacts[]` and completion-gate `evidence_refs`, and changes gate status. When docs are not applicable, `/ship` records the decision in gate `reason` and cites final `decision` evidence without waiving the whole `review -> done` gate.

**Execution policy**:

- Publish only the current task scope; avoid full rewrites
- Before publishing, list source files, target files, and out-of-scope content
- After publishing, run the link, sanitization, and `git diff --check` checks from `/publish-docs`
- Do not block `CLEAN` by default, but fix before continuing if secrets, `.agent/` path leaks, or code/doc fact mismatches are found

**State transition**: `PUBLISH_DOCS` → `CLEAN` (final state)

---

## 传统执行步骤（兼容旧版，逐步迁移到状态机模式）

### 第一步：加载任务上下文

读取 `.agent/plans/task-progress.md`，定位指定任务 ID：
- 确认任务描述和验收标准
- 检查是否有未完成的依赖任务（若有，提示用户确认是否继续）

### 第二步：代码审查（可跳过）

除非指定 `--no-review`，否则自动触发代码审查流程：

```bash
git diff HEAD    # 审查所有未提交改动
git diff --staged  # 若已有暂存区，优先审查暂存内容
```

重点检查：
- 是否满足任务验收标准
- 是否符合 `.agent/rules/code-standards.md`
- 是否有遗漏的边界处理或测试

若发现问题，列出后询问用户：**修复后继续，还是先交付再开新任务跟进？**

### 第三步：提交代码

调用 `/commit` 工作流：
- AI 分析改动，生成 Conventional Commits 格式提交信息
- 展示给用户确认后执行 `git commit`
- 遵守 `.agent/rules/commit-standards.md`（禁止 AI 署名）

### 第四步：标记任务完成

调用 `/done <task-id>` 逻辑：
- 路线图 `[ ]` → `[x]`
- 从活跃任务表移除
- 追加到"最近完成"
- 重新计算整体进度百分比

### 第五步：同步关联任务

检查 `.agent/plans/task-progress.md` 中是否有其他任务依赖已完成的任务：
- 若有，将其状态从"阻塞"更新为"可开始"
- 若有并行任务受影响，提示用户

### 第六步：交付报告

输出简报：

```
🚢 交付完成：T-001（实现 JWT token 生成与验证）

  ✅ 代码已审查
  ✅ 提交：abc1234 feat(auth): 实现 JWT token 生成与验证
  ✅ 任务已标记完成
  📊 整体进度：72% → 78%

  🔓 已解锁任务：T-007（实现登录接口 /auth/login）
  📌 推荐下一步：/start-task T-007
```

---

## 💡 使用场景

| 场景 | 命令 |
|------|------|
| 正常完成一个任务 | `/ship T-001` |
| 快速提交，跳过审查 | `/ship T-001 --no-review` |
| 一次性交付多个小任务 | `/ship T-001 T-002 T-003` |
| 只想提交，不更新计划 | `/commit`（直接用提交工作流）|

## Recording Points

`/ship` owns activity at each pipeline stage. Record an event when entering REVIEW, when entering TEST, and when the final SHIP state is reached:

```bash
# Entering REVIEW
node .agent/skills/activity-recording/scripts/index.js record-event \
  --kind validation \
  --source /ship \
  --summary "Ship <TASK_ID> entered REVIEW" \
  --actor-type workflow \
  --actor-id /ship \
  --dedupe-key "ship:<TASK_ID>:review:enter"

# Final SHIP outcome
node .agent/skills/activity-recording/scripts/index.js record-receipt \
  --kind delivery \
  --source /ship \
  --activity-refs ACT-ship-<TASK_ID>-review,ACT-ship-<TASK_ID>-test \
  --availability available \
  --redaction not_applicable \
  --dedupe-key "ship:<TASK_ID>:delivered"
```

If the helper is missing or recording is unavailable, continue with the legacy workflow behavior and skip the call. Do not invent receipts.
