hookehuyr

chore: stop tracking ignored directories (.claude, .cursor, .specify, .trae, .github, docs)

Showing 50 changed files with 0 additions and 3952 deletions
{
"permissions": {
"allow": [
"Bash(tree:*)",
"Bash(xargs awk:*)",
"Bash(find:*)",
"Bash(grep:*)"
]
}
}
---
description: 在生成 tasks.md 之后,对 spec.md、plan.md、tasks.md 做一次非破坏性的跨文件一致性与质量分析。
---
## 用户输入
```text
$ARGUMENTS
```
在继续之前,你**必须**先考虑用户输入(如果不为空)。
## 目标
在开始实现之前,识别三份核心产物(`spec.md``plan.md``tasks.md`)之间的不一致、重复、歧义和说明不足之处。本命令**必须**`/speckit.tasks` 成功生成完整的 `tasks.md` 之后才运行。
## 运行约束
**严格只读****不要**修改任何文件。输出结构化的分析报告。可以提供可选的修复方案(用户必须明确同意后,才可以人工触发后续的编辑命令)。
**宪法优先级**:在本分析范围内,项目宪法(`.specify/memory/constitution.md`**不可协商**。任何与宪法冲突的问题都自动视为 CRITICAL,并要求调整 spec/plan/tasks,而不是淡化、重新解释或悄悄忽略原则。如果确实需要修改原则本身,必须在 `/speckit.analyze` 之外,通过单独、明确的宪法更新来完成。
## 执行步骤
### 1. 初始化分析上下文
在仓库根目录只运行一次 `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks`,并解析 JSON 中的 FEATURE_DIR 和 AVAILABLE_DOCS。推导出绝对路径:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
如果缺少任何必需文件,直接报错并提示用户运行缺失的前置命令。
当参数里包含单引号(例如 "I'm Groot")时,使用转义写法:如 'I'\''m Groot'(或尽量用双引号:"I'm Groot")。
### 2. 加载产物(渐进式披露)
每个产物只加载最少且必要的上下文:
**来自 spec.md:**
- 概览/背景
- 功能需求
- 非功能需求
- 用户故事
- 边界情况(如存在)
**来自 plan.md:**
- 架构/技术栈选择
- 数据模型引用
- 阶段划分
- 技术约束
**来自 tasks.md:**
- 任务 ID
- 任务描述
- 阶段分组
- 并行标记 [P]
- 引用到的文件路径
**来自宪法:**
- 加载 `.specify/memory/constitution.md` 用于原则校验
### 3. 构建语义模型
创建内部表示(输出中不要包含原始产物全文):
- **需求清单**:每条功能/非功能需求都要有稳定的 key(根据祈使句短语生成 slug;例如 “用户可以上传文件” → `user-can-upload-file`
- **用户故事/动作清单**:离散的用户动作及其验收标准
- **任务覆盖映射**:将每个任务映射到一个或多个需求/故事(通过关键字推断或显式引用模式,比如 ID、关键短语)
- **宪法规则集**:提取原则名称以及 MUST/SHOULD 等规范性语句
### 4. 检测遍历(Token 高效分析)
聚焦高信号问题。总计最多输出 50 条发现;其余聚合到溢出摘要中。
#### A. 重复检测
- 识别近似重复的需求
- 标记表达质量较低的需求,建议合并收敛表述
#### B. 歧义检测
- 标记缺少可度量标准的模糊形容词(fast、scalable、secure、intuitive、robust 等)
- 标记未解决的占位符(TODO、TKTK、???、`<placeholder>` 等)
#### C. 说明不足
- 有动词但缺少对象或可度量结果的需求
- 用户故事缺少与验收标准对齐的说明
- 任务引用了 spec/plan 中未定义的文件或组件
#### D. 宪法对齐
- 任意与宪法 MUST 原则冲突的需求或计划要素
- 缺失宪法要求的必填章节或质量门禁
#### E. 覆盖缺口
- 没有关联任务的需求
- 未映射到任何需求/故事的任务
- 未在任务中体现的非功能需求(例如性能、安全)
#### F. 不一致
- 术语漂移(同一概念在不同文件中用不同名称)
- plan 引用的数据实体在 spec 中缺失(或反之)
- 任务顺序自相矛盾(例如未注明依赖却在基础初始化之前安排集成任务)
- 需求相互冲突(例如一处要求 Next.js,另一处指定 Vue)
### 5. 严重级别判定
使用以下启发式规则为发现排序:
- **CRITICAL**: 违反宪法 MUST、缺失核心产物,或关键需求零覆盖导致基线功能无法实现
- **HIGH**: 重复或冲突的需求、含糊的安全/性能属性、不可测试的验收标准
- **MEDIUM**: 术语漂移、缺少非功能需求的任务覆盖、边界情况说明不足
- **LOW**: 风格/措辞改进、不影响执行顺序的轻微冗余
### 6. 产出精简分析报告
按以下结构输出 Markdown 报告(不写文件):
## 规格说明分析报告
| ID | 类别 | 严重级别 | 位置 | 摘要 | 建议 |
|----|----------|----------|-------------|---------|----------------|
| A1 | 重复 | HIGH | spec.md:L120-134 | 两条相似需求…… | 合并表述;保留更清晰的版本 |
(每条发现一行;生成稳定 ID,并以类别首字母作为前缀。)
**覆盖摘要表:**
| 需求 Key | 是否有任务 | 任务 ID | 备注 |
|-----------------|-----------|----------|-------|
**宪法对齐问题:**(如有)
**未映射任务:**(如有)
**指标:**
- 需求总数
- 任务总数
- 覆盖率(至少关联 1 个任务的需求占比)
- 歧义数量
- 重复数量
- 严重问题数量
### 7. 给出下一步动作
在报告末尾输出精炼的“下一步动作”区块:
- 若存在 CRITICAL:建议在进入 `/speckit.implement` 之前先解决
- 若只有 LOW/MEDIUM:可继续推进,但应给出改进建议
- 给出明确命令建议:例如“用更精炼描述重新运行 /speckit.specify”“运行 /speckit.plan 调整架构”“手动编辑 tasks.md 为 ‘performance-metrics’ 补齐覆盖”
### 8. 提供修复建议
询问用户:“你希望我为前 N 个问题给出具体的修复编辑建议吗?”(不要自动应用。)
## 运行原则
### 上下文效率
- **最小高信号 token**:聚焦可执行发现,不做穷举式文档复述
- **渐进式披露**:逐步加载产物,不把全文倾倒进分析
- **token 高效输出**:发现表最多 50 行,其余做溢出摘要
- **确定性结果**:在无变更前提下重复运行应得到一致的 ID 与统计
### 分析准则
- **禁止修改文件**(严格只读分析)
- **禁止臆造缺失章节**(缺失就如实报告)
- **优先处理宪法违规则**(一律 CRITICAL)
- **用例子胜过穷举规则**(引用具体实例而不是泛泛而谈)
- **零问题也要输出报告**(给出覆盖统计并明确通过)
## 上下文
$ARGUMENTS
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
---
description: 通过交互式或提供的原则输入创建/更新项目宪法,并确保所有依赖模板保持同步。
handoffs:
- label: 生成规格说明
agent: speckit.specify
prompt: 基于更新后的宪法生成功能规格说明。我想要构建……
---
## 用户输入
```text
$ARGUMENTS
```
在继续之前,你**必须**先考虑用户输入(如果不为空)。
## 概述
你正在更新 `.specify/memory/constitution.md` 中的项目宪法。该文件是一个模板(Template),包含方括号占位符(例如 `[PROJECT_NAME]``[PRINCIPLE_1_NAME]`)。你的工作是:(a)收集/推导具体值,(b)精准填充模板,(c)将所有修订同步传播到依赖产物中。
按以下流程执行:
1. 加载 `.specify/memory/constitution.md` 中现有的宪法模板。
- 识别所有形如 `[ALL_CAPS_IDENTIFIER]` 的占位符 token。
**重要**:用户需要的原则数量可能少于或多于模板默认数量。如果用户指定了数量,必须尊重该数量,并在通用模板结构下调整文档内容。
2. 收集/推导占位符的具体值:
- 若用户输入(对话中)已提供取值,直接使用。
- 否则从仓库上下文推断(README、文档、若存在则参考仓库内嵌的旧宪法内容)。
- 治理日期规则:`RATIFICATION_DATE` 为原始生效日期(未知则询问或标记 TODO);`LAST_AMENDED_DATE` 若本次有修改则为今天,否则保留原值。
- `CONSTITUTION_VERSION` 必须按语义化版本规则递增:
- MAJOR:不向后兼容的治理/原则移除或重定义。
- MINOR:新增原则/章节,或对既有指导做实质性扩展。
- PATCH:澄清、措辞、错别字修正、非语义性的精炼。
- 若版本升级类型不明确,在最终落盘前先给出判断理由。
3. 起草更新后的宪法内容:
- 用具体文本替换每个占位符(不应残留方括号 token;除非项目明确决定暂不定义,并对每个保留项给出理由)。
- 保持标题层级不变;占位符被替换后,注释可移除,除非该注释仍对理解有帮助。
- 确保每条原则包含:简短名称行、概括不可协商规则的段落(或要点列表),若理由不明显则补充明确的理由说明。
- 确保治理(Governance)章节包含:修订流程、版本策略、合规审查期望。
4. 一致性传播清单(把旧清单转为可执行校验项):
- 阅读 `.specify/templates/plan-template.md`,确保其中的“宪法检查”或规则与更新后的原则一致。
- 阅读 `.specify/templates/spec-template.md`,校验范围/需求对齐;若宪法新增/移除必填章节或约束,则同步更新模板。
- 阅读 `.specify/templates/tasks-template.md`,确保任务分类能体现新增/移除的原则驱动任务类型(例如可观测性、版本策略、测试纪律)。
- 阅读 `.specify/templates/commands/*.md` 下的每个命令文件(包含本文件),确保通用指导中不残留过时的 agent 特定引用(例如仅写 CLAUDE)。
- 阅读运行/使用指导文档(例如 `README.md``docs/quickstart.md`,或存在的 agent 专属指导文件),同步更新与宪法变更相关的引用。
5. 生成“同步影响报告”(更新后,作为 HTML 注释插入到宪法文件顶部):
- 版本变更:旧版本 → 新版本
- 修改过的原则列表(若重命名则写 旧标题 → 新标题)
- 新增章节
- 移除章节
- 需要更新的模板列表(✅ 已更新 / ⚠ 待处理),并附文件路径
- 若有占位符被刻意延期,列出后续 TODO
6. 最终输出前校验:
- 不残留任何无法解释的方括号占位符 token。
- 版本行与同步影响报告一致。
- 日期使用 ISO 格式 YYYY-MM-DD。
- 原则陈述应可验证、可测试,避免含糊措辞(必要时将“should”替换为 MUST/SHOULD,并给出理由)。
7. 将完成的宪法内容写回 `.specify/memory/constitution.md`(覆盖写入)。
8. 输出给用户的最终总结应包含:
- 新版本号与升级理由。
- 需要人工跟进的文件(如有)。
- 建议的提交信息(例如 `docs: amend constitution to vX.Y.Z (principle additions + governance update)`)。
格式与样式要求:
- 标题层级必须与模板完全一致(不要升/降级标题)。
- 适度换行以保持可读性(理想情况下 <100 字符),但不要为了硬性限制造成生硬断行。
- 章节之间保持一个空行。
- 避免行尾空格。
如果用户只提供部分更新(例如只修改一条原则),也要照样执行校验与版本决策步骤。
如果缺少关键信息(例如确实不知道 ratification date),插入 `TODO(<FIELD_NAME>): explanation`,并在同步影响报告的延期项(deferred)中列出。
不要创建新的模板;始终在现有的 `.specify/memory/constitution.md` 文件上操作。
---
description: 通过处理并执行 tasks.md 中定义的所有任务,落实实现计划
---
## 用户输入
```text
$ARGUMENTS
```
在继续之前,你**必须**先考虑用户输入(如果不为空)。
## 概述
1. 在仓库根目录运行一次 `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks`,并解析 JSON 中的 FEATURE_DIR 与 AVAILABLE_DOCS 列表。所有路径必须是绝对路径。当参数里包含单引号(例如 "I'm Groot")时,使用转义写法:如 'I'\''m Groot'(或尽量用双引号:"I'm Groot")。
2. **检查检查清单状态**(如果存在 FEATURE_DIR/checklists/):
- 扫描 checklists/ 目录下的所有清单文件
- 对每个清单统计:
- 总条目:匹配 `- [ ]``- [X]``- [x]` 的所有行
- 已完成条目:匹配 `- [X]``- [x]` 的行
- 未完成条目:匹配 `- [ ]` 的行
- 生成状态表:
```text
| Checklist | Total | Completed | Incomplete | Status |
|-----------|-------|-----------|------------|--------|
| ux.md | 12 | 12 | 0 | ✓ PASS |
| test.md | 8 | 5 | 3 | ✗ FAIL |
| security.md | 6 | 6 | 0 | ✓ PASS |
```
- 计算总体状态:
- **PASS**:所有清单的未完成条目为 0
- **FAIL**:存在至少一个清单有未完成条目
- **如果存在未完成清单**
- 展示状态表与未完成数量
- **停止**并询问:“有些检查清单尚未完成。是否仍要继续实现?(yes/no)”
- 等待用户回复后再继续
- 若用户回复 “no”“wait” 或 “stop”,则终止执行
- 若用户回复 “yes”“proceed” 或 “continue”,则进入第 3 步
- **如果所有清单都已完成**
- 展示所有清单通过的状态表
- 自动进入第 3 步
3. 加载并分析实现上下文:
- **必须**:读取 tasks.md 获取完整任务列表与执行计划
- **必须**:读取 plan.md 获取技术栈、架构与文件结构
- **如果存在**:读取 data-model.md 获取实体与关系
- **如果存在**:读取 contracts/ 获取 API 规范与测试要求
- **如果存在**:读取 research.md 获取技术决策与约束
- **如果存在**:读取 quickstart.md 获取集成场景
4. **项目初始化校验**
- **必须**:基于实际项目情况创建/校验 ignore 文件:
**检测与创建逻辑**
- 通过下列命令是否成功来判断仓库是否是 git 仓库(如果是,则创建/校验 .gitignore):
```sh
git rev-parse --git-dir 2>/dev/null
```
- 检查是否存在 Dockerfile* 或 plan.md 中提到 Docker → 创建/校验 .dockerignore
- 检查是否存在 .eslintrc* → 创建/校验 .eslintignore
- 检查是否存在 eslint.config.* → 确保配置中的 `ignores` 覆盖所需模式
- 检查是否存在 .prettierrc* → 创建/校验 .prettierignore
- 检查是否存在 .npmrc 或 package.json →(若要发布)创建/校验 .npmignore
- 检查是否存在 terraform 文件(*.tf)→ 创建/校验 .terraformignore
- 检查是否需要 .helmignore(存在 helm charts)→ 创建/校验 .helmignore
**如果 ignore 文件已存在**:校验其包含关键模式,只追加缺失且重要的模式
**如果 ignore 文件不存在**:按检测到的技术栈创建包含完整模式集合的文件
**按技术栈的常见模式**(来自 plan.md 的技术栈):
- **Node.js/JavaScript/TypeScript**: `node_modules/`, `dist/`, `build/`, `*.log`, `.env*`
- **Python**: `__pycache__/`, `*.pyc`, `.venv/`, `venv/`, `dist/`, `*.egg-info/`
- **Java**: `target/`, `*.class`, `*.jar`, `.gradle/`, `build/`
- **C#/.NET**: `bin/`, `obj/`, `*.user`, `*.suo`, `packages/`
- **Go**: `*.exe`, `*.test`, `vendor/`, `*.out`
- **Ruby**: `.bundle/`, `log/`, `tmp/`, `*.gem`, `vendor/bundle/`
- **PHP**: `vendor/`, `*.log`, `*.cache`, `*.env`
- **Rust**: `target/`, `debug/`, `release/`, `*.rs.bk`, `*.rlib`, `*.prof*`, `.idea/`, `*.log`, `.env*`
- **Kotlin**: `build/`, `out/`, `.gradle/`, `.idea/`, `*.class`, `*.jar`, `*.iml`, `*.log`, `.env*`
- **C++**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.so`, `*.a`, `*.exe`, `*.dll`, `.idea/`, `*.log`, `.env*`
- **C**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.a`, `*.so`, `*.exe`, `Makefile`, `config.log`, `.idea/`, `*.log`, `.env*`
- **Swift**: `.build/`, `DerivedData/`, `*.swiftpm/`, `Packages/`
- **R**: `.Rproj.user/`, `.Rhistory`, `.RData`, `.Ruserdata`, `*.Rproj`, `packrat/`, `renv/`
- **Universal**: `.DS_Store`, `Thumbs.db`, `*.tmp`, `*.swp`, `.vscode/`, `.idea/`
**工具特定模式**
- **Docker**: `node_modules/`, `.git/`, `Dockerfile*`, `.dockerignore`, `*.log*`, `.env*`, `coverage/`
- **ESLint**: `node_modules/`, `dist/`, `build/`, `coverage/`, `*.min.js`
- **Prettier**: `node_modules/`, `dist/`, `build/`, `coverage/`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
- **Terraform**: `.terraform/`, `*.tfstate*`, `*.tfvars`, `.terraform.lock.hcl`
- **Kubernetes/k8s**: `*.secret.yaml`, `secrets/`, `.kube/`, `kubeconfig*`, `*.key`, `*.crt`
5. 解析 tasks.md 结构并提取:
- **任务阶段**:初始化、测试、核心、集成、打磨
- **任务依赖**:串行与并行的执行规则
- **任务细节**:ID、描述、文件路径、并行标记 [P]
- **执行流程**:顺序与依赖要求
6. 按任务计划执行实现:
- **按阶段执行**:完成当前阶段后再进入下一阶段
- **遵守依赖**:串行任务按顺序执行;并行任务 [P] 可同时执行
- **遵循 TDD**:若存在测试任务,先执行测试任务再执行对应实现任务
- **按文件协调**:影响同一文件的任务必须串行执行
- **阶段校验点**:进入下一阶段前先校验当前阶段是否完成
7. 实现执行规则:
- **先做初始化**:初始化项目结构、依赖、配置
- **先写测试再写代码**:如果需要为契约、实体与集成场景编写测试
- **核心开发**:实现模型、服务、CLI 命令、端点
- **集成工作**:数据库连接、中间件、日志、外部服务
- **打磨与校验**:单元测试、性能优化、文档
8. 进度跟踪与错误处理:
- 每完成一个任务都汇报进度
- 任意非并行任务失败时立即停止执行
- 并行任务 [P] 允许继续已成功任务,并汇报失败项
- 提供带上下文的清晰错误信息,便于定位
- 若实现无法继续,给出明确的下一步建议
- **重要**:任务完成后,务必在 tasks 文件中用 [X] 勾掉该任务
9. 完成校验:
- 确认所有必需任务都已完成
- 检查实现的功能是否与原始 spec 一致
- 校验测试通过且覆盖率满足要求
- 确认实现遵循技术计划
- 汇报最终状态并总结已完成工作
注意:本命令假设 tasks.md 中已存在完整的任务拆分。如果任务不完整或缺失,应建议先运行 `/speckit.tasks` 重新生成任务列表。
---
description: 使用计划模板执行实现规划流程,并生成设计产物。
handoffs:
- label: 生成任务列表
agent: speckit.tasks
prompt: 将实现计划拆分为可执行任务
send: true
- label: 生成检查清单
agent: speckit.checklist
prompt: 为以下领域生成一份检查清单……
---
## 用户输入
```text
$ARGUMENTS
```
在继续之前,你**必须**先考虑用户输入(如果不为空)。
## 概述
1. **准备**:在仓库根目录运行 `.specify/scripts/bash/setup-plan.sh --json`,并解析 JSON 中的 FEATURE_SPEC、IMPL_PLAN、SPECS_DIR、BRANCH。当参数里包含单引号(例如 "I'm Groot")时,使用转义写法:如 'I'\''m Groot'(或尽量用双引号:"I'm Groot")。
2. **加载上下文**:读取 FEATURE_SPEC 与 `.specify/memory/constitution.md`。加载 IMPL_PLAN 模板(已复制到目标位置)。
3. **执行规划流程**:按 IMPL_PLAN 模板结构完成:
- 填写技术上下文(未知项标记为 “NEEDS CLARIFICATION”)
- 从宪法中填写“宪法检查”小节
- 评估门禁(若存在未经合理解释的违规则 ERROR)
- Phase 0:生成 research.md(解决所有 NEEDS CLARIFICATION)
- Phase 1:生成 data-model.md、contracts/、quickstart.md
- Phase 1:通过运行 agent 脚本更新 agent 上下文
- 设计完成后重新评估“宪法检查”
4. **停止并汇报**:命令在 Phase 2 规划后结束。汇报分支名、IMPL_PLAN 路径与生成的产物。
## 阶段
### Phase 0:大纲与调研
1. **从上面的技术上下文中提取未知项**
- 每个 NEEDS CLARIFICATION → 一条调研任务
- 每个依赖 → 一条最佳实践任务
- 每个集成点 → 一条模式/方案任务
2. **生成并分发调研 agent**
```text
对于技术上下文中的每个未知项:
任务:"为 {feature context} 调研 {unknown}"
对于每个技术选型:
任务:"为 {domain} 场景寻找 {tech} 的最佳实践"
```
3. **在 `research.md` 中汇总结论**,格式为:
- 决策(Decision):[选择了什么]
- 理由(Rationale):[为什么这样选]
- 备选方案(Alternatives):[还评估了什么]
**输出**:research.md,且所有 NEEDS CLARIFICATION 已解决
### Phase 1:设计与契约
**前置条件:** `research.md` 已完成
1. **从功能 spec 中提取实体**`data-model.md`
- 实体名称、字段、关系
- 来自需求的校验规则
- 若适用:状态流转
2. **从功能需求生成 API 契约**
- 每个用户动作 → 一个 endpoint
- 使用标准 REST/GraphQL 模式
- 输出 OpenAPI/GraphQL schema 到 `/contracts/`
3. **更新 agent 上下文**
- 运行 `.specify/scripts/bash/update-agent-context.sh cursor-agent`
- 脚本会检测当前使用的是哪个 AI agent
- 更新对应的 agent 专属上下文文件
- 只追加本次计划中新引入的技术
- 保留标记区间内的人工补充内容
**输出**:data-model.md、/contracts/*、quickstart.md、agent 专属上下文文件
## 关键规则
- 使用绝对路径
- 门禁失败或存在未解决澄清项时直接 ERROR
This diff is collapsed. Click to expand it.
---
description: 基于现有设计产物,为该功能生成可执行、按依赖排序的 tasks.md。
handoffs:
- label: 一致性分析
agent: speckit.analyze
prompt: 执行项目一致性分析
send: true
- label: 分阶段实现
agent: speckit.implement
prompt: 按阶段开始实现
send: true
---
## 用户输入
```text
$ARGUMENTS
```
在继续之前,你**必须**先考虑用户输入(如果不为空)。
## 概述
1. **准备**:在仓库根目录运行 `.specify/scripts/bash/check-prerequisites.sh --json` 并解析 FEATURE_DIR 与 AVAILABLE_DOCS 列表。所有路径必须是绝对路径。当参数里包含单引号(例如 "I'm Groot")时,使用转义写法:如 'I'\''m Groot'(或尽量用双引号:"I'm Groot")。
2. **加载设计文档**:从 FEATURE_DIR 读取:
- **必需**:plan.md(技术栈、依赖库、结构)、spec.md(带优先级的用户故事)
- **可选**:data-model.md(实体)、contracts/(API 端点)、research.md(决策)、quickstart.md(测试场景)
- 注意:并非所有项目都有全部文档。应基于当前可用文档生成任务。
3. **执行任务生成流程**
- 加载 plan.md,提取技术栈、依赖库与项目结构
- 加载 spec.md,提取带优先级的用户故事(P1、P2、P3 等)
- 如果存在 data-model.md:提取实体并映射到用户故事
- 如果存在 contracts/:将端点映射到用户故事
- 如果存在 research.md:提取决策用于初始化相关任务
- 按用户故事组织生成任务(见下方“任务生成规则”)
- 生成依赖图,展示用户故事的完成顺序
- 为每个用户故事提供并行执行示例
- 校验任务完整性(每个用户故事包含所需任务,且可独立测试)
4. **生成 tasks.md**:以 `.specify/templates/tasks-template.md` 为结构,填充:
- 从 plan.md 读取正确的功能名称
- Phase 1:初始化任务(项目初始化)
- Phase 2:基础任务(所有用户故事的阻塞前置)
- Phase 3+:按 spec.md 的优先级为每个用户故事建一个阶段
- 每个阶段包含:故事目标、独立测试标准、测试(如有要求)、实现任务
- 最终阶段:打磨与横切关注点
- 所有任务必须遵循严格的清单格式(见下方“任务生成规则”)
- 每个任务都要写清楚文件路径
- Dependencies 章节展示故事完成顺序
- 每个故事提供并行执行示例
- Implementation strategy 章节说明实现策略(先 MVP,逐步交付)
5. **报告(Report)**:输出生成的 tasks.md 路径与摘要:
- 任务总数
- 每个用户故事的任务数
- 识别到的并行机会
- 每个故事的独立测试标准
- 建议的 MVP 范围(通常只包含用户故事 1)
- 格式校验:确认所有任务都遵循清单格式(checkbox、ID、标签、文件路径)
用于任务生成的上下文:$ARGUMENTS
tasks.md 应当可以直接执行——每个任务都必须足够具体,使得 LLM 在不依赖额外上下文的情况下也能完成。
## 任务生成规则
**关键(CRITICAL)**:任务必须按用户故事组织,以支持独立实现与独立测试。
**测试是可选项**:只有在 spec 明确要求,或用户要求 TDD 时才生成测试任务。
### 清单格式(必须)
每个任务都必须严格遵循以下格式:
```text
- [ ] [TaskID] [P?] [Story?] 包含文件路径的任务描述
```
**格式组成**
1. **勾选框(Checkbox)**:必须以 `- [ ]` 开头(Markdown checkbox)
2. **任务 ID(Task ID)**:按执行顺序递增编号(T001、T002、T003...)
3. **[P] 标记**:仅当任务可并行时才包含(不同文件,且不依赖未完成任务)
4. **[Story] 标签**:仅用于“用户故事阶段”的任务,且必须包含
- 格式:[US1][US2][US3] 等(映射 spec.md 的用户故事)
- 初始化阶段:不加 story 标签
- 基础阶段:不加 story 标签
- 用户故事阶段:必须有 story 标签
- 打磨阶段:不加 story 标签
5. **描述(Description)**:清晰描述动作,并包含准确文件路径
**示例**
- ✅ 正确:`- [ ] T001 按实现计划创建项目结构`
- ✅ 正确:`- [ ] T005 [P] 在 src/middleware/auth.py 实现认证中间件`
- ✅ 正确:`- [ ] T012 [P] [US1] 在 src/models/user.py 创建 User 模型`
- ✅ 正确:`- [ ] T014 [US1] 在 src/services/user_service.py 实现 UserService`
- ❌ 错误:`- [ ] 创建用户模型`(缺少 ID 与 Story 标签)
- ❌ 错误:`T001 [US1] 创建模型`(缺少 checkbox)
- ❌ 错误:`- [ ] [US1] 创建用户模型`(缺少 Task ID)
- ❌ 错误:`- [ ] T001 [US1] 创建模型`(缺少文件路径)
### 任务组织方式
1. **来自用户故事(spec.md)——主要组织方式**
- 每个用户故事(P1、P2、P3...)对应一个阶段
- 将所有相关组件映射到对应的故事:
- 该故事需要的模型
- 该故事需要的服务
- 该故事需要的端点/UI
- 若需要测试:该故事专属的测试任务
- 标记故事依赖(大多数故事应尽量独立)
2. **来自 contracts**
- 将每个 contract/endpoint 映射到它服务的用户故事
- 若需要测试:每个 contract 在该故事阶段中,先生成 contract 测试任务 [P],再实现
3. **来自数据模型**
- 将每个实体映射到需要它的用户故事
- 若实体服务多个故事:放入最早的故事阶段或初始化阶段
- 关系处理 → 放到对应故事阶段的服务层任务中
4. **来自初始化/基础设施**
- 共享基础设施 → 初始化阶段(Phase 1)
- 基础/阻塞任务 → 基础阶段(Phase 2)
- 故事特定的初始化 → 放到该故事阶段内
### 阶段结构
- **Phase 1**:初始化(项目初始化)
- **Phase 2**:基础(阻塞前置;必须在用户故事之前完成)
- **Phase 3+**:按优先级顺序的用户故事(P1、P2、P3...)
- 每个故事内:测试(如需)→ 模型 → 服务 → 端点 → 集成
- 每个阶段都应是一个完整且可独立测试的增量
- **最终阶段**:打磨与横切关注点
---
description: 基于现有设计产物,将已有任务转换为可执行、按依赖排序的 GitHub issue。
tools: ['github/github-mcp-server/issue_write']
---
## 用户输入
```text
$ARGUMENTS
```
在继续之前,你**必须**先考虑用户输入(如果不为空)。
## 概述
1. 在仓库根目录运行 `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` 并解析 FEATURE_DIR 与 AVAILABLE_DOCS 列表。所有路径必须是绝对路径。当参数里包含单引号(例如 "I'm Groot")时,使用转义写法:如 'I'\''m Groot'(或尽量用双引号:"I'm Groot")。
2. 从脚本输出中提取 **tasks** 文件路径。
3. 通过以下命令获取 Git 远端地址(remote):
```bash
git config --get remote.origin.url
```
> [!CAUTION]
> 只有当 remote 是 GitHub URL 时才允许继续后续步骤
4. 对任务列表中的每个任务,使用 GitHub MCP server 在与该 remote 相匹配的仓库中创建一个新 issue。
> [!CAUTION]
> 任何情况下都不要在与 remote URL 不匹配的仓库里创建 issue
---
description: "生成/更新项目原则(constitution)"
agent: agent
---
请根据当前仓库的技术栈与业务场景,生成或更新 .specify/memory/constitution.md:
- 内容使用中文
- 原则需要覆盖:工程规范、UI/样式规范、网络请求返回结构、资源链接规则、开发与发布约束
- 原则要具体可执行,避免空泛口号
- 如果已存在同名文件,保留现有有效条款,只补齐缺失部分并做结构化整理
---
description: "按任务实现并自检(implement)"
agent: agent
argument-hint: "feature_key(例如 001-xxx)"
---
你需要按 specs/<feature_key>/tasks.md 逐条完成实现,并遵循:
- 严格对照 specs/<feature_key>/spec.md 的验收标准
- 修改尽量小,避免无关重构
- 接口返回结构固定为 { code, data, msg },错误提示使用 msg
- 图片域名为 cdn.ipadbiz.cn 时追加 ?imageMogr2/thumbnail/200x/strip/quality/70
- 完成后运行现有的测试/检查脚本(如果仓库提供)
- 不要启动或重启任何服务;不要引导打开预览
---
description: "生成技术方案(plan)"
agent: agent
argument-hint: "feature_key(例如 001-xxx)"
---
基于 specs/<feature_key>/spec.md,生成 specs/<feature_key>/plan.md。
约束:
- 给出最小改动方案,优先复用现有组件、工具与目录结构
- 明确需要修改/新增的文件清单(按路径列出)
- 明确数据流、状态管理方式(如需要 pinia/route query/组件本地状态)
- 明确接口调用点与返回结构 { code, data, msg } 的处理策略
- 样式:优先 TailwindCSS 类名(项目已引入),Less 用于层级补充
- 不要启动或重启任何服务;不要引导打开预览
plan.md 输出结构:
1) 总体方案
2) 页面与路由变更
3) 组件与复用点
4) 状态管理与数据流
5) 接口与错误处理
6) 样式与响应式策略
7) 影响范围与回归清单
---
description: "生成需求规格说明(spec)"
agent: agent
argument-hint: "feature_key 与需求描述(例如 001-xxx ...)"
---
你需要把用户的需求整理成可评审的规格说明,输出到 specs/<feature_key>/spec.md。
约束:
- 只写“做什么/为什么”,不要写实现细节
- 不确定的信息必须写成 [NEEDS CLARIFICATION],并给出具体要问的问题
- 规格说明使用中文,结构清晰,便于团队协作评审
- feature_key 使用数字前缀与短横线命名,例如 001-course-share-poster
spec.md 模板:
1) 背景与目标
- 背景:
- 目标:
- 非目标:
2) 用户画像与使用场景
3) 需求范围
- 页面/入口:
- 核心流程:
- 状态与异常分支:
4) 用户故事(User Stories)
- 作为……我想……以便……
5) 验收标准(Acceptance Criteria)
- 使用可验证的条件描述
6) 交互与视觉要点
- 移动端优先(如涉及 PC/移动差异需要说明)
7) 数据与接口
- 需要的字段(仅描述数据含义,不给实现)
- 返回结构固定为 { code, data, msg }
8) 边界条件与风险
9) 待确认事项
- [NEEDS CLARIFICATION] ...
---
description: "从方案拆分可执行任务(tasks)"
agent: agent
argument-hint: "feature_key(例如 001-xxx)"
---
基于 specs/<feature_key>/plan.md,生成 specs/<feature_key>/tasks.md。
约束:
- 任务要可执行、可验收,按顺序列出
- 每条任务不超过 14 个字
- 标注必要的回归点
- 不要包含“启动服务/打开预览”相关任务
tasks.md 格式:
- [ ] 任务1
- [ ] 任务2
回归清单:
- [ ] 回归项1
- [ ] 回归项2
# mlaj 宪法
## 核心原则
### 用户需求为中心
- 以用户需求为中心,优先实现最小可用闭环,避免过度设计
### 修改尽量小且可回滚
- 修改应尽量小且可回滚,避免大范围重构
### 风格一致与复用优先
- 保持现有代码风格与目录结构一致,优先复用已有工具与组件
### 生产代码完毕后不要重启服务
- 生产代码完毕后不要重启服务
### 操作完成后不要自动打开预览
- 操作完成后不要自动打开预览
## 技术与工程约束
- 依赖管理使用 pnpm
- 构建工具使用 Vite
- 前端使用 Vue3(优先 setup 语法糖)
- 移动端 UI 优先使用 Vant
- 样式使用 Less;如果项目已引入 TailwindCSS,布局优先用 Tailwind 类名,细节用 Less 补充
- 路由使用 vue-router
- 状态管理使用 pinia(如项目已接入)
- 不引入不必要的新库;如必须新增依赖,需要在方案中说明原因与替代方案
## 接口与数据约束
- 所有网络请求返回对象结构必须为 { code, data, msg }
- code=1 表示成功,其他值表示失败;失败时保持 msg 可读
## 资源与链接约束
- 若图片域名为 cdn.ipadbiz.cn,需要自动追加 ?imageMogr2/thumbnail/200x/strip/quality/70
## 治理与管理
- 本宪法优先级高于临时约定与个人习惯;出现冲突时以本宪法为准
- 宪法变更应同步更新版本/日期信息,并确保对现有工程约束的兼容性
**版本**: [CONSTITUTION_VERSION] | **批准**: [RATIFICATION_DATE] | **最后修订**: [LAST_AMENDED_DATE]
#!/usr/bin/env bash
# 前置条件检查脚本(整合版)
#
# 本脚本为 Spec-Driven Development 工作流提供统一的前置条件检查,
# 用于替代此前分散在多个脚本中的同类功能。
#
# 用法:./check-prerequisites.sh [OPTIONS]
#
# OPTIONS:
# --json 以 JSON 格式输出
# --require-tasks 要求 tasks.md 必须存在(实现阶段使用)
# --include-tasks 在 AVAILABLE_DOCS 列表中包含 tasks.md
# --paths-only 仅输出路径变量(不做校验)
# --help, -h 显示帮助信息
#
# 输出:
# JSON 模式:{"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]}
# 文本模式:FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md
# 仅路径:REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... 等
set -e
# 解析命令行参数
JSON_MODE=false
REQUIRE_TASKS=false
INCLUDE_TASKS=false
PATHS_ONLY=false
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--require-tasks)
REQUIRE_TASKS=true
;;
--include-tasks)
INCLUDE_TASKS=true
;;
--paths-only)
PATHS_ONLY=true
;;
--help|-h)
cat << 'EOF'
用法:check-prerequisites.sh [OPTIONS]
用于 Spec-Driven Development 工作流的前置条件检查(整合版)。
选项:
--json 以 JSON 格式输出
--require-tasks 要求 tasks.md 必须存在(实现阶段使用)
--include-tasks 在 AVAILABLE_DOCS 列表中包含 tasks.md
--paths-only 仅输出路径变量(不做前置条件校验)
--help, -h 显示帮助信息
示例:
# 检查任务前置条件(需要 plan.md)
./check-prerequisites.sh --json
# 检查实现前置条件(需要 plan.md + tasks.md)
./check-prerequisites.sh --json --require-tasks --include-tasks
# 仅获取功能路径(不做校验)
./check-prerequisites.sh --paths-only
EOF
exit 0
;;
*)
echo "错误:未知选项 '$arg'。使用 --help 查看用法。" >&2
exit 1
;;
esac
done
# 引入通用函数
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# 获取功能路径并校验分支
eval $(get_feature_paths)
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
# 若为仅路径模式:输出路径后退出(支持 --json 与 --paths-only 组合)
if $PATHS_ONLY; then
if $JSON_MODE; then
# 最小 JSON 路径负载(不做校验)
printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \
"$REPO_ROOT" "$CURRENT_BRANCH" "$FEATURE_DIR" "$FEATURE_SPEC" "$IMPL_PLAN" "$TASKS"
else
echo "REPO_ROOT: $REPO_ROOT"
echo "BRANCH: $CURRENT_BRANCH"
echo "FEATURE_DIR: $FEATURE_DIR"
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "TASKS: $TASKS"
fi
exit 0
fi
# 校验必要的目录与文件
if [[ ! -d "$FEATURE_DIR" ]]; then
echo "错误:未找到功能目录:$FEATURE_DIR" >&2
echo "请先运行 /speckit.specify 以创建功能目录结构。" >&2
exit 1
fi
if [[ ! -f "$IMPL_PLAN" ]]; then
echo "错误:在 $FEATURE_DIR 中未找到 plan.md" >&2
echo "请先运行 /speckit.plan 以创建实现计划。" >&2
exit 1
fi
# 如果需要则检查 tasks.md
if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then
echo "错误:在 $FEATURE_DIR 中未找到 tasks.md" >&2
echo "请先运行 /speckit.tasks 以创建任务清单。" >&2
exit 1
fi
# 构建可用文档列表
docs=()
# 固定检查这些可选文档
[[ -f "$RESEARCH" ]] && docs+=("research.md")
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
# 检查 contracts 目录(仅当存在且非空)
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
docs+=("contracts/")
fi
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
# 若要求包含 tasks.md,且文件存在,则加入列表
if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then
docs+=("tasks.md")
fi
# 输出结果
if $JSON_MODE; then
# 构建文档 JSON 数组
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(printf '"%s",' "${docs[@]}")
json_docs="[${json_docs%,}]"
fi
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$FEATURE_DIR" "$json_docs"
else
# 文本输出
echo "FEATURE_DIR:$FEATURE_DIR"
echo "AVAILABLE_DOCS:"
# 展示各文档的存在状态
check_file "$RESEARCH" "research.md"
check_file "$DATA_MODEL" "data-model.md"
check_dir "$CONTRACTS_DIR" "contracts/"
check_file "$QUICKSTART" "quickstart.md"
if $INCLUDE_TASKS; then
check_file "$TASKS" "tasks.md"
fi
fi
#!/usr/bin/env bash
# 所有脚本共用的函数与变量
# 获取仓库根目录(非 git 仓库时提供兜底)
get_repo_root() {
if git rev-parse --show-toplevel >/dev/null 2>&1; then
git rev-parse --show-toplevel
else
# 非 git 仓库:回退为脚本所在目录向上查找
local script_dir="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
(cd "$script_dir/../../.." && pwd)
fi
}
# 获取当前分支(非 git 仓库时提供兜底)
get_current_branch() {
# 优先使用 SPECIFY_FEATURE 环境变量
if [[ -n "${SPECIFY_FEATURE:-}" ]]; then
echo "$SPECIFY_FEATURE"
return
fi
# 其次尝试从 git 读取
if git rev-parse --abbrev-ref HEAD >/dev/null 2>&1; then
git rev-parse --abbrev-ref HEAD
return
fi
# 非 git 仓库:尝试找到最新的功能目录
local repo_root=$(get_repo_root)
local specs_dir="$repo_root/specs"
if [[ -d "$specs_dir" ]]; then
local latest_feature=""
local highest=0
for dir in "$specs_dir"/*; do
if [[ -d "$dir" ]]; then
local dirname=$(basename "$dir")
if [[ "$dirname" =~ ^([0-9]{3})- ]]; then
local number=${BASH_REMATCH[1]}
number=$((10#$number))
if [[ "$number" -gt "$highest" ]]; then
highest=$number
latest_feature=$dirname
fi
fi
fi
done
if [[ -n "$latest_feature" ]]; then
echo "$latest_feature"
return
fi
fi
echo "main" # 最终兜底
}
# 检查是否为 git 仓库
has_git() {
git rev-parse --show-toplevel >/dev/null 2>&1
}
check_feature_branch() {
local branch="$1"
local has_git_repo="$2"
# 非 git 仓库无法强制分支命名,但仍输出提示
if [[ "$has_git_repo" != "true" ]]; then
echo "[specify] 警告:未检测到 Git 仓库;已跳过分支校验" >&2
return 0
fi
if [[ ! "$branch" =~ ^[0-9]{3}- ]]; then
echo "错误:当前不在功能分支。当前分支:$branch" >&2
echo "功能分支命名应类似:001-feature-name" >&2
return 1
fi
return 0
}
get_feature_dir() { echo "$1/specs/$2"; }
# 按数字前缀查找功能目录,而不是严格按分支名匹配
# 这样允许多个分支指向同一份规格(例如 004-fix-bug、004-add-feature)
find_feature_dir_by_prefix() {
local repo_root="$1"
local branch_name="$2"
local specs_dir="$repo_root/specs"
# 从分支名提取数字前缀(例如从 "004-whatever" 提取 "004")
if [[ ! "$branch_name" =~ ^([0-9]{3})- ]]; then
# 分支名不含数字前缀:回退为按分支名拼路径
echo "$specs_dir/$branch_name"
return
fi
local prefix="${BASH_REMATCH[1]}"
# 在 specs/ 下查找以该前缀开头的目录
local matches=()
if [[ -d "$specs_dir" ]]; then
for dir in "$specs_dir"/"$prefix"-*; do
if [[ -d "$dir" ]]; then
matches+=("$(basename "$dir")")
fi
done
fi
# 处理查找结果
if [[ ${#matches[@]} -eq 0 ]]; then
# 未找到:返回按分支名拼的路径(后续会给出更明确的错误)
echo "$specs_dir/$branch_name"
elif [[ ${#matches[@]} -eq 1 ]]; then
# 仅一个匹配:直接返回
echo "$specs_dir/${matches[0]}"
else
# 多个匹配:命名规范正确时不应发生
echo "错误:发现多个同前缀规格目录 '$prefix':${matches[*]}" >&2
echo "请确保每个数字前缀只对应一个规格目录。" >&2
echo "$specs_dir/$branch_name" # 返回一个路径以避免脚本中断
fi
}
get_feature_paths() {
local repo_root=$(get_repo_root)
local current_branch=$(get_current_branch)
local has_git_repo="false"
if has_git; then
has_git_repo="true"
fi
# 使用前缀匹配以支持“多分支对应同一份规格”的场景
local feature_dir=$(find_feature_dir_by_prefix "$repo_root" "$current_branch")
cat <<EOF
REPO_ROOT='$repo_root'
CURRENT_BRANCH='$current_branch'
HAS_GIT='$has_git_repo'
FEATURE_DIR='$feature_dir'
FEATURE_SPEC='$feature_dir/spec.md'
IMPL_PLAN='$feature_dir/plan.md'
TASKS='$feature_dir/tasks.md'
RESEARCH='$feature_dir/research.md'
DATA_MODEL='$feature_dir/data-model.md'
QUICKSTART='$feature_dir/quickstart.md'
CONTRACTS_DIR='$feature_dir/contracts'
EOF
}
check_file() { [[ -f "$1" ]] && echo " ✓ $2" || echo " ✗ $2"; }
check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo " ✓ $2" || echo " ✗ $2"; }
#!/usr/bin/env bash
set -e
JSON_MODE=false
SHORT_NAME=""
BRANCH_NUMBER=""
ARGS=()
i=1
while [ $i -le $# ]; do
arg="${!i}"
case "$arg" in
--json)
JSON_MODE=true
;;
--short-name)
if [ $((i + 1)) -gt $# ]; then
echo '错误:--short-name 需要提供值' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
# 检查下一个参数是否为另一个选项(以 -- 开头)
if [[ "$next_arg" == --* ]]; then
echo '错误:--short-name 需要提供值' >&2
exit 1
fi
SHORT_NAME="$next_arg"
;;
--number)
if [ $((i + 1)) -gt $# ]; then
echo '错误:--number 需要提供值' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
if [[ "$next_arg" == --* ]]; then
echo '错误:--number 需要提供值' >&2
exit 1
fi
BRANCH_NUMBER="$next_arg"
;;
--help|-h)
echo "用法:$0 [--json] [--short-name <短名>] [--number N] <功能描述>"
echo ""
echo "选项:"
echo " --json 以 JSON 格式输出"
echo " --short-name <短名> 为分支提供自定义短名(2-4 个单词)"
echo " --number N 手动指定分支编号(覆盖自动检测)"
echo " --help, -h 显示帮助信息"
echo ""
echo "示例:"
echo " $0 '新增用户登录与鉴权能力' --short-name 'user-auth'"
echo " $0 '为 API 接入 OAuth2 登录' --number 5"
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
i=$((i + 1))
done
FEATURE_DESCRIPTION="${ARGS[*]}"
if [ -z "$FEATURE_DESCRIPTION" ]; then
echo "用法:$0 [--json] [--short-name <短名>] [--number N] <功能描述>" >&2
exit 1
fi
# 通过查找项目标记来定位仓库根目录
find_repo_root() {
local dir="$1"
while [ "$dir" != "/" ]; do
if [ -d "$dir/.git" ] || [ -d "$dir/.specify" ]; then
echo "$dir"
return 0
fi
dir="$(dirname "$dir")"
done
return 1
}
# 从 specs 目录中获取最大编号
get_highest_from_specs() {
local specs_dir="$1"
local highest=0
if [ -d "$specs_dir" ]; then
for dir in "$specs_dir"/*; do
[ -d "$dir" ] || continue
dirname=$(basename "$dir")
number=$(echo "$dirname" | grep -o '^[0-9]\+' || echo "0")
number=$((10#$number))
if [ "$number" -gt "$highest" ]; then
highest=$number
fi
done
fi
echo "$highest"
}
# 从 git 分支中获取最大编号
get_highest_from_branches() {
local highest=0
# 获取所有分支(本地 + 远端)
branches=$(git branch -a 2>/dev/null || echo "")
if [ -n "$branches" ]; then
while IFS= read -r branch; do
# 清理分支名:移除前缀标记与远端前缀
clean_branch=$(echo "$branch" | sed 's/^[* ]*//; s|^remotes/[^/]*/||')
# 若分支符合 ###-*,则提取功能编号
if echo "$clean_branch" | grep -q '^[0-9]\{3\}-'; then
number=$(echo "$clean_branch" | grep -o '^[0-9]\{3\}' || echo "0")
number=$((10#$number))
if [ "$number" -gt "$highest" ]; then
highest=$number
fi
fi
done <<< "$branches"
fi
echo "$highest"
}
# 检查现有分支(本地 + 远端)并返回下一个可用编号
check_existing_branches() {
local specs_dir="$1"
# 拉取所有远端以获取最新分支信息(无远端时忽略错误)
git fetch --all --prune 2>/dev/null || true
# 获取所有分支中的最大编号(不局限于匹配 short name)
local highest_branch=$(get_highest_from_branches)
# 获取所有 specs 中的最大编号(不局限于匹配 short name)
local highest_spec=$(get_highest_from_specs "$specs_dir")
# 两者取最大值
local max_num=$highest_branch
if [ "$highest_spec" -gt "$max_num" ]; then
max_num=$highest_spec
fi
# 返回下一个编号
echo $((max_num + 1))
}
# 清理并格式化分支名
clean_branch_name() {
local name="$1"
echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//'
}
# 解析仓库根目录:优先使用 git 信息;如不可用则回退为查找仓库标记,
# 以兼容使用 --no-git 初始化的仓库。
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if git rev-parse --show-toplevel >/dev/null 2>&1; then
REPO_ROOT=$(git rev-parse --show-toplevel)
HAS_GIT=true
else
REPO_ROOT="$(find_repo_root "$SCRIPT_DIR")"
if [ -z "$REPO_ROOT" ]; then
echo "错误:无法确定仓库根目录。请在仓库内运行本脚本。" >&2
exit 1
fi
HAS_GIT=false
fi
cd "$REPO_ROOT"
SPECS_DIR="$REPO_ROOT/specs"
mkdir -p "$SPECS_DIR"
# 生成分支名:包含停用词过滤与长度过滤
generate_branch_name() {
local description="$1"
# 常见停用词(用于过滤)
local stop_words="^(i|a|an|the|to|for|of|in|on|at|by|with|from|is|are|was|were|be|been|being|have|has|had|do|does|did|will|would|should|could|can|may|might|must|shall|this|that|these|those|my|your|our|their|want|need|add|get|set)$"
# 转小写并按单词拆分
local clean_name=$(echo "$description" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/ /g')
# 过滤单词:移除停用词与长度 < 3 的词(除非在原描述中以大写出现,通常为缩写)
local meaningful_words=()
for word in $clean_name; do
# 跳过空词
[ -z "$word" ] && continue
# 保留:不属于停用词,并且(长度 >= 3 或为可能的缩写)
if ! echo "$word" | grep -qiE "$stop_words"; then
if [ ${#word} -ge 3 ]; then
meaningful_words+=("$word")
elif echo "$description" | grep -q "\b${word^^}\b"; then
# 原描述中若以大写出现则保留(很可能是缩写)
meaningful_words+=("$word")
fi
fi
done
# 若有有效词,则取前 3-4 个
if [ ${#meaningful_words[@]} -gt 0 ]; then
local max_words=3
if [ ${#meaningful_words[@]} -eq 4 ]; then max_words=4; fi
local result=""
local count=0
for word in "${meaningful_words[@]}"; do
if [ $count -ge $max_words ]; then break; fi
if [ -n "$result" ]; then result="$result-"; fi
result="$result$word"
count=$((count + 1))
done
echo "$result"
else
# 若未找到有效词:回退为原始逻辑
local cleaned=$(clean_branch_name "$description")
echo "$cleaned" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//'
fi
}
# 生成分支名
if [ -n "$SHORT_NAME" ]; then
# 使用用户提供的 short name,并做清理
BRANCH_SUFFIX=$(clean_branch_name "$SHORT_NAME")
else
# 根据描述智能过滤生成
BRANCH_SUFFIX=$(generate_branch_name "$FEATURE_DESCRIPTION")
fi
# 确定分支编号
if [ -z "$BRANCH_NUMBER" ]; then
if [ "$HAS_GIT" = true ]; then
# 检查远端已有分支
BRANCH_NUMBER=$(check_existing_branches "$SPECS_DIR")
else
# 回退为本地目录检查
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
BRANCH_NUMBER=$((HIGHEST + 1))
fi
fi
# 强制按十进制解释,避免八进制转换(例如 010 在八进制会变为 8,但这里应是十进制 10)
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
# GitHub 对分支名有 244 字节限制:必要时校验并截断
MAX_BRANCH_LENGTH=244
if [ ${#BRANCH_NAME} -gt $MAX_BRANCH_LENGTH ]; then
# 计算需要从后缀中截断的长度
# 分支名包含:功能编号(3)+ 连字符(1)= 4 个字符
MAX_SUFFIX_LENGTH=$((MAX_BRANCH_LENGTH - 4))
# 尽量按单词边界截断后缀
TRUNCATED_SUFFIX=$(echo "$BRANCH_SUFFIX" | cut -c1-$MAX_SUFFIX_LENGTH)
# 若截断产生了末尾连字符则移除
TRUNCATED_SUFFIX=$(echo "$TRUNCATED_SUFFIX" | sed 's/-$//')
ORIGINAL_BRANCH_NAME="$BRANCH_NAME"
BRANCH_NAME="${FEATURE_NUM}-${TRUNCATED_SUFFIX}"
>&2 echo "[specify] Warning: 分支名超过 GitHub 的 244 字节限制"
>&2 echo "[specify] 原始:$ORIGINAL_BRANCH_NAME${#ORIGINAL_BRANCH_NAME} 字节)"
>&2 echo "[specify] 已截断为:$BRANCH_NAME${#BRANCH_NAME} 字节)"
fi
if [ "$HAS_GIT" = true ]; then
git checkout -b "$BRANCH_NAME"
else
>&2 echo "[specify] Warning: 未检测到 Git 仓库;已跳过创建分支 $BRANCH_NAME"
fi
FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME"
mkdir -p "$FEATURE_DIR"
TEMPLATE="$REPO_ROOT/.specify/templates/spec-template.md"
SPEC_FILE="$FEATURE_DIR/spec.md"
if [ -f "$TEMPLATE" ]; then cp "$TEMPLATE" "$SPEC_FILE"; else touch "$SPEC_FILE"; fi
# 为当前会话设置 SPECIFY_FEATURE 环境变量
export SPECIFY_FEATURE="$BRANCH_NAME"
if $JSON_MODE; then
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$BRANCH_NAME" "$SPEC_FILE" "$FEATURE_NUM"
else
echo "BRANCH_NAME: $BRANCH_NAME"
echo "SPEC_FILE: $SPEC_FILE"
echo "FEATURE_NUM: $FEATURE_NUM"
echo "已设置 SPECIFY_FEATURE 环境变量为:$BRANCH_NAME"
fi
#!/usr/bin/env bash
set -e
# 解析命令行参数
JSON_MODE=false
ARGS=()
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--help|-h)
echo "用法:$0 [--json]"
echo " --json 以 JSON 格式输出结果"
echo " --help 显示帮助信息"
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
done
# 获取脚本目录并加载通用函数
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# 从通用函数获取所有路径与变量
eval $(get_feature_paths)
# 检查是否在合规的功能分支上(仅 git 仓库)
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
# 确保功能目录存在
mkdir -p "$FEATURE_DIR"
# 如果存在计划模板,则复制
TEMPLATE="$REPO_ROOT/.specify/templates/plan-template.md"
if [[ -f "$TEMPLATE" ]]; then
cp "$TEMPLATE" "$IMPL_PLAN"
echo "已复制 plan 模板到:$IMPL_PLAN"
else
echo "警告:未找到 plan 模板:$TEMPLATE"
# 如果不存在模板,则创建空的 plan 文件
touch "$IMPL_PLAN"
fi
# 输出结果
if $JSON_MODE; then
printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","SPECS_DIR":"%s","BRANCH":"%s","HAS_GIT":"%s"}\n' \
"$FEATURE_SPEC" "$IMPL_PLAN" "$FEATURE_DIR" "$CURRENT_BRANCH" "$HAS_GIT"
else
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "SPECS_DIR: $FEATURE_DIR"
echo "BRANCH: $CURRENT_BRANCH"
echo "HAS_GIT: $HAS_GIT"
fi
This diff is collapsed. Click to expand it.
# [项目名称] 开发规范
从所有功能计划自动生成。最近更新:[DATE]
## 当前技术栈
[从所有 plan.md 中提取]
## 项目结构
```text
[从计划中提取的真实结构]
```
## 常用命令
[仅保留与当前技术栈相关的命令]
## 代码风格
[语言相关规范(仅保留当前使用的语言)]
## 最近变更
[最近 3 个功能及其变更]
<!-- 手工补充开始 -->
<!-- 手工补充结束 -->
# [清单类型] 检查清单:[功能名称]
**用途**[本清单覆盖内容的简要说明]
**创建时间**[DATE]
**关联功能**[链接到 spec.md 或相关文档]
**说明**:本清单由 `/speckit.checklist` 命令基于功能上下文与需求自动生成。
<!--
============================================================================
重要:以下检查项仅为示例,用于说明格式。
/speckit.checklist 命令必须基于以下信息,将这些示例替换为真实检查项:
- 用户提出的具体检查清单诉求
- spec.md 中的功能需求
- plan.md 中的技术上下文
- tasks.md 中的实现细节
生成的 checklist 文件中不要保留这些示例项。
============================================================================
-->
## [分类 1]
- [ ] CHK001 第一条检查项(动作明确)
- [ ] CHK002 第二条检查项
- [ ] CHK003 第三条检查项
## [分类 2]
- [ ] CHK004 另一类检查项
- [ ] CHK005 带具体判定标准的检查项
- [ ] CHK006 本分类最后一条检查项
## 备注
- 完成后勾选:`[x]`
- 发现问题可直接在行内补充说明
- 可添加链接指向相关资源或文档
- 条目按编号顺序排列,便于引用
# 实现计划:[FEATURE]
**分支**`[###-feature-name]` | **日期**[DATE] | **规格说明**[link]
**输入**:来自 `/specs/[###-feature-name]/spec.md` 的功能规格说明
**说明**:本模板由 `/speckit.plan` 命令填充。执行流程可参考 `.specify/templates/commands/plan.md`
## 摘要
[从功能规格中提取:核心需求 +(结合 research 的)技术方案摘要]
## 技术上下文
<!--
必填:将本章节内容替换为项目的技术细节。
这里的结构仅用于引导迭代过程,可按需调整。
-->
**语言/版本**: [例如 Python 3.11、Swift 5.9、Rust 1.75 或 NEEDS CLARIFICATION]
**主要依赖**: [例如 FastAPI、UIKit、LLVM 或 NEEDS CLARIFICATION]
**存储**: [如适用,例如 PostgreSQL、CoreData、文件 或 N/A]
**测试**: [例如 pytest、XCTest、cargo test 或 NEEDS CLARIFICATION]
**目标平台**: [例如 Linux 服务器、iOS 15+、WASM 或 NEEDS CLARIFICATION]
**工程类型**: [single/web/mobile - 决定源码结构]
**性能目标**: [领域相关,例如 1000 req/s、10k lines/sec、60 fps 或 NEEDS CLARIFICATION]
**约束**: [领域相关,例如 <200ms p95、<100MB 内存、支持离线 或 NEEDS CLARIFICATION]
**规模/范围**: [领域相关,例如 10k 用户、1M LOC、50 个页面 或 NEEDS CLARIFICATION]
## 宪法检查
*门禁:必须在阶段 0 调研前通过;在阶段 1 设计后需要复检。*
[根据 constitution 文件确定门禁项]
## 项目结构
### 文档(本功能)
```text
specs/[###-feature]/
├── plan.md # 本文件(/speckit.plan 输出)
├── research.md # 阶段 0 输出(/speckit.plan)
├── data-model.md # 阶段 1 输出(/speckit.plan)
├── quickstart.md # 阶段 1 输出(/speckit.plan)
├── contracts/ # 阶段 1 输出(/speckit.plan)
└── tasks.md # 阶段 2 输出(/speckit.tasks - 不由 /speckit.plan 创建)
```
### 源码(仓库根目录)
<!--
必填:将下方占位树替换为本功能对应的真实目录结构。
删除未使用的选项,并将所选结构扩展为真实路径(例如 apps/admin、packages/xxx)。
最终交付的 plan.md 不应包含 “选项” 字样。
-->
```text
# [不使用则删除] 选项 1:单体工程(默认)
src/
├── models/
├── services/
├── cli/
└── lib/
tests/
├── contract/
├── integration/
└── unit/
# [不使用则删除] 选项 2:Web 应用(检测到 "frontend" + "backend" 时)
backend/
├── src/
│ ├── models/
│ ├── services/
│ └── api/
└── tests/
frontend/
├── src/
│ ├── components/
│ ├── pages/
│ └── services/
└── tests/
# [不使用则删除] 选项 3:移动端 + API(检测到 "iOS/Android" 时)
api/
└── [同 backend 的结构]
ios/ 或 android/
└── [平台相关结构:功能模块、UI 流程、平台测试]
```
**结构选择**: [说明最终选择的结构,并引用上面列出的真实目录]
## 复杂度记录
> **仅在“宪法检查”存在需要解释的违规项时填写**
| 违规项 | 必要性 | 为什么不能用更简单方案 |
|--------|--------|--------------------------|
| [例如:第 4 个子工程] | [当前需求] | [为何 3 个工程不够] |
| [例如:Repository 模式] | [具体问题] | [为何不能直接访问数据库] |
# 功能规格说明:[功能名称]
**功能分支**`[###-feature-name]`
**创建时间**[DATE]
**状态**:草稿
**输入**:用户描述:"$ARGUMENTS"
## 用户场景与验收 *(必填)*
<!--
重要:用户故事必须按重要性排序,体现为“用户旅程”优先级。
每个用户故事/旅程都必须可以独立验收——意味着即使只实现其中一个,
也应当形成可用的 MVP(最小可用产品)并能交付价值。
为每个故事分配优先级(P1、P2、P3...),其中 P1 最关键。
将每个故事视为一段可独立交付的功能切片,能够:
- 独立开发
- 独立验收
- 独立部署
- 独立向用户演示
-->
### 用户故事 1 - [简短标题](优先级:P1)
[用通俗语言描述该用户旅程]
**为什么是这个优先级**[解释价值以及为何排在该优先级]
**独立验收**[描述如何独立验收——例如:“通过 [具体动作] 即可完整验收,并交付 [具体价值]”】【示例仅供参考】
**验收场景**
1. **假设** [初始状态]**当** [动作]**则** [期望结果]
2. **假设** [初始状态]**当** [动作]**则** [期望结果]
---
### 用户故事 2 - [简短标题](优先级:P2)
[用通俗语言描述该用户旅程]
**为什么是这个优先级**[解释价值以及为何排在该优先级]
**独立验收**[描述如何独立验收]
**验收场景**
1. **假设** [初始状态]**当** [动作]**则** [期望结果]
---
### 用户故事 3 - [简短标题](优先级:P3)
[用通俗语言描述该用户旅程]
**为什么是这个优先级**[解释价值以及为何排在该优先级]
**独立验收**[描述如何独立验收]
**验收场景**
1. **假设** [初始状态]**当** [动作]**则** [期望结果]
---
[按需补充更多用户故事,并为每个故事分配优先级]
### 边界情况
<!--
需要补全:本章节内容是占位符。
请补充正确的边界情况。
-->
-[边界条件] 时会发生什么?
- 系统如何处理 [错误场景]
## 需求 *(必填)*
<!--
需要补全:本章节内容是占位符。
请补充正确的功能需求。
-->
### 功能需求
- **FR-001**:系统必须 [具体能力,例如“允许用户创建账号”]
- **FR-002**:系统必须 [具体能力,例如“校验邮箱地址”]
- **FR-003**:用户必须能够 [关键交互,例如“重置密码”]
- **FR-004**:系统必须 [数据要求,例如“持久化用户偏好”]
- **FR-005**:系统必须 [行为要求,例如“记录所有安全事件”]
*标记不清晰需求的示例:*
- **FR-006**:系统必须通过 [NEEDS CLARIFICATION:认证方式未指定——邮箱/密码、SSO、OAuth?] 对用户进行认证
- **FR-007**:系统必须保留用户数据 [NEEDS CLARIFICATION:保留期限未指定]
### 关键实体 *(当功能涉及数据时填写)*
- **[实体 1]**[表示什么;关键属性(不写实现细节)]
- **[实体 2]**[表示什么;与其他实体的关系]
## 成功标准 *(必填)*
<!--
需要补全:定义可度量的成功标准。
必须与技术实现无关,并且可度量。
-->
### 可度量结果
- **SC-001**[可度量指标,例如“用户可在 2 分钟内完成账号创建”】【示例仅供参考】
- **SC-002**[可度量指标,例如“系统在 1000 并发用户下无明显劣化”】【示例仅供参考】
- **SC-003**[用户满意度指标,例如“90% 的用户首次尝试即可完成主任务”】【示例仅供参考】
- **SC-004**[业务指标,例如“将与 [X] 相关的支持工单减少 50%”】【示例仅供参考】
---
description: "功能实现的任务清单模板"
---
# 任务清单:[功能名称]
**输入**:来自 `/specs/[###-feature-name]/` 的设计与规格文档
**前置条件**:plan.md(必需)、spec.md(用户故事必需)、research.md、data-model.md、contracts/
**测试**:下方示例包含测试任务。测试是可选的——仅在功能规格中明确要求时才需要包含。
**组织方式**:任务按用户故事分组,保证每个故事都能独立实现与独立验证。
## 格式:`[ID] [P?] [Story] 描述`
- **[P]**:可并行执行(不同文件、无依赖)
- **[Story]**:任务所属用户故事(例如 US1、US2、US3)
- 描述中包含准确的文件路径
## 路径约定
- **单体工程**:仓库根目录下 `src/``tests/`
- **Web 应用**`backend/src/``frontend/src/`
- **移动端**`api/src/``ios/src/``android/src/`
- 下方展示默认按“单体工程”组织;请根据 plan.md 的结构调整
<!--
============================================================================
重要:以下任务仅为示例,用于说明结构与写法。
/speckit.tasks 命令必须基于以下信息,将这些示例替换为真实任务:
- spec.md 的用户故事(含优先级 P1、P2、P3...)
- plan.md 的功能与实现要求
- data-model.md 的实体
- contracts/ 的接口定义
任务必须按用户故事组织,使每个故事都能:
- 独立实现
- 独立验证
- 作为 MVP 增量交付
生成的 tasks.md 文件中不要保留这些示例任务。
============================================================================
-->
## 阶段 1:准备(共享基础设施)
**目标**:项目初始化与基础结构搭建
- [ ] T001 按实现计划创建项目结构
- [ ] T002 初始化 [language] 工程并安装 [framework] 依赖
- [ ] T003 [P] 配置 lint 与格式化工具
---
## 阶段 2:基础(阻塞性前置条件)
**目标**:核心基础设施(任何用户故事开始前必须完成)
**⚠️ 关键**:在本阶段完成前,不允许开始任何用户故事的工作
基础任务示例(请根据项目实际情况调整):
- [ ] T004 建立数据库结构与迁移机制
- [ ] T005 [P] 实现认证/鉴权框架
- [ ] T006 [P] 建立 API 路由与中间件结构
- [ ] T007 创建所有故事依赖的基础模型/实体
- [ ] T008 配置错误处理与日志基础设施
- [ ] T009 建立环境配置管理
**检查点**:基础设施就绪——用户故事实现可以并行推进
---
## 阶段 3:用户故事 1 - [标题](优先级:P1)🎯 MVP
**目标**[简述该故事交付内容]
**独立验证**[如何单独验证该故事可用]
### 用户故事 1 的测试(可选:仅在明确要求测试时)⚠️
> **注意:先写测试,并确保在实现前测试会失败**
- [ ] T010 [P] [US1][endpoint] 编写契约测试:tests/contract/test_[name].py
- [ ] T011 [P] [US1][用户旅程] 编写集成测试:tests/integration/test_[name].py
### 用户故事 1 的实现
- [ ] T012 [P] [US1] 创建 [Entity1] 模型:src/models/[entity1].py
- [ ] T013 [P] [US1] 创建 [Entity2] 模型:src/models/[entity2].py
- [ ] T014 [US1] 实现 [Service]:src/services/[service].py(依赖 T012、T013)
- [ ] T015 [US1] 实现 [endpoint/feature]:src/[location]/[file].py
- [ ] T016 [US1] 增加校验与错误处理
- [ ] T017 [US1] 为用户故事 1 的关键操作补充日志
**检查点**:此时用户故事 1 应完整可用,且可独立验证
---
## 阶段 4:用户故事 2 - [标题](优先级:P2)
**目标**[简述该故事交付内容]
**独立验证**[如何单独验证该故事可用]
### 用户故事 2 的测试(可选:仅在明确要求测试时)⚠️
- [ ] T018 [P] [US2][endpoint] 编写契约测试:tests/contract/test_[name].py
- [ ] T019 [P] [US2][用户旅程] 编写集成测试:tests/integration/test_[name].py
### 用户故事 2 的实现
- [ ] T020 [P] [US2] 创建 [Entity] 模型:src/models/[entity].py
- [ ] T021 [US2] 实现 [Service]:src/services/[service].py
- [ ] T022 [US2] 实现 [endpoint/feature]:src/[location]/[file].py
- [ ] T023 [US2] 与用户故事 1 的组件集成(如需要)
**检查点**:此时用户故事 1 和 2 应都能独立工作
---
## 阶段 5:用户故事 3 - [标题](优先级:P3)
**目标**[简述该故事交付内容]
**独立验证**[如何单独验证该故事可用]
### 用户故事 3 的测试(可选:仅在明确要求测试时)⚠️
- [ ] T024 [P] [US3][endpoint] 编写契约测试:tests/contract/test_[name].py
- [ ] T025 [P] [US3][用户旅程] 编写集成测试:tests/integration/test_[name].py
### 用户故事 3 的实现
- [ ] T026 [P] [US3] 创建 [Entity] 模型:src/models/[entity].py
- [ ] T027 [US3] 实现 [Service]:src/services/[service].py
- [ ] T028 [US3] 实现 [endpoint/feature]:src/[location]/[file].py
**检查点**:此时所有用户故事都应可独立运行
---
[如需要,可按同样格式继续添加更多用户故事阶段]
---
## 阶段 N:打磨与横切关注点
**目标**:影响多个用户故事的改进项
- [ ] TXXX [P] 更新 docs/ 内的文档
- [ ] TXXX 代码清理与重构
- [ ] TXXX 跨故事的性能优化
- [ ] TXXX [P] 在 tests/unit/ 增加单测(如需)
- [ ] TXXX 安全加固
- [ ] TXXX 验证 quickstart.md
---
## 依赖与执行顺序
### 阶段依赖
- **准备(阶段 1)**:无依赖,可立即开始
- **基础(阶段 2)**:依赖准备阶段完成——阻塞所有用户故事
- **用户故事(阶段 3+)**:均依赖基础阶段完成
- 之后可并行推进(若有人力)
- 或按优先级串行推进(P1 → P2 → P3)
- **打磨(最终阶段)**:依赖所有目标用户故事完成
### 用户故事依赖
- **用户故事 1(P1)**:基础阶段后可开始——不依赖其他故事
- **用户故事 2(P2)**:基础阶段后可开始——可能与 US1 集成,但应保持可独立验证
- **用户故事 3(P3)**:基础阶段后可开始——可能与 US1/US2 集成,但应保持可独立验证
### 每个用户故事内部顺序
- 测试(如包含)必须先写,且在实现前应失败
- 先模型,再服务
- 先服务,再接口/端点
- 先核心实现,再集成
- 完成当前故事后再进入下一个优先级
### 并行机会
- 阶段 1 中标记 [P] 的任务可并行
- 阶段 2 中标记 [P] 的任务可并行(在阶段 2 内)
- 基础阶段完成后,所有用户故事可并行开始(若团队容量允许)
- 用户故事内标记 [P] 的测试可并行
- 用户故事内标记 [P] 的模型可并行
- 不同用户故事可由不同成员并行推进
---
## 并行示例:用户故事 1
```bash
# 一次性启动用户故事 1 的所有测试(如需要测试):
任务: "为 [endpoint] 编写契约测试:tests/contract/test_[name].py"
任务: "为 [用户旅程] 编写集成测试:tests/integration/test_[name].py"
# 一次性启动用户故事 1 的所有模型任务:
任务: "创建 [Entity1] 模型:src/models/[entity1].py"
任务: "创建 [Entity2] 模型:src/models/[entity2].py"
```
---
## 实施策略
### MVP 优先(仅用户故事 1)
1. 完成阶段 1:准备
2. 完成阶段 2:基础(关键:阻塞所有故事)
3. 完成阶段 3:用户故事 1
4. **停止并验证**:独立验证用户故事 1
5. 如已就绪则部署/演示
### 增量交付
1. 完成准备 + 基础 → 基础设施就绪
2. 增加用户故事 1 → 独立验证 → 部署/演示(MVP)
3. 增加用户故事 2 → 独立验证 → 部署/演示
4. 增加用户故事 3 → 独立验证 → 部署/演示
5. 每个故事都应在不破坏既有能力的前提下增量交付价值
### 多人并行策略
多人协作时:
1. 团队协作完成准备 + 基础
2. 基础完成后:
- 开发 A:用户故事 1
- 开发 B:用户故事 2
- 开发 C:用户故事 3
3. 各故事独立完成并独立集成
---
## 备注
- [P] 任务:不同文件、无依赖,可并行
- [Story] 标签:将任务映射到具体用户故事,便于追溯
- 每个用户故事都应可独立完成与独立验证
- 实现前先确认测试会失败(如有测试)
- 每完成一个任务或合理的任务组再提交
- 在任意检查点都可以停下来做独立验证
- 避免:任务描述模糊、同文件冲突、跨故事强耦合导致无法独立交付
对话处理完成一个任务后,需要更新changelog.md文件,添加一个新的版本号,版本号的格式为YYYY-MM-DD,版本号的内容为任务的描述.
---
name: vue-best-practices
description: Vue 3 TypeScript, vue-tsc, Volar, Vite, component props, testing, composition API.
---
# Vue Best Practices
## Capability Rules
| Rule | Keywords | Description |
|------|----------|-------------|
| [vue-tsc-strict-templates](rules/vue-tsc-strict-templates.md) | undefined component, template error, strictTemplates | Catch undefined components in templates |
| [fallthrough-attributes](rules/fallthrough-attributes.md) | fallthrough, $attrs, wrapper component | Type-check fallthrough attributes |
| [strict-css-modules](rules/strict-css-modules.md) | css modules, $style, typo | Catch CSS module class typos |
| [data-attributes-config](rules/data-attributes-config.md) | data-*, strictTemplates, attribute | Allow data-* attributes |
| [volar-3-breaking-changes](rules/volar-3-breaking-changes.md) | volar, vue-language-server, editor | Fix Volar 3.0 upgrade issues |
| [module-resolution-bundler](rules/module-resolution-bundler.md) | cannot find module, @vue/tsconfig, moduleResolution | Fix module resolution errors |
| [unplugin-auto-import-conflicts](rules/unplugin-auto-import-conflicts.md) | unplugin, auto-import, types any | Fix unplugin type conflicts |
| [codeactions-save-performance](rules/codeactions-save-performance.md) | slow save, vscode, performance | Fix slow save in large projects |
| [duplicate-plugin-detection](rules/duplicate-plugin-detection.md) | duplicate plugin, vite, vue plugin | Detect duplicate plugins |
| [define-model-update-event](rules/define-model-update-event.md) | defineModel, update event, undefined | Fix model update errors |
| [with-defaults-union-types](rules/with-defaults-union-types.md) | withDefaults, union type, default | Fix union type defaults |
| [deep-watch-numeric](rules/deep-watch-numeric.md) | watch, deep, array, Vue 3.5 | Efficient array watching |
| [vue-directive-comments](rules/vue-directive-comments.md) | @vue-ignore, @vue-skip, template | Control template type checking |
| [script-setup-jsdoc](rules/script-setup-jsdoc.md) | jsdoc, script setup, documentation | Add JSDoc to script setup |
| [vue-router-typed-params](rules/vue-router-typed-params.md) | route params, typed router, unplugin | Fix route params typing |
## Efficiency Rules
| Rule | Keywords | Description |
|------|----------|-------------|
| [hmr-vue-ssr](rules/hmr-vue-ssr.md) | hmr, ssr, hot reload | Fix HMR in SSR apps |
| [pinia-store-mocking](rules/pinia-store-mocking.md) | pinia, mock, vitest, store | Mock Pinia stores |
## Reference
- [Vue Language Tools](https://github.com/vuejs/language-tools)
- [Vue 3 Documentation](https://vuejs.org/)
\ No newline at end of file
---
title: Fix Slow Save Times with Code Actions Setting
impact: HIGH
impactDescription: fixes 30-60 second save delays in large Vue projects
type: capability
tags: performance, save-time, vscode, code-actions, volar
---
# Fix Slow Save Times with Code Actions Setting
**Impact: HIGH** - fixes 30-60 second save delays in large Vue projects
In large Vue projects, saving files can take 30-60+ seconds due to VSCode's code actions triggering expensive TypeScript state synchronization.
## Problem
Symptoms:
- Save operation takes 30+ seconds
- Editor becomes unresponsive during save
- CPU spikes when saving Vue files
- Happens more in larger projects
## Root Cause
VSCode emits document change events multiple times during save cycles. Each event triggers Volar to synchronize with TypeScript, causing expensive re-computation.
## Solution
Disable code actions or limit their timeout:
**Option 1: Disable code actions (fastest)**
```json
// .vscode/settings.json
{
"vue.codeActions.enabled": false
}
```
**Option 2: Limit code action time**
```json
// .vscode/settings.json
{
"vue.codeActions.savingTimeLimit": 1000
}
```
**Option 3: Disable specific code actions**
```json
// .vscode/settings.json
{
"vue.codeActions.enabled": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "never"
}
}
```
## VSCode Version Requirement
VSCode 1.81.0+ includes fixes that reduce save time issues. Upgrade if using an older version.
## Additional Optimizations
```json
// .vscode/settings.json
{
"vue.codeActions.enabled": false,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {},
"[vue]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "Vue.volar"
}
}
```
## Reference
- [Vue Language Tools Discussion #2740](https://github.com/vuejs/language-tools/discussions/2740)
---
title: Allow Data Attributes with Strict Templates
impact: MEDIUM
impactDescription: fixes data-testid and data-* attribute errors in strict mode
type: capability
tags: dataAttributes, vueCompilerOptions, strictTemplates, data-testid, testing
---
# Allow Data Attributes with Strict Templates
**Impact: MEDIUM** - fixes data-testid and data-* attribute errors in strict mode
With `strictTemplates` enabled, `data-*` attributes on components cause type errors. Use the `dataAttributes` option to allow specific patterns.
## Problem
```vue
<template>
<!-- Error: Property 'data-testid' does not exist on type... -->
<MyComponent data-testid="submit-button" />
<!-- Error: Property 'data-cy' does not exist on type... -->
<MyComponent data-cy="login-form" />
</template>
```
## Solution
Configure `dataAttributes` to allow specific patterns:
```json
// tsconfig.json or tsconfig.app.json
{
"vueCompilerOptions": {
"strictTemplates": true,
"dataAttributes": ["data-*"]
}
}
```
Now all `data-*` attributes are allowed on any component.
## Specific Patterns
You can be more selective:
```json
{
"vueCompilerOptions": {
"dataAttributes": [
"data-testid",
"data-cy",
"data-test-*"
]
}
}
```
This only allows the specified patterns, not all data attributes.
## Common Testing Attributes
For testing libraries, allow their specific attributes:
| Library | Attribute | Pattern |
|---------|-----------|---------|
| Testing Library | `data-testid` | `"data-testid"` |
| Cypress | `data-cy` | `"data-cy"` |
| Playwright | `data-testid` | `"data-testid"` |
| Generic | All data attributes | `"data-*"` |
## Reference
- [Vue Language Tools Wiki - Vue Compiler Options](https://github.com/vuejs/language-tools/wiki/Vue-Compiler-Options)
---
title: Vue 3.5+ Deep Watch Numeric Depth
impact: MEDIUM
impactDescription: enables efficient array mutation watching with numeric deep option
type: capability
tags: watch, deep, vue-3.5, array, mutation, performance
---
# Vue 3.5+ Deep Watch Numeric Depth
**Impact: MEDIUM** - enables efficient array mutation watching with numeric deep option
Vue 3.5 introduced `deep: number` for watch depth control. This allows watching array mutations without the performance cost of deep traversal.
## Symptoms
- Array mutations not triggering watch callback
- Deep watch causing performance issues on large nested objects
- Unaware of new Vue 3.5 feature
> **Note:** TypeScript error "Type 'number' is not assignable to type 'boolean'" no longer occurs with Vue 3.5+ and current TypeScript versions. The types now correctly support numeric `deep` values.
## The Feature
```typescript
// Vue 3.5+ only
watch(items, (newVal) => {
// Triggered on array mutations (push, pop, splice, etc.)
}, { deep: 1 })
```
| deep value | Behavior |
|------------|----------|
| `true` | Full recursive traversal (original behavior) |
| `false` | Only reference changes |
| `1` | One level deep - array mutations, not nested objects |
| `2` | Two levels deep |
| `n` | N levels deep |
## Fix
**Step 1: Ensure Vue 3.5+**
```bash
npm install vue@^3.5.0
```
**Step 2: Update @vue/runtime-core types**
```bash
npm install -D @vue/runtime-core@latest
```
**Step 3: Use numeric depth**
```typescript
import { watch, ref } from 'vue'
const items = ref([{ id: 1, data: { nested: 'value' } }])
// Watch array mutations only (push, pop, etc.)
watch(items, (newItems) => {
console.log('Array mutated')
}, { deep: 1 })
// Won't trigger on: items.value[0].data.nested = 'new'
// Will trigger on: items.value.push(newItem)
```
## Performance Comparison
```typescript
const largeNestedData = ref({ /* deeply nested structure */ })
// SLOW - traverses entire structure
watch(largeNestedData, handler, { deep: true })
// FAST - only watches top-level changes
watch(largeNestedData, handler, { deep: 1 })
// FASTEST - only reference changes
watch(largeNestedData, handler, { deep: false })
```
## Alternative: watchEffect for Selective Tracking
```typescript
// Only tracks properties actually accessed
watchEffect(() => {
// Only re-runs when items.value.length or first item changes
console.log(items.value.length, items.value[0]?.id)
})
```
## TypeScript Note
If TypeScript complains about numeric deep, ensure:
1. Vue version is 3.5+
2. `@vue/runtime-core` types are updated
3. tsconfig targets correct node_modules types
## Reference
- [Vue Watchers Docs](https://vuejs.org/guide/essentials/watchers.html)
- [Vue 3.5 Release Notes](https://blog.vuejs.org/posts/vue-3-5)
---
title: defineModel Fires Update Event with Undefined
impact: MEDIUM
impactDescription: fixes runtime errors from unexpected undefined in model updates
type: capability
tags: defineModel, v-model, update-event, undefined, vue-3.5
---
# defineModel Fires Update Event with Undefined
**Impact: MEDIUM** - fixes runtime errors from unexpected undefined in model updates
> **Version Note (2025):** This issue may be resolved in Vue 3.5+. Testing with Vue 3.5.26 could not reproduce the double emission with `undefined`. If you're on Vue 3.5+, verify the issue exists in your specific scenario before applying workarounds.
Components using `defineModel` may fire the `@update:model-value` event with `undefined` in certain edge cases. TypeScript types don't always reflect this behavior, potentially causing runtime errors when the parent expects a non-nullable value.
## Symptoms
- Parent component receives `undefined` unexpectedly
- Runtime error: "Cannot read property of undefined"
- Type mismatch between expected `T` and received `T | undefined`
- Issue appears when clearing/resetting the model value
## Root Cause
`defineModel` returns `Ref<T | undefined>` by default, even when `T` is non-nullable. The update event can fire with `undefined` when:
- Component unmounts
- Model is explicitly cleared
- Internal state resets
## Fix
**Option 1: Use required option (Vue 3.5+)**
```typescript
// Returns Ref<Item> instead of Ref<Item | undefined>
const model = defineModel<Item>({ required: true })
```
**Option 2: Type parent handler to accept undefined**
```vue
<template>
<MyComponent
v-model="item"
@update:model-value="handleUpdate"
/>
</template>
<script setup lang="ts">
// Handle both value and undefined
const handleUpdate = (value: Item | undefined) => {
if (value !== undefined) {
item.value = value
}
}
</script>
```
**Option 3: Use default value in defineModel**
```typescript
const model = defineModel<string>({ default: '' })
```
## Type Declaration Pattern
```typescript
// In child component
interface Props {
modelValue: Item
}
const model = defineModel<Item>({ required: true })
// Emits will be typed as (value: Item) not (value: Item | undefined)
```
## Reference
- [vuejs/core#12817](https://github.com/vuejs/core/issues/12817)
- [vuejs/core#10103](https://github.com/vuejs/core/issues/10103)
- [defineModel docs](https://vuejs.org/api/sfc-script-setup.html#definemodel)
---
title: Duplicate Vue Plugin Detection
impact: MEDIUM
impactDescription: fixes cryptic build errors from Vue plugin registered twice
type: capability
tags: vite, plugin, vue, duplicate, config, inline
---
# Duplicate Vue Plugin Detection
**Impact: MEDIUM** - fixes cryptic build errors from Vue plugin registered twice
When using Vite's JavaScript API, if the Vue plugin is loaded in `vite.config.js` and specified again in `inlineConfig`, it gets registered twice, causing cryptic build errors.
## Symptoms
- Build produces unexpected output or fails silently
- "Cannot read property of undefined" during build
- Different build behavior between CLI and JavaScript API
- Vue components render incorrectly after build
## Root Cause
Vite doesn't deduplicate plugins by name when merging configs. The Vue plugin's internal state gets corrupted when registered twice.
## Fix
**Option 1: Use configFile: false with inline plugins**
```typescript
import { build } from 'vite'
import vue from '@vitejs/plugin-vue'
await build({
configFile: false, // Don't load vite.config.js
plugins: [vue()],
// ... rest of config
})
```
**Option 2: Don't specify plugins in inlineConfig**
```typescript
// vite.config.js already has vue plugin
import { build } from 'vite'
await build({
// Don't add vue plugin here - it's in vite.config.js
root: './src',
build: { outDir: '../dist' }
})
```
**Option 3: Filter out Vue plugin before merging**
```typescript
import { build, loadConfigFromFile } from 'vite'
import vue from '@vitejs/plugin-vue'
const { config } = await loadConfigFromFile({ command: 'build', mode: 'production' })
// Remove existing Vue plugin
const filteredPlugins = config.plugins?.filter(
p => !p || (Array.isArray(p) ? false : p.name !== 'vite:vue')
) || []
await build({
...config,
plugins: [...filteredPlugins, vue({ /* your options */ })]
})
```
## Detection Script
Add this to debug plugin registration:
```typescript
// vite.config.ts
export default defineConfig({
plugins: [
vue(),
{
name: 'debug-plugins',
configResolved(config) {
const vuePlugins = config.plugins.filter(p => p.name?.includes('vue'))
if (vuePlugins.length > 1) {
console.warn('WARNING: Multiple Vue plugins detected:', vuePlugins.map(p => p.name))
}
}
}
]
})
```
## Common Scenarios
| Scenario | Solution |
|----------|----------|
| Using `vite.createServer()` | Use `configFile: false` |
| Build script with custom config | Don't duplicate plugins |
| Monorepo with shared config | Check for plugin inheritance |
## Reference
- [Vite Issue #5335](https://github.com/vitejs/vite/issues/5335)
- [Vite JavaScript API](https://vite.dev/guide/api-javascript.html)
---
title: Enable Fallthrough Attributes Type Checking
impact: HIGH
impactDescription: enables type-safe fallthrough attributes in component libraries
type: capability
tags: fallthroughAttributes, vueCompilerOptions, component-library, wrapper-components
---
# Enable Fallthrough Attributes Type Checking
**Impact: MEDIUM** - enables type-aware attribute forwarding in component libraries
When building component libraries with wrapper components, enable `fallthroughAttributes` to get IDE autocomplete for attributes that will be forwarded to child elements.
## What It Does
Wrapper components that pass attributes to child elements can benefit from type-aware completion:
```vue
<!-- MyButton.vue - wrapper around native button -->
<template>
<button v-bind="$attrs"><slot /></button>
</template>
```
## Solution
Enable `fallthroughAttributes` in your tsconfig:
```json
// tsconfig.json or tsconfig.app.json
{
"vueCompilerOptions": {
"fallthroughAttributes": true
}
}
```
## How It Works
When `fallthroughAttributes: true`:
- Vue Language Server analyzes which element receives `$attrs`
- IDE autocomplete suggests valid attributes for the target element
- Helps developers discover available attributes
> **Note:** This primarily enables IDE autocomplete for valid fallthrough attributes. It does NOT reject invalid attributes as type errors - arbitrary attributes are still allowed.
## Related Options
Combine with `strictTemplates` for comprehensive checking:
```json
{
"vueCompilerOptions": {
"strictTemplates": true,
"fallthroughAttributes": true
}
}
```
## Reference
- [Vue Language Tools Wiki - Vue Compiler Options](https://github.com/vuejs/language-tools/wiki/Vue-Compiler-Options)
---
title: HMR Debugging for Vue SSR
impact: MEDIUM
impactDescription: fixes Hot Module Replacement breaking in Vue SSR applications
type: efficiency
tags: vite, hmr, ssr, vue, hot-reload, server-side-rendering
---
# HMR Debugging for Vue SSR
**Impact: MEDIUM** - fixes Hot Module Replacement breaking in Vue SSR applications
Hot Module Replacement breaks when modifying Vue component `<script setup>` sections in SSR applications. Changes cause errors instead of smooth updates, requiring full page reloads.
## Symptoms
- HMR works for `<template>` changes but breaks for `<script setup>`
- "Cannot read property of undefined" after saving
- Full page reload required after script changes
- HMR works in dev:client but not dev:ssr
## Root Cause
SSR mode has a different transformation pipeline. The Vue plugin's HMR boundary detection doesn't handle SSR modules the same way as client modules.
## Fix
**Step 1: Ensure correct SSR plugin configuration**
```typescript
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
ssr: {
// Don't externalize these for HMR to work
noExternal: ['vue', '@vue/runtime-core', '@vue/runtime-dom']
}
})
```
**Step 2: Configure dev server for SSR HMR**
```typescript
// server.ts
import { createServer } from 'vite'
const vite = await createServer({
server: { middlewareMode: true },
appType: 'custom'
})
// Use vite.ssrLoadModule for server-side imports
const { render } = await vite.ssrLoadModule('/src/entry-server.ts')
// Handle HMR
vite.watcher.on('change', async (file) => {
if (file.endsWith('.vue')) {
// Invalidate the module
const mod = vite.moduleGraph.getModuleById(file)
if (mod) {
vite.moduleGraph.invalidateModule(mod)
}
}
})
```
**Step 3: Add HMR acceptance in entry-server**
```typescript
// entry-server.ts
import { createApp } from './main'
export async function render(url: string) {
const app = createApp()
// ... render logic
}
// Accept HMR updates
if (import.meta.hot) {
import.meta.hot.accept()
}
```
## Framework-Specific Solutions
### Nuxt 3
HMR should work out of the box. If not:
```bash
rm -rf .nuxt node_modules/.vite
npm install
npm run dev
```
### Vite SSR Template
Ensure you're using the latest `@vitejs/plugin-vue`:
```bash
npm install @vitejs/plugin-vue@latest
```
## Debugging
Enable verbose HMR logging:
```typescript
// vite.config.ts
export default defineConfig({
server: {
hmr: {
overlay: true
}
},
logLevel: 'info' // Shows HMR updates
})
```
## Known Limitations
- HMR for `<script>` (not `<script setup>`) may require full reload
- SSR components with external dependencies may not hot-reload
- State is not preserved for SSR components (expected behavior)
## Reference
- [vite-plugin-vue#525](https://github.com/vitejs/vite-plugin-vue/issues/525)
- [Vite SSR Guide](https://vite.dev/guide/ssr.html)
---
title: moduleResolution Bundler Migration Issues
impact: HIGH
impactDescription: fixes "Cannot find module" errors after @vue/tsconfig upgrade
type: capability
tags: moduleResolution, bundler, tsconfig, vue-tsconfig, node, esm
---
# moduleResolution Bundler Migration Issues
**Impact: HIGH** - fixes "Cannot find module" errors after @vue/tsconfig upgrade
Recent versions of `@vue/tsconfig` changed `moduleResolution` from `"node"` to `"bundler"`. This can break existing projects with errors like "Cannot find module 'vue'" or issues with `resolveJsonModule`.
## Symptoms
- `Cannot find module 'vue'` or other packages
- `Option '--resolveJsonModule' cannot be specified without 'node' module resolution`
- Errors appear after updating `@vue/tsconfig`
- Some third-party packages no longer resolve
## Root Cause
`moduleResolution: "bundler"` requires:
1. TypeScript 5.0+
2. Packages to have proper `exports` field in package.json
3. Different resolution rules than Node.js classic resolution
## Fix
**Option 1: Ensure TypeScript 5.0+ everywhere**
```bash
npm install -D typescript@^5.0.0
```
In monorepos, ALL packages must use TypeScript 5.0+.
**Option 2: Add compatibility workaround**
```json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"resolvePackageJsonExports": false
}
}
```
Setting `resolvePackageJsonExports: false` restores compatibility with packages that don't have proper exports.
**Option 3: Revert to Node resolution**
```json
{
"compilerOptions": {
"moduleResolution": "node"
}
}
```
## Which Packages Break?
Packages break if they:
- Lack `exports` field in package.json
- Have incorrect `exports` configuration
- Rely on Node.js-specific resolution behavior
## Diagnosis
```bash
# Check which resolution is being used
cat tsconfig.json | grep moduleResolution
# Test if a specific module resolves
npx tsc --traceResolution 2>&1 | grep "module-name"
```
## Reference
- [vuejs/tsconfig#8](https://github.com/vuejs/tsconfig/issues/8)
- [TypeScript moduleResolution docs](https://www.typescriptlang.org/tsconfig#moduleResolution)
- [Vite discussion#14001](https://github.com/vitejs/vite/discussions/14001)
---
title: Mocking Pinia Stores with Vitest
impact: HIGH
impactDescription: properly mocks Pinia stores in component tests
type: efficiency
tags: pinia, vitest, testing, mock, createTestingPinia, store
---
# Mocking Pinia Stores with Vitest
**Impact: HIGH** - properly mocks Pinia stores in component tests
Developers struggle to properly mock Pinia stores: `createTestingPinia` requires explicit `createSpy` configuration, and "injection Symbol(pinia) not found" errors occur without proper setup.
> **Important (@pinia/testing 1.0+):** The `createSpy` option is **REQUIRED**, not optional. Omitting it throws an error: "You must configure the `createSpy` option."
## Symptoms
- "injection Symbol(pinia) not found" error
- "You must configure the `createSpy` option" error
- Actions not properly mocked
- Store state not reset between tests
## Fix
**Pattern 1: Basic setup with createTestingPinia**
```typescript
import { mount } from '@vue/test-utils'
import { createTestingPinia } from '@pinia/testing'
import { vi } from 'vitest'
import MyComponent from './MyComponent.vue'
import { useCounterStore } from '@/stores/counter'
test('component uses store', async () => {
const wrapper = mount(MyComponent, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn, // REQUIRED in @pinia/testing 1.0+
initialState: {
counter: { count: 10 } // Set initial state
}
})
]
}
})
// Get the store instance AFTER mounting
const store = useCounterStore()
// Actions are automatically stubbed
await wrapper.find('button').trigger('click')
expect(store.increment).toHaveBeenCalled()
})
```
**Pattern 2: Customize action behavior**
```typescript
test('component handles async action', async () => {
const wrapper = mount(MyComponent, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn,
stubActions: false // Don't stub, use real actions
})
]
}
})
const store = useCounterStore()
// Override specific action
store.fetchData = vi.fn().mockResolvedValue({ items: [] })
await wrapper.find('.load-button').trigger('click')
expect(store.fetchData).toHaveBeenCalled()
})
```
**Pattern 3: Testing store directly**
```typescript
import { setActivePinia, createPinia } from 'pinia'
import { useCounterStore } from '@/stores/counter'
describe('Counter Store', () => {
beforeEach(() => {
setActivePinia(createPinia())
})
test('increments count', () => {
const store = useCounterStore()
expect(store.count).toBe(0)
store.increment()
expect(store.count).toBe(1)
})
})
```
## Setup Store with Vitest
```typescript
// stores/counter.ts - Setup store syntax
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
// Test file
test('setup store works', async () => {
const pinia = createTestingPinia({
createSpy: vi.fn,
initialState: {
counter: { count: 5 }
}
})
const wrapper = mount(MyComponent, {
global: { plugins: [pinia] }
})
const store = useCounterStore()
expect(store.count).toBe(5)
expect(store.doubleCount).toBe(10)
})
```
## Reset Between Tests
```typescript
describe('Store Tests', () => {
let pinia: Pinia
beforeEach(() => {
pinia = createTestingPinia({
createSpy: vi.fn
})
})
afterEach(() => {
vi.clearAllMocks()
})
test('test 1', () => { /* ... */ })
test('test 2', () => { /* ... */ })
})
```
## Reference
- [Pinia Testing Guide](https://pinia.vuejs.org/cookbook/testing.html)
- [Pinia Discussion #2092](https://github.com/vuejs/pinia/discussions/2092)
---
title: JSDoc Documentation for Script Setup Components
impact: MEDIUM
impactDescription: enables proper documentation for composition API components
type: capability
tags: jsdoc, script-setup, documentation, composition-api, component
---
# JSDoc Documentation for Script Setup Components
**Impact: MEDIUM** - enables proper documentation for composition API components
`<script setup>` doesn't have an obvious place to attach JSDoc comments for the component itself. Use a dual-script pattern.
## Problem
**Incorrect:**
```vue
<script setup lang="ts">
/**
* This comment doesn't appear in IDE hover or docs
* @component
*/
import { ref } from 'vue'
const count = ref(0)
</script>
```
JSDoc comments inside `<script setup>` don't attach to the component export because there's no explicit export statement.
## Solution
Use both `<script>` and `<script setup>` blocks:
**Correct:**
```vue
<script lang="ts">
/**
* A counter component that displays and increments a value.
*
* @example
* ```vue
* <Counter :initial="5" @update="handleUpdate" />
* ```
*
* @component
*/
export default {}
</script>
<script setup lang="ts">
import { ref } from 'vue'
const props = defineProps<{
/** Starting value for the counter */
initial?: number
}>()
const emit = defineEmits<{
/** Emitted when counter value changes */
update: [value: number]
}>()
const count = ref(props.initial ?? 0)
</script>
```
## How It Works
- The regular `<script>` block's default export is merged with `<script setup>`
- JSDoc on `export default {}` attaches to the component
- Props and emits JSDoc in `<script setup>` still work normally
## What Gets Documented
| Location | Shows In |
|----------|----------|
| `export default {}` JSDoc | Component import hover |
| `defineProps` JSDoc | Prop hover in templates |
| `defineEmits` JSDoc | Event handler hover |
## Reference
- [Vue Language Tools Discussion #5932](https://github.com/vuejs/language-tools/discussions/5932)
---
title: Enable Strict CSS Modules Type Checking
impact: MEDIUM
impactDescription: catches typos in CSS module class names at compile time
type: capability
tags: strictCssModules, vueCompilerOptions, css-modules, style-module
---
# Enable Strict CSS Modules Type Checking
**Impact: MEDIUM** - catches typos in CSS module class names at compile time
When using CSS modules with `<style module>`, Vue doesn't validate class names by default. Enable `strictCssModules` to catch typos and undefined classes.
## Problem
CSS module class name errors go undetected:
```vue
<script setup lang="ts">
// No error for typo in class name
</script>
<template>
<div :class="$style.buttn">Click me</div>
</template>
<style module>
.button {
background: blue;
}
</style>
```
The typo `buttn` instead of `button` silently fails at runtime.
## Solution
Enable `strictCssModules` in your tsconfig:
```json
// tsconfig.json or tsconfig.app.json
{
"vueCompilerOptions": {
"strictCssModules": true
}
}
```
Now `$style.buttn` will show a type error because `buttn` doesn't exist in the CSS module.
## What Gets Checked
| Access | With strictCssModules |
|--------|----------------------|
| `$style.validClass` | OK |
| `$style.typo` | Error: Property 'typo' does not exist |
| `$style['dynamic']` | OK (dynamic access not checked) |
## Limitations
- Only checks static property access (`$style.className`)
- Dynamic access (`$style[variable]`) is not validated
- Only works with `<style module>`, not external CSS files
## Reference
- [Vue Language Tools Wiki - Vue Compiler Options](https://github.com/vuejs/language-tools/wiki/Vue-Compiler-Options)
---
title: unplugin-vue-components and unplugin-auto-import Type Conflicts
impact: HIGH
impactDescription: fixes component types resolving as any when using both plugins
type: capability
tags: unplugin-vue-components, unplugin-auto-import, types, any, dts
---
# unplugin-vue-components and unplugin-auto-import Type Conflicts
**Impact: HIGH** - fixes component types resolving as any when using both plugins
Installing both `unplugin-vue-components` and `unplugin-auto-import` can cause component types to resolve as `any`. The generated `.d.ts` files conflict with each other.
## Symptoms
- Components typed as `any` instead of proper component types
- No autocomplete for component props
- No type errors for invalid props
- Types work when using only one plugin but break with both
## Root Cause
Both plugins generate declaration files (`components.d.ts` and `auto-imports.d.ts`) that can have conflicting declarations. TypeScript declaration merging fails silently.
## Fix
**Step 1: Ensure both .d.ts files are in tsconfig include**
```json
{
"include": [
"src/**/*.ts",
"src/**/*.vue",
"components.d.ts",
"auto-imports.d.ts"
]
}
```
**Step 2: Set explicit, different dts paths**
```typescript
// vite.config.ts
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
Components({
dts: 'src/types/components.d.ts' // Explicit unique path
}),
AutoImport({
dts: 'src/types/auto-imports.d.ts' // Explicit unique path
})
]
})
```
**Step 3: Regenerate type files**
```bash
# Delete existing .d.ts files
rm components.d.ts auto-imports.d.ts
# Restart dev server to regenerate
npm run dev
```
**Step 4: Verify no duplicate declarations**
Check that the same component isn't declared in both files.
## Plugin Order Matters
Configure Components plugin AFTER AutoImport:
```typescript
plugins: [
AutoImport({ /* ... */ }),
Components({ /* ... */ }) // Must come after AutoImport
]
```
## Common Mistake: Duplicate Imports
Don't configure the same import in both plugins:
```typescript
// Wrong - Vue imported in both
AutoImport({
imports: ['vue']
})
Components({
resolvers: [/* includes Vue components */]
})
```
## Reference
- [unplugin-vue-components#640](https://github.com/unplugin/unplugin-vue-components/issues/640)
- [unplugin-auto-import docs](https://github.com/unplugin/unplugin-auto-import)
---
title: Volar 3.0 Breaking Changes
impact: HIGH
impactDescription: fixes editor integration after Volar/vue-language-server upgrade
type: capability
tags: volar, vue-language-server, neovim, vscode, ide, ts_ls, vtsls
---
# Volar 3.0 Breaking Changes
**Impact: HIGH** - fixes editor integration after Volar/vue-language-server upgrade
Volar 3.0 (vue-language-server 3.x) introduced breaking changes to the language server protocol. Editors configured for Volar 2.x will break with errors like "vue_ls doesn't work with ts_ls.. it expects vtsls".
## Symptoms
- `vue_ls doesn't work with ts_ls`
- TypeScript features stop working in Vue files
- No autocomplete, type hints, or error highlighting
- Editor shows "Language server initialization failed"
## Fix by Editor
### VSCode
Update the "Vue - Official" extension to latest version. It manages the language server automatically.
### NeoVim (nvim-lspconfig)
**Option 1: Use vtsls instead of ts_ls**
```lua
-- Replace ts_ls/tsserver with vtsls
require('lspconfig').vtsls.setup({})
require('lspconfig').volar.setup({})
```
**Option 2: Downgrade vue-language-server**
```bash
npm install -g @vue/language-server@2.1.10
```
### JetBrains IDEs
Update to latest Vue plugin. If issues persist, disable and re-enable the Vue plugin.
## What Changed in 3.0
| Feature | Volar 2.x | Volar 3.0 |
|---------|-----------|-----------|
| Package name | volar | vue_ls |
| TypeScript integration | ts_ls/tsserver | vtsls required |
| Hybrid mode | Optional | Default |
## Workaround: Stay on 2.x
If upgrading is not possible:
```bash
npm install -g @vue/language-server@^2.0.0
```
Pin in your project's package.json to prevent accidental upgrades.
## Reference
- [vuejs/language-tools#5598](https://github.com/vuejs/language-tools/issues/5598)
- [NeoVim Vue Setup Guide](https://dev.to/danwalsh/solved-vue-3-typescript-inlay-hint-support-in-neovim-53ej)
---
title: Vue Template Directive Comments
impact: HIGH
impactDescription: enables fine-grained control over template type checking
type: capability
tags: vue-directive, vue-ignore, vue-expect-error, vue-skip, template, type-checking
---
# Vue Template Directive Comments
**Impact: HIGH** - enables fine-grained control over template type checking
Vue Language Tools supports special directive comments to control type checking behavior in templates.
## Available Directives
### @vue-ignore
Suppress type errors for the next line:
```vue
<template>
<!-- @vue-ignore -->
<Component :prop="valueWithTypeError" />
</template>
```
### @vue-expect-error
Assert that the next line should have a type error (useful for testing):
```vue
<template>
<!-- @vue-expect-error -->
<Component :invalid-prop="value" />
</template>
```
### @vue-skip
Skip type checking for an entire block:
```vue
<template>
<!-- @vue-skip -->
<div>
<!-- Everything in here is not type-checked -->
<LegacyComponent :any="props" :go="here" />
</div>
</template>
```
### @vue-generic
Declare template-level generic types:
```vue
<template>
<!-- @vue-generic {T extends string} -->
<GenericList :items="items as T[]" />
</template>
```
## Use Cases
- Migrating legacy components with incomplete types
- Working with third-party components that have incorrect type definitions
- Temporarily suppressing errors during refactoring
- Testing that certain patterns produce expected type errors
## Reference
- [Vue Language Tools Wiki - Directive Comments](https://github.com/vuejs/language-tools/wiki/Directive-Comments)
---
title: Vue Router useRoute Params Union Type Narrowing
impact: MEDIUM
impactDescription: fixes "Property does not exist" errors with typed route params
type: capability
tags: vue-router, useRoute, unplugin-vue-router, typed-routes, params
---
# Vue Router useRoute Params Union Type Narrowing
**Impact: MEDIUM** - fixes "Property does not exist" errors with typed route params
With `unplugin-vue-router` typed routes, `route.params` becomes a union of ALL page param types. TypeScript cannot narrow `Record<never, never> | { id: string }` properly, causing "Property 'id' does not exist" errors even on the correct page.
## Symptoms
- "Property 'id' does not exist on type 'RouteParams'"
- `route.params.id` shows as `string | undefined` everywhere
- Union type of all route params instead of specific route
- Type narrowing with `if (route.name === 'users-id')` doesn't work
## Root Cause
`unplugin-vue-router` generates a union type of all possible route params. TypeScript's control flow analysis can't narrow this union based on route name checks.
## Fix
**Option 1: Pass route name to useRoute (recommended)**
```typescript
// pages/users/[id].vue
import { useRoute } from 'vue-router/auto'
// Specify the route path for proper typing
const route = useRoute('/users/[id]')
// Now properly typed as { id: string }
console.log(route.params.id) // string, not string | undefined
```
**Option 2: Type assertion with specific route**
```typescript
import { useRoute } from 'vue-router'
import type { RouteLocationNormalized } from 'vue-router/auto-routes'
const route = useRoute() as RouteLocationNormalized<'/users/[id]'>
route.params.id // Properly typed
```
**Option 3: Define route-specific param type**
```typescript
// In your page component
interface UserRouteParams {
id: string
}
const route = useRoute()
const { id } = route.params as UserRouteParams
```
## Required tsconfig Setting
Ensure `moduleResolution: "bundler"` for unplugin-vue-router:
```json
{
"compilerOptions": {
"moduleResolution": "bundler"
}
}
```
## Caveat: Route Name Format
The route name matches the file path pattern:
- `pages/users/[id].vue``/users/[id]`
- `pages/posts/[slug]/comments.vue``/posts/[slug]/comments`
## Reference
- [unplugin-vue-router#337](https://github.com/posva/unplugin-vue-router/issues/337)
- [unplugin-vue-router#176](https://github.com/posva/unplugin-vue-router/discussions/176)
- [unplugin-vue-router TypeScript docs](https://uvr.esm.is/guide/typescript.html)
---
title: Enable Strict Template Checking
impact: HIGH
impactDescription: catches undefined components and props at compile time
type: capability
tags: vue-tsc, typescript, type-checking, templates, vueCompilerOptions
---
# Enable Strict Template Checking
**Impact: HIGH** - catches undefined components and props at compile time
By default, vue-tsc does not report errors for undefined components in templates. Enable `strictTemplates` to catch these issues during type checking.
## Which tsconfig?
Add `vueCompilerOptions` to the tsconfig that includes Vue source files. In projects with multiple tsconfigs (like those created with `create-vue`), this is typically `tsconfig.app.json`, not the root `tsconfig.json` or `tsconfig.node.json`.
**Incorrect (missing strict checking):**
```json
{
"compilerOptions": {
"strict": true
}
// vueCompilerOptions not configured - undefined components won't error
}
```
**Correct (strict template checking enabled):**
```json
{
"compilerOptions": {
"strict": true
},
"vueCompilerOptions": {
"strictTemplates": true
}
}
```
## Available Options
| Option | Default | Effect |
|--------|---------|--------|
| `strictTemplates` | `false` | Enables all checkUnknown* options below |
| `checkUnknownComponents` | `false` | Error on undefined/unregistered components |
| `checkUnknownProps` | `false` | Error on props not declared in component definition |
| `checkUnknownEvents` | `false` | Error on events not declared via `defineEmits` |
| `checkUnknownDirectives` | `false` | Error on unregistered custom directives |
## Granular Control
If `strictTemplates` is too strict, enable individual checks:
```json
{
"vueCompilerOptions": {
"checkUnknownComponents": true,
"checkUnknownProps": false
}
}
```
## Reference
- [Vue Compiler Options](https://github.com/vuejs/language-tools/wiki/Vue-Compiler-Options)
- [Vite Vue+TS Template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-vue-ts)
---
title: withDefaults Incorrect Default with Union Types
impact: MEDIUM
impactDescription: fixes incorrect default value behavior with union type props
type: capability
tags: withDefaults, defineProps, union-types, defaults, vue-3.5
---
# withDefaults Incorrect Default with Union Types
**Impact: MEDIUM** - fixes spurious "Missing required prop" warning with union type props
Using `withDefaults` with union types like `false | string` may produce a Vue runtime warning "Missing required prop" even when a default is provided. The runtime value IS applied correctly, but the warning can be confusing.
## Symptoms
- Vue warns "Missing required prop" despite default being set
- Warning appears only with union types like `false | string`
- TypeScript types are correct
- Runtime value IS correct (the default is applied)
## Problematic Pattern
```typescript
// This produces a spurious warning (but works at runtime)
interface Props {
value: false | string // Union type
}
const props = withDefaults(defineProps<Props>(), {
value: 'default' // Runtime value IS correct, but Vue warns about missing prop
})
```
## Fix
**Option 1: Use Reactive Props Destructure (Vue 3.5+)**
```vue
<script setup lang="ts">
interface Props {
value: false | string
}
// Preferred in Vue 3.5+
const { value = 'default' } = defineProps<Props>()
</script>
```
**Option 2: Use runtime declaration**
```vue
<script setup lang="ts">
const props = defineProps({
value: {
type: [Boolean, String] as PropType<false | string>,
default: 'default'
}
})
</script>
```
**Option 3: Split into separate props**
```typescript
interface Props {
enabled: boolean
customValue?: string
}
const props = withDefaults(defineProps<Props>(), {
enabled: false,
customValue: 'default'
})
```
## Why Reactive Props Destructure Works
Vue 3.5's Reactive Props Destructure handles default values at the destructuring level, bypassing the type inference issues with `withDefaults`.
```typescript
// The default is applied during destructuring, not type inference
const { prop = 'default' } = defineProps<{ prop?: string }>()
```
## Enable Reactive Props Destructure
This is enabled by default in Vue 3.5+. For older versions:
```javascript
// vite.config.js
export default {
plugins: [
vue({
script: {
propsDestructure: true
}
})
]
}
```
## Reference
- [vuejs/core#12897](https://github.com/vuejs/core/issues/12897)
- [Reactive Props Destructure RFC](https://github.com/vuejs/rfcs/discussions/502)
# 架构实现与工程配置
## 入口与初始化
- 应用入口:[/src/main.js](file:///Users/huyirui/program/itomix/git/mlaj/src/main.js)
- 创建 App、注册全局 Icon 组件、挂载路由
- 全局注入 axios 到 app.config.globalProperties.$http
- 根组件:[/src/App.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/App.vue)
- 初始化全局认证与购物车:provideAuth / provideCart
- 生产环境 + 微信环境:初始化微信 JSSDK(配置签名 URL)
- 生产环境:版本更新探测(弹窗提示刷新)
## 路由与权限
- 路由入口:[/src/router/index.js](file:///Users/huyirui/program/itomix/git/mlaj/src/router/index.js)
- Hash 路由:createWebHashHistory(import.meta.env.VITE_BASE || '/')
- beforeEach:统一登录页回跳处理,并在必要时探测“是否已登录”
- 鉴权策略:[/src/router/guards.js](file:///Users/huyirui/program/itomix/git/mlaj/src/router/guards.js)
- 白名单 + meta.requiresAuth 双策略判断
- 未登录时重定向 /login 并带 redirect
- 微信授权策略:[/src/router/guards.js](file:///Users/huyirui/program/itomix/git/mlaj/src/router/guards.js)
- 不在路由守卫自动触发授权,避免循环
- 仅在用户触发(如点击微信图标/购买流程探测)时调用 startWxAuth
## 请求与登录态注入
- Axios 封装:[/src/utils/axios.js](file:///Users/huyirui/program/itomix/git/mlaj/src/utils/axios.js)
- 请求拦截:动态读取本地 user_info 并注入 User-Id / User-Token
- 响应拦截:code=401 时,仅当当前路由确实需要登录才跳转登录(公开页面不强制跳转)
- 登录态管理:[/src/contexts/auth.js](file:///Users/huyirui/program/itomix/git/mlaj/src/contexts/auth.js)
- provide/inject 维护 currentUser/loading/login/logout
- localStorage 持久化 currentUser
- 初始化流程中会探测授权/登录态并拉取用户信息
## 购物车与结算
- 购物车上下文:[/src/contexts/cart.js](file:///Users/huyirui/program/itomix/git/mlaj/src/contexts/cart.js)
- 单品/多品两种模式(App.vue 默认使用单品模式)
- localStorage 带时间戳的过期策略(默认一天过期)
- handleCheckout 负责构建订单数据并提交订单
## 上传与预览
- 上传工具:[/src/utils/upload.js](file:///Users/huyirui/program/itomix/git/mlaj/src/utils/upload.js)[/src/utils/qiniuFileHash.js](file:///Users/huyirui/program/itomix/git/mlaj/src/utils/qiniuFileHash.js)
- 前端计算文件 Hash,支持“秒传检测 + 直传对象存储”
- 关键业务复用:[/src/composables/useCheckin.js](file:///Users/huyirui/program/itomix/git/mlaj/src/composables/useCheckin.js)
- 打卡/作业提交流程:校验、上传、提交、编辑回填等
- 预览组件:[/src/components/media](file:///Users/huyirui/program/itomix/git/mlaj/src/components/media)
- 视频/音频播放器、PDF/Office 预览等
## Vite 配置与环境变量
- Vite 配置:[/vite.config.js](file:///Users/huyirui/program/itomix/git/mlaj/vite.config.js)
- 自动按需引入 Vant 组件(unplugin-auto-import / unplugin-vue-components)
- 别名:@ / @components / @utils / @api 等
- 本地代理:createProxy(viteEnv.VITE_PROXY_PREFIX, viteEnv.VITE_PROXY_TARGET)
- 环境变量示例:[.env](file:///Users/huyirui/program/itomix/git/mlaj/.env)
- VITE_PORT:开发端口
- VITE_PROXY_TARGET / VITE_PROXY_PREFIX:接口代理目标与前缀
- VITE_OUTDIR:构建输出目录
- VITE_CONSOLE:调试开关
## 目录结构(详细)
```
mlaj/
├── build/ # Vite 代理封装
├── docs/ # 项目文档(本目录)
├── public/ # 静态资源
├── src/
│ ├── api/ # 按业务域拆分的接口封装(auth/course/checkin/teacher/...)
│ ├── assets/ # 图片等资源
│ ├── common/ # 常量
│ ├── components/ # 组件(按业务域归类)
│ ├── composables/ # 组合式函数(逻辑复用,含单测)
│ ├── contexts/ # 全局状态(provide/inject:auth/cart)
│ ├── router/ # 路由定义与守卫
│ ├── utils/ # 工具层(axios、上传、鉴权存储、版本更新等)
│ └── views/ # 页面(按业务域归类)
├── tailwind.config.js # Tailwind 配置
└── vite.config.js # Vite 配置
```
# 功能更新记录(Recent Changes)
说明:该章节从 README 迁移到本文件,避免 README 过长。后续新增变更建议追加在文件顶部。
## 2026-01-25
- 新增「暂存用户打卡信息」开发规划:[/docs/plan/暂存用户打卡信息.md](file:///Users/huyirui/program/itomix/git/mlaj/docs/plan/%E6%9A%82%E5%AD%98%E7%94%A8%E6%88%B7%E6%89%93%E5%8D%A1%E4%BF%A1%E6%81%AF.md)
- 完成「暂存用户打卡信息」功能开发
- 核心逻辑:[/src/composables/useCheckinDraft.js](file:///Users/huyirui/program/itomix/git/mlaj/src/composables/useCheckinDraft.js)
- 页面集成:[/src/views/checkin/CheckinDetailPage.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/views/checkin/CheckinDetailPage.vue)
- 支持自动保存、过期清理、恢复提示
- 修复打卡详情页 `countValue` 初始化顺序导致的 ReferenceError 报错
- 修复附件上传成功后未保存 URL 导致草稿恢复后无法预览的问题
- 优化文件 URL 获取逻辑:移除硬编码默认域名,优先使用接口返回的 URL 或 src,仅在有域名信息时拼接 URL
## 打卡详情页重构(/checkin/detail)
- 统一了文本、媒体上传和计数打卡的入口
- 实现了基于 composables 的通用提交流程:[/src/composables/useCheckin.js](file:///Users/huyirui/program/itomix/git/mlaj/src/composables/useCheckin.js)
- 页面入口:[/src/views/checkin/CheckinDetailPage.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/views/checkin/CheckinDetailPage.vue)
- 优化了附件预览与编辑回填逻辑(音频/视频/图片预览能力)
## 教师端功能完善(/teacher)
- 新增作业管理页面:/teacher/tasks(列表展示:名称、开始/截止时间)
- 新增作业主页:/teacher/tasks/:id(统计 + 日历视图)
- 新增学员作业记录页:/teacher/student-record(作业帖子 + 点赞/点评)
## 基础体验优化
- 登录逻辑调整:仅在登录页点击微信图标时触发授权(避免路由守卫自动授权导致的循环)
- 关键文件:[/src/router/guards.js](file:///Users/huyirui/program/itomix/git/mlaj/src/router/guards.js)[/src/router/index.js](file:///Users/huyirui/program/itomix/git/mlaj/src/router/index.js)[/src/views/auth/LoginPage.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/views/auth/LoginPage.vue)
- 搜索栏优化:提升 iOS 软键盘“搜索”键触发稳定性
- 课程详情页:增加动态 Open Graph 标签,优化分享体验
## 课程详情页动态 Open Graph 元标签
- 行为:进入课程详情页时,在 head 中插入 og:title / og:description / og:image / og:url;离开页面时移除
- CDN 规则:图片域名为 cdn.ipadbiz.cn 时,追加 ?imageMogr2/thumbnail/200x/strip/quality/70
- 位置:[/src/views/courses/CourseDetailPage.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/views/courses/CourseDetailPage.vue)
## 购买流程环境校验与微信授权探测
- 行为:仅对非免费课程在详情页点击“购买”时进行校验;生产环境必须为微信内置浏览器
- 微信环境内:若未完成微信授权(openid_has=false),会自动发起一次微信授权并中止本次购买,授权后再次点击进入结算
- 位置:[/src/views/courses/CourseDetailPage.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/views/courses/CourseDetailPage.vue)
## 401 拦截策略优化(公开页面不再跳登录)
- 行为:接口返回 code=401 时,仅当当前路由确实需要登录时才重定向登录
- 位置:[/src/utils/axios.js](file:///Users/huyirui/program/itomix/git/mlaj/src/utils/axios.js)
## 搜索栏回车搜索兼容性提升
- 行为:输入框类型改为 search,并可选开启 form submit 机制,同时保留 keyup.enter
- 位置:[/src/components/common/SearchBar.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/components/common/SearchBar.vue)
## 分享海报弹窗(可复用)
- 入口:课程详情页底部操作栏“分享”按钮
- 组件:[/src/components/poster/SharePoster.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/components/poster/SharePoster.vue)
- 能力:弹窗打开时通过 Canvas 合成海报(封面、二维码、文案),生成 dataURL 展示,用户长按保存
## 打卡弹窗与列表组件(可复用)
- 打卡弹窗:[/src/components/checkin/CheckInDialog.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/components/checkin/CheckInDialog.vue)
- 打卡列表:[/src/components/checkin/CheckInList.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/components/checkin/CheckInList.vue)
# /src/components 组件目录索引
## 目录划分
| 目录 | 代表组件 | 说明 |
| --- | --- | --- |
| activity/ | ActivityCard.vue、ActivityApplyHistoryPopup.vue | 活动卡片、报名/历史相关弹窗 |
| calendar/ | CollapsibleCalendar.vue、TaskCalendar.vue | 日历与任务日历组件 |
| checkin/ | CheckInDialog.vue、CheckInList.vue、CheckinCard.vue、UploadVideoPopup.vue | 打卡/作业相关组件(弹窗、列表、卡片、上传) |
| common/ | ConfirmDialog.vue、GradientHeader.vue、SearchBar.vue、UserAgreement.vue | 通用基础组件(确认、头部、搜索、协议) |
| count/ | AddTargetDialog.vue、CheckinTargetList.vue、postCountModel.vue | 计数型打卡相关组件 |
| courses/ | CourseCard.vue、CourseList.vue、LiveStreamCard.vue、ReviewPopup.vue | 课程展示与列表、直播卡片、评价弹窗等 |
| effects/ | FrostedGlass.vue、StarryBackground.vue | 视觉效果组件 |
| homePage/ | FeaturedCoursesSection.vue、LatestActivitiesSection.vue | 首页区块组件(精选/活动/推荐等) |
| infoEntry/ | formPage.vue | 信息录入相关组件 |
| layout/ | AppLayout.vue、BottomNav.vue | 页面布局与底部导航 |
| media/ | AudioPlayer.vue、VideoPlayer.vue、PdfPreview.vue、OfficeViewer.vue | 音视频播放器与文档预览 |
| payment/ | WechatPayment.vue | 微信支付相关组件 |
| poster/ | RecallPoster.vue、SharePoster.vue | 海报生成与分享相关组件 |
| studyDetail/ | StudyCatalogPopup.vue、StudyCommentsSection.vue、StudyMaterialsPopup.vue | 学习详情页的弹窗与评论区 |
| teacher/ | TaskFilter.vue、TaskCascaderFilter.vue | 教师端筛选与任务相关组件 |
## 备注
- 布局目录已归一:统一使用 [/src/components/layout](file:///Users/huyirui/program/itomix/git/mlaj/src/components/layout),已移除 /src/layouts
# 暂存用户打卡信息
## 背景
用户在“提交作业/打卡”页面输入了较长文字并上传了媒体,但在未点击提交时被中断(误触返回、微信进程被系统回收、来电/切后台等),再次进入页面内容丢失,导致体验断裂。
本规划目标是在不改动后端接口的前提下,在前端提供“草稿暂存(文本 + 已上传媒体信息)”能力,支持一周内自动过期清理,并在用户再次进入时提示恢复或删除。
涉及页面与核心逻辑参考:
- 打卡提交页:[CheckinDetailPage.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/views/checkin/CheckinDetailPage.vue)
- 打卡核心逻辑:[useCheckin.js](file:///Users/huyirui/program/itomix/git/mlaj/src/composables/useCheckin.js)
- 环境变量约定:[.env](file:///Users/huyirui/program/itomix/git/mlaj/.env)
## 需求拆解(逐条对齐)
1. 缓存最多保存一周:写入时记录 saved_at,读写时执行过期清理(>7天删除)。
2. 用户提交后清空缓存:提交成功(code===1)后删除对应草稿。
3. 进入页面若存在未完成信息:弹框提示“继续/删除”,继续则回填,删除则清空。
4. 功能开关放到 .env:新增 VITE_CHECKIN_DRAFT_CACHE(0/1),默认建议 1(也可先默认 0,灰度开启)。
## 范围与不做项(第一版)
- 覆盖:文字内容、已上传成功的媒体(含 url/meta_id/file_type/name)。
- 不覆盖:未上传完成的 File/Blob(localStorage 无法可靠持久化;要支持需 IndexedDB 存 Blob,复杂度与风险较高)。
- 编辑模式(route.query.status===edit):第一版建议默认不启用草稿恢复,避免与“编辑回显(来自后端)”冲突;若要覆盖编辑场景,采用独立 key(见“扩展”)。
## 关键设计
### 1) 存储介质
- 使用 localStorage:实现成本低,满足“一周”与“断网/切后台后仍可恢复”。
- 数据量控制:只存“已上传成功”的附件元数据;不存 File 本体。
### 2) 草稿 Key 设计(避免串号)
建议 key 包含用户与作业上下文,确保不同用户/不同作业互不影响:
- 前缀:CHECKIN_DRAFT_V1
- 维度:user_id、task_id、date、task_type、status
示例:
- CHECKIN_DRAFT_V1:{user_id}:{task_id}:{date}:{task_type}:{status}
其中:
- user_id:来自 currentUser(contexts/auth.js 本地持久化)
- task_id/date/task_type/status:来自路由 query(CheckinDetailPage 已使用 route.query.task_id/date/task_type/status)
### 3) 数据结构(建议)
```json
{
"version": 1,
"saved_at": 1730000000000,
"expires_at": 1730000000000,
"context": {
"user_id": "123",
"task_id": "456",
"date": "2026-01-25",
"task_type": "upload",
"status": "create"
},
"payload": {
"message": "...",
"active_type": "image",
"subtask_id": "789",
"file_list": [
{
"meta_id": "xxx",
"url": "https://...",
"name": "a.jpg",
"file_type": "image"
}
],
"count": {
"gratitude_count": 1,
"gratitude_form_list": []
}
}
}
```
说明:
- file_list:仅保存 useCheckin.afterRead 上传成功后写入的字段(item.status===done 且 meta_id 存在)。
- count:来源于 CheckinDetailPage 的 selectedTargets/countValue(第一版可以先不存,或存但不影响非 count 类型)。
### 4) 触发保存的时机(自动暂存)
- 文本变化:watch(message) debounce 500ms 保存。
- 附件变化:watch(fileList) 深度监听 debounce 500ms 保存(仅保存 done 项)。
- 作业选择变化:watch(selectedTaskValue) debounce 200ms 保存。
- 页面离开兜底:beforeRouteLeave 或 window.pagehide/visibilitychange 时强制保存一次(避免最后一次变更没落盘)。
落盘时机要遵循开关:VITE_CHECKIN_DRAFT_CACHE === '1' 才启用。
### 5) 弹框提示与回填流程
进入 [CheckinDetailPage.vue](file:///Users/huyirui/program/itomix/git/mlaj/src/views/checkin/CheckinDetailPage.vue)(且非 edit 模式)时:
1. 读取 key 对应草稿;若不存在或已过期,直接进入正常流程。
2. 若存在草稿且 payload 有实际内容(message 有非空或 file_list 非空):弹框提示。
3. 用户选择:
- 继续:将草稿回填到 message / activeType / fileList / selectedTaskValue(以及 count 数据如启用),并立刻再保存一次(避免回填后又丢)。
- 删除:删除草稿并保持空表单。
弹框建议用 showConfirmDialog(Vant 4),取消分支需要 catch,避免控制台出现 Uncaught (in promise) cancel(Vant 文档:showConfirmDialog.then/catch)[3](https://develop365.gitlab.io/vant/zh-CN/dialog/)
### 6) 清理策略(“定期清除一周前”)
采用“惰性清理 + 低频全量清理”组合:
- 惰性清理:每次读/写草稿时,如果 expires_at < now 则删除。
- 低频全量:进入打卡页时,扫描 localStorage 中以 CHECKIN_DRAFT_V1: 开头的 key,删除所有过期项。
说明:localStorage 没有内建 TTL,必须业务侧维护 expires_at。
### 7) 提交成功后清空
清空动作必须绑定到“真正提交成功”之后:
- 建议在 useCheckin.onSubmit 中,当 add/edit API 返回 code===1 且后续逻辑准备 router.back 前,删除对应 key。
这样可覆盖“不同入口页复用 onSubmit”以及“提交后立即返回上一页”的场景。
## 开发步骤(可落地的实现顺序)
### 第 0 步:验证手段先行(TDD)
新增 Vitest 用例,先定义以下可验证点:
- 写入后能读取同一 key 的草稿;过期后读取返回空且自动删除。
- 仅保存 status===done 且含 meta_id 的附件。
- 清理函数能删除所有过期 key,不误删其他业务 localStorage。
- 提交成功时会调用清理(可通过 mock API 返回 code===1 验证)。
### 第 1 步:抽离草稿存储模块
位置建议:src/utils/checkinDraftCache.js(纯函数、无 UI 依赖)。
对外 API(示例):
- is_enabled(): boolean(读取 env + 可选 query override)
- build_key(context): string
- save_draft(key, draft)
- read_draft(key): draft|null(含 TTL 处理)
- clear_draft(key)
- cleanup_expired(prefix)
### 第 2 步:在 CheckinDetailPage 接入“检测 + 弹框 + 回填”
- onMounted:初始化后读取草稿并弹框。
- 回填时机:建议在任务详情/子任务列表加载完成后再回填 selectedTaskValue,避免 option 未加载导致显示异常。
### 第 3 步:在 CheckinDetailPage 接入“自动保存”
- 对 message/fileList/selectedTaskValue/countValue/selectedTargets 建立 watch + debounce。
- 页面离开事件兜底(pagehide/visibilitychange)。
### 第 4 步:在 useCheckin.onSubmit 接入“成功清理”
- onSubmit 成功分支清除草稿。
- 失败分支不清除,保留草稿以便重试。
## 边界条件与遗漏点梳理(建议补齐)
1. 多用户切换:key 必须含 user_id,否则会串草稿。
2. 多任务并存:key 必须含 task_id/date/task_type,否则会在不同作业之间误恢复。
3. 附件未上传完成:
- 仅保存已上传成功的项;如果用户退出时仍有 uploading 项,恢复后无法找回该 File。
- 可在保存时统计未保存数量,并在恢复弹框里追加提示“有 X 个附件上传未完成未被暂存”。
4. 关闭开关后的行为:
- 关闭后不再读/写;建议仍执行一次 cleanup_expired,避免历史堆积。
5. 版本升级/数据结构变更:draft.version 不匹配时丢弃并清除,避免解析异常。
6. localStorage 配额:图片多但只存 url/meta_id 一般不会超;仍需 try/catch JSON 与 setItem 异常。
7. 编辑模式:
- 要支持“编辑中断恢复”,建议 key 加 post_id 维度,并在 initEditData 回显后再弹框询问是否覆盖当前表单。
## 环境变量(规划)
[.env](file:///Users/huyirui/program/itomix/git/mlaj/.env) 增加:
- VITE_CHECKIN_DRAFT_CACHE = 1
约定:
- '1' 开启,'0' 关闭
- 可选增加 URL 覆盖用于灰度测试:?enable_draft=1 / ?enable_draft=0(模式同 VITE_CHECKIN_MULTI_ATTACHMENT)