commit 26975e5c3a07e8c2ae348826bbce6ae7db601592 Author: ning-inspire Date: Tue Nov 17 09:57:41 2026 +0800 Initial commit: ai4se-harness-suite Import harness suite (skills, installers, overnight-runner, docs) as a fresh history for InspireChina. Co-authored-by: Cursor diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ac77af5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# OS +.DS_Store +Thumbs.db + +# Editors +.idea/ +*.iml +.vscode/ +.settings/ + +# Node +node_modules/ +*.tsbuildinfo + +# Java / Maven +target/ +*.class +*.jar + +# Build output +frontend/dist/ + +# E2E artifacts +e2e/playwright-report/ +e2e/test-results/ +e2e/screenshots/ + +# Runtime state(只排除运行时产物,project.yaml / queue.yaml / decisions.jsonl 要进版本库) +**/.overnight-runner/state.json +**/.overnight-runner/state.json.bak +**/.overnight-runner/logs/ +**/.overnight-runner/queue/*/state.json +**/.overnight-runner/queue/*/state.json.bak +**/.overnight-runner/queue/*/logs/ +**/.overnight-runner/queue/*/.lock +*.log + +# Python +__pycache__/ +*.pyc +.venv/ +venv/ + +# Secrets +.env +.env.local +**/src/main/resources/application.yml diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6def049 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,478 @@ +# 架构与工程规范(team-harness-suite) + +本文件定义本仓库的架构边界、模块职责与工程规范。目标是让新成员与自动化工具在不了解上下文的情况下, +也能按一致方式新增模块、扩展能力并避免破坏依赖关系。 + +> 这是一个 **harness 仓库**,不是业务应用。仓库里没有运行时服务, +> 交付物是 **skill、安装脚本、模板、文档** —— 它们被安装到别人的项目里去干活。 +> +> 参考实现在 [`example-project/`](example-project/):一份填满规范的全栈项目, +> 用来说明"被这套 harness 管理之后,项目应该长什么样"。 + +## 1. 仓库拓扑 + +技术栈: + +| 类型 | 技术 | 用在哪 | +|---|---|---| +| 文档 | Markdown | skill、指南、规范、模板 | +| 脚本 | Bash 3.2+ | 安装脚本(安装器型 skill) | +| 脚本 | Python 3.9+(**零第三方依赖**) | `overnight-runner` 的运行器 | +| 脚本 | Node.js 18+ | `tool-chain-installer` 的安装器 | +| 配置 | YAML | 队列配置、项目配置、skill 清单 | +| 配置 | JSON / JSONC | MCP 工具清单、opencode 配置 | + +主要模块: + +``` +team-harness-suite/ +├── agile-team-sdd/ # SDD 技能套件(16 个 skill 模板 + 安装器) +├── harness-installer/ # 初始化目标项目的 AGENTS.md + docs/ 骨架 +├── tool-chain-installer/ # 安装 MCP 工具链到项目配置 +├── overnight-runner/ # 无人值守跑 plan 的分屏面板 + 看门狗 +├── team-workflow-guide/ # 团队流程与角色手册(纯文档) +├── example-project/ # 全栈参考实现(被这套 harness 管理的样子) +└── opencode.jsonc # 注册本仓库的 skills 路径 +``` + +运行时形态: + +``` +使用者 ──安装──▶ 目标项目 ──▶ opencode 加载 skill + │ + ├─ agile-team-sdd → 目标项目/.agent/skills/ + ├─ harness-installer → 目标项目/AGENTS.md + docs/ + ├─ tool-chain-installer→ 目标项目/.mcp.json + opencode.jsonc + └─ overnight-runner → 目标项目/tools/overnight-runner/ +``` + +## 2. 横切关注点:skill 机制与占位符 + +本仓库的 **核心机制** 是 skill。所有模板型交付物都遵守同一套约定。 + +### skill 的四种形态 + +| 形态 | 目录 | 干什么 | +|---|---|---| +| **安装器型** | `harness-installer/`、`tool-chain-installer/` | 一个 skill,作用是把东西装进目标项目 | +| **套件型** | `agile-team-sdd/` | 一个 skill(安装器)+ N 个 skill 模板,一次装一批 | +| **运行时型** | `overnight-runner/` | 一个 skill,作用是 **启动** 一个长跑工具 | +| **文档型** | `team-workflow-guide/` | 不是 skill,是人读的指南 | + +### SKILL.md 格式(强制) + +```markdown +--- +name: <与所在目录同名,小写连字符,≤64 字符> +description: <一句话说明"做什么"+"什么时候用",第三人称,前置触发关键词> +--- + +<正文:什么时候用 / 怎么做 / 硬性约束 / 反模式 / 自检清单> +``` + +- `name` **必须** 与目录名一致 —— opencode 靠它索引 +- `description` 是 **唯一** 的触发依据,写得含糊 skill 就等于不存在 +- 正文里的路径 **不能** 写死成某个项目的绝对路径 + +### 占位符(强制) + +模板里的项目专属路径一律写成 `{{PLACEHOLDER}}`,由安装脚本渲染: + +``` +{{PROJECT_ROOT}} {{FEATURES_DIR}} {{DESIGNS_DIR}} {{AGENTS_FILE}} ... +``` + +约束: + +- 占位符字典写在 `agile-team-sdd/placeholders.md`,**新增必须同步登记** +- 未登记的占位符会在安装时报警(`install.sh` 的残留检查) +- 渲染后的路径默认是绝对路径(`PATH_MODE=absolute`); + 会随仓库分发的项目用 `PATH_MODE=relative` +- 占位符 **不替换** 与项目无关的内容(Markdown 代码块、语言标注、PlantUML 的 `{字段}`) + +### 模板 skill 的命名 + +模板目录带 `-template` 后缀,安装时去掉: + +``` +agile-team-sdd/skills/dev-plan-template/SKILL.md (frontmatter: name: dev-plan-template) + ↓ install.sh +<目标项目>/.agent/skills/dev-plan/SKILL.md (frontmatter: name: dev-plan) +``` + +**原因**:模板本身也要能被 opencode 扫描到,但不能和已安装的同名 skill 冲突。 + +### 模板标记块 + +每份模板 `SKILL.md` 顶部带: + +```markdown + +> **这是模板文件。** 路径由 `{{PLACEHOLDER}}` 占位符标记…… + +``` + +安装时整块删除。**新增模板必须带这个块**,否则安装后会出现"这是模板"的提示。 + +## 3. 模块边界 + +``` + ┌─────────────────┐ + │ team-workflow- │ 流程与角色约定(人读) + │ guide/ │ + └────────┬────────┘ + │ 指导 + ┌─────────────┼─────────────┐ + │ │ │ +┌──▼──────────┐ ┌▼───────────┐ ┌▼──────────────────┐ +│harness- │ │agile-team- │ │tool-chain- │ +│installer/ │ │sdd/ │ │installer/ │ +│AGENTS.md │ │16 个 skill │ │MCP 工具链 │ +│docs/ 骨架 │ │模板 + 安装器│ │ │ +└─────────────┘ └┬───────────┘ └──────────────────┘ + │ 装进 + ┌────────▼─────────┐ + │ example-project/ │ 参考实现 + └──────────────────┘ + + ┌──────────────────┐ + │ overnight-runner/│ 运行时型:启动长跑工具 + └──────────────────┘ +``` + +硬约束: + +- **四个安装器/套件型模块之间不互相 import**。它们通过 **文件系统与 YAML 清单** 通信。 + 唯一允许的跨模块引用是 **文档里的路径**。 +- `example-project/` 是 **被管理的对象**,不是本仓库的实现的一部分。 + 它的代码不参与本仓库的验证脚本(除了 skill 一致性检查)。 +- `team-workflow-guide/` 是 **纯文档**,不包含可执行代码。 + +## 4. 清单是唯一事实源 + +每个可扩展的集合都有 **一份清单**,其它地方不许硬编码: + +| 集合 | 清单文件 | 谁读它 | +|---|---|---| +| SDD skill 套件 | `agile-team-sdd/catalog.json` | `install.sh`(分组过滤)、`SKILL.md`(文档) | +| MCP 工具 | `tool-chain-installer/catalog/mcp-catalog.json` | `install-tools.mjs` | + +`catalog.json` 的每一项至少包含: + +```json +{ + "name": "dev-plan", + "description": "在实现前写技术方案(Plan),等待人工确认", + "when": "新功能、重构或任何非简单变更,动手写代码之前", + "produces": ["docs/plans/YYYYMMDD-{slug}.md"], + "dependsOn": [] +} +``` + +**新增 skill 的完整流程**:建 `skills/-template/SKILL.md` → 在 `catalog.json` 登记 → +跑 `install.sh --list` 验证 → 补 `agile-team-sdd/SKILL.md` 与 `README.md` 的表格。 + +## 5. 文件与目录约定 + +### 脚本 + +| 位置 | 用途 | 入口约定 | +|---|---|---| +| `<模块>/scripts/install.sh` | 安装到目标项目 | `./install.sh <目标目录> [--dry-run] [--force]` | +| `<模块>/scripts/*.mjs` | Node 安装器 | `node + + diff --git a/example-project/docs/features/iteration1/prototypes/package-lock.json b/example-project/docs/features/iteration1/prototypes/package-lock.json new file mode 100644 index 0000000..fb309e6 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/package-lock.json @@ -0,0 +1,1539 @@ +{ + "name": "iteration1-prototypes", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "iteration1-prototypes", + "version": "0.1.0", + "dependencies": { + "element-plus": "^2.9.0", + "vue": "^3.5.13", + "vue-router": "^4.5.0" + }, + "devDependencies": { + "@types/node": "^22.10.0", + "@vitejs/plugin-vue": "^5.2.1", + "typescript": "~5.5.0", + "vite": "^5.4.0", + "vue-tsc": "^2.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@ctrl/tinycolor": { + "version": "4.3.1", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@element-plus/icons-vue": { + "version": "2.3.2", + "license": "MIT", + "peerDependencies": { + "vue": "^3.2.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "license": "MIT" + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "license": "MIT" + }, + "node_modules/@popperjs/core": { + "name": "@sxzz/popperjs-es", + "version": "2.11.8", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.3.tgz", + "integrity": "sha512-mqfypgH/liYjaSCoPI4erckUcROgZtmFUUmyOJ05oyayi/tVqOEYAzWP7ufqCoCT3xB31Fw4XIVO/jX42hYvKA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.3.tgz", + "integrity": "sha512-5tY+GC/1gpt79cKS2DQzu6iD824j6BmI4q5Zb6qftZ4kWqIQmvR3DD4eJ2Gclu6/nVMYDk2IVpqxypWOiAuWJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.3.tgz", + "integrity": "sha512-nDBcQ/o3PMmGxmAzGBJFn+n1rb83Va9WSdFIq1AHmlEF3tuibVsyJ3kG5x13r7VIy6WI8SvzCdHVNSlSDIdj8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.3", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.3.tgz", + "integrity": "sha512-xo5xeo/AjEB/ArzQjGn0JRDZuybZicQ5O3VPfko6ocH1li/qNrN4p5+R/WgjavzRz6UwAOaqsau7VvRQA6i6AA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.3.tgz", + "integrity": "sha512-zdckkcxHDEEKyDbC1t21DeaaiKGymxbkBU9c3zyfaaz+8N96ItJw4nmzHhZF+Mukgt906fnf2tsc90pVyStuHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.3.tgz", + "integrity": "sha512-9oXqI7g/ycEz7TyicdGBC4sL6PfWMXAx8u15f/nd7lYkCLJd8U8VdBfbpc4SSnRBU/e7aPALve3mhzasGDeCYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.3.tgz", + "integrity": "sha512-hbgT4NlaOELE3D5UUzSqF+OFgwz4Scvo2SQD9nZJUFjdIsg9Kg3FabQauUxkHKY9N5yjNXfXRRmiKNN4JpLmFA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.3.tgz", + "integrity": "sha512-yECcXZ/Bl+JVRhLFgld42rYrXgPdE0LtySGAmmmH6OtkaJM17A4cWG/eCzDymMVb52/jZjW0R54YrTHj4xXlSA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.3.tgz", + "integrity": "sha512-q4Q4/B7wyqM+TFqY5tJYQlaz5+ksGopcRmMeMdu4q6eaPK7N1PymTjIaH5LL32mMJBqIzpRof7BhlYLim5JgNQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.3.tgz", + "integrity": "sha512-Ich3TGl/7GqhQ6G6jVPzgGQGJjd3E5hECxSVanPYchy6Vwcq+WI8wG/gmEMilHNy+ZYCR6U8EN50EejG3TaIgw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.3.tgz", + "integrity": "sha512-URBmOhwv4Y0Hi5Hhxc3cmqZLtQlx55DOs5PUhhITDC3zu0qwAfhcNAFAIwAhOUdA6NFVEck07CNZX6cBEs1vTg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.3.tgz", + "integrity": "sha512-PTdJXuZplRyaE3ECArlbZubI2LlUHWm0oCipCexnE/8LM+L7qIqUiNbU0piBxt46EB5zxXX+cpmDvHX4Z3WwcQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.3.tgz", + "integrity": "sha512-IlSQPDExSm9YdtrWeZIHj87GPXI9lYygRvHVwQ1o9t91JHIiB2CihrvNIASpc/zI28atqm04jS3proaQuaJMww==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.3.tgz", + "integrity": "sha512-O2ssyDcBTZkH5v2P/9ZaXJreL0hCKvUA5UwuHn0jCKeMLKi4GhspZJ1I5FT5QsHtJ/dPx4pup7pg/Lw0emeY0Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.3.tgz", + "integrity": "sha512-fesqagxcnc87lH2+aBWne/tFCmQVIGH+YezjY1wQwbUODuTBBlhHoyxju6umwn8LnjHVanjpoeaQdLsXP8JQSQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.3.tgz", + "integrity": "sha512-WAjFDtLW3HjJ2RAytKoWdFwlK/hW8rJHrjhRZFw14nR+c9JN//WIlSBkyXUjEYCNOFs2sGLNutOEPQG4iVYHgA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.3.tgz", + "integrity": "sha512-+fZiTeHV/1fy/14dRqE4thjYwUOABL6qQjxElOEQg2oHLkCamO8dxhHphVgD4+pFxtVEUIWxsGVduPtwnAlvbg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.3.tgz", + "integrity": "sha512-pfn4Zd9Ic3lEaSwW3GsQhTIDd7929C+eiEkOutsSCT2IHD6rDLblwmMQkgeGOso0oDo9Jk/ERtFdtFr9ElLs+g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.3.tgz", + "integrity": "sha512-eUXzaeNQbKXKNqseL3g/usUqOPmRu+DbQsvwr9MXMdV+VQFUNb9bcWSNAAs/TRV95PCbFK46kLzHEOhFSzujsg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.3.tgz", + "integrity": "sha512-OiUclE7QDU4H/hr3ACRHhVGKWl+gNx+6Emignfq0hmNmzzTkZnT79wzB9NXKd0QH16S4t/wVqlAFBfC17nkZ5A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.3.tgz", + "integrity": "sha512-s6EclDWmk6zvIfk1yixgYthk7xHNx0xu5cEF5RDpS4IHNTpfswRX6xOXVG5cHF5xWn0B6EpDGARhPQ520KTlsA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.3.tgz", + "integrity": "sha512-G2xnmxGnU8XHLwtjnnXNRcLrub+Af3nm9VQ1QzL2aEiAL7woBdRgTCZBslJl8umA+YMqdEFpUh9kJB/Vyzk2wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.3.tgz", + "integrity": "sha512-Y/4tApNVrMUYWbAHsyRWJgwuuJOfhTNhA2B04Xpa6+G9btkPZ9kU3XagUKzPTwF3hg36NpQk748JsnoTVho67Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.3.tgz", + "integrity": "sha512-i2vH/OA5BcW+TdNg12ZTRC4rn+vILaPMP9CvHqnv+QEpMjBHGGNLo4k4EnEqzjYvTD6x1Xark9WhsQbH4bTzUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.3.tgz", + "integrity": "sha512-ADb1Uz2MNM0sxVpAlMNdQG16Hw4sgW1aqVL7NeqBMpcZeiHb192d7W6shZdMQs33D+w9ihDYBBPsYqqc4MlD8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.27", + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.21", + "license": "MIT" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "5.2.4", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.15" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.15", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.15", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.15", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.12", + "@vue/shared": "3.5.45", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.12", + "@vue/compiler-core": "3.5.45", + "@vue/compiler-dom": "3.5.45", + "@vue/compiler-ssr": "3.5.45", + "@vue/shared": "3.5.45", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.32", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/compiler-vue2": { + "version": "2.7.16", + "dev": true, + "license": "MIT", + "dependencies": { + "de-indent": "^1.0.2", + "he": "^1.2.0" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.4", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "2.2.12", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.15", + "@vue/compiler-dom": "^3.5.0", + "@vue/compiler-vue2": "^2.7.16", + "@vue/shared": "^3.5.0", + "alien-signals": "^1.0.3", + "minimatch": "^9.0.3", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.45", + "@vue/runtime-core": "3.5.45", + "@vue/shared": "3.5.45", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.45", + "@vue/runtime-dom": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.45", + "license": "MIT" + }, + "node_modules/@vueuse/core": { + "version": "15.0.0", + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.21", + "@vueuse/metadata": "15.0.0", + "@vueuse/shared": "15.0.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/@vueuse/metadata": { + "version": "15.0.0", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared": { + "version": "15.0.0", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/alien-signals": { + "version": "1.0.13", + "dev": true, + "license": "MIT" + }, + "node_modules/async-validator": { + "version": "4.2.5", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.1.8", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "license": "MIT" + }, + "node_modules/dayjs": { + "version": "1.11.23", + "license": "MIT" + }, + "node_modules/de-indent": { + "version": "1.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/element-plus": { + "version": "2.14.8", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^4.2.2", + "@element-plus/icons-vue": "^2.3.2", + "@floating-ui/dom": "^1.8.0", + "@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.8", + "@types/lodash": "^4.17.24", + "@types/lodash-es": "^4.17.12", + "@vueuse/core": "15.0.0", + "async-validator": "^4.2.5", + "dayjs": "^1.11.20", + "lodash": "^4.18.1", + "lodash-es": "^4.18.1", + "lodash-unified": "^1.0.3", + "memoize-one": "^6.0.0", + "normalize-wheel-es": "^1.2.0", + "vue-component-type-helpers": "^3.3.11" + }, + "peerDependencies": { + "vue": "^3.3.7" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/he": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "license": "MIT" + }, + "node_modules/lodash-unified": { + "version": "1.0.3", + "license": "MIT", + "peerDependencies": { + "@types/lodash-es": "*", + "lodash": "*", + "lodash-es": "*" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/memoize-one": { + "version": "6.0.0", + "license": "MIT" + }, + "node_modules/minimatch": { + "version": "9.0.9", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-wheel-es": { + "version": "1.2.0", + "license": "BSD-3-Clause" + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.33", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.68.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.3", + "@rollup/rollup-android-arm64": "4.68.3", + "@rollup/rollup-android-x64": "4.68.3", + "@rollup/rollup-darwin-arm64": "4.68.3", + "@rollup/rollup-darwin-x64": "4.68.3", + "@rollup/rollup-freebsd-arm64": "4.68.3", + "@rollup/rollup-freebsd-x64": "4.68.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.3", + "@rollup/rollup-linux-arm-musleabihf": "4.68.3", + "@rollup/rollup-linux-arm64-gnu": "4.68.3", + "@rollup/rollup-linux-arm64-musl": "4.68.3", + "@rollup/rollup-linux-loong64-gnu": "4.68.3", + "@rollup/rollup-linux-loong64-musl": "4.68.3", + "@rollup/rollup-linux-ppc64-gnu": "4.68.3", + "@rollup/rollup-linux-ppc64-musl": "4.68.3", + "@rollup/rollup-linux-riscv64-gnu": "4.68.3", + "@rollup/rollup-linux-riscv64-musl": "4.68.3", + "@rollup/rollup-linux-s390x-gnu": "4.68.3", + "@rollup/rollup-linux-x64-gnu": "4.68.3", + "@rollup/rollup-linux-x64-musl": "4.68.3", + "@rollup/rollup-openbsd-x64": "4.68.3", + "@rollup/rollup-openharmony-arm64": "4.68.3", + "@rollup/rollup-win32-arm64-msvc": "4.68.3", + "@rollup/rollup-win32-ia32-msvc": "4.68.3", + "@rollup/rollup-win32-x64-gnu": "4.68.3", + "@rollup/rollup-win32-x64-msvc": "4.68.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/typescript": { + "version": "5.5.4", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "5.4.21", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vscode-uri": { + "version": "3.2.0", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.45", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.45", + "@vue/compiler-sfc": "3.5.45", + "@vue/runtime-dom": "3.5.45", + "@vue/server-renderer": "3.5.45", + "@vue/shared": "3.5.45" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-component-type-helpers": { + "version": "3.3.14", + "license": "MIT" + }, + "node_modules/vue-router": { + "version": "4.6.5", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.4" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/vue-tsc": { + "version": "2.2.12", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.15", + "@vue/language-core": "2.2.12" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + } + } +} diff --git a/example-project/docs/features/iteration1/prototypes/package.json b/example-project/docs/features/iteration1/prototypes/package.json new file mode 100644 index 0000000..ddedabf --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/package.json @@ -0,0 +1,23 @@ +{ + "name": "iteration1-prototypes", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc -b && vite build", + "preview": "vite preview" + }, + "dependencies": { + "element-plus": "^2.9.0", + "vue": "^3.5.13", + "vue-router": "^4.5.0" + }, + "devDependencies": { + "@types/node": "^22.10.0", + "@vitejs/plugin-vue": "^5.2.1", + "typescript": "~5.5.0", + "vite": "^5.4.0", + "vue-tsc": "^2.0.0" + } +} diff --git a/example-project/docs/features/iteration1/prototypes/src/App.vue b/example-project/docs/features/iteration1/prototypes/src/App.vue new file mode 100644 index 0000000..98240ae --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/App.vue @@ -0,0 +1,3 @@ + diff --git a/example-project/docs/features/iteration1/prototypes/src/layouts/SideLayout.vue b/example-project/docs/features/iteration1/prototypes/src/layouts/SideLayout.vue new file mode 100644 index 0000000..41640b6 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/layouts/SideLayout.vue @@ -0,0 +1,43 @@ + + + diff --git a/example-project/docs/features/iteration1/prototypes/src/layouts/UserLayout.vue b/example-project/docs/features/iteration1/prototypes/src/layouts/UserLayout.vue new file mode 100644 index 0000000..419f336 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/layouts/UserLayout.vue @@ -0,0 +1,44 @@ + + + diff --git a/example-project/docs/features/iteration1/prototypes/src/main.ts b/example-project/docs/features/iteration1/prototypes/src/main.ts new file mode 100644 index 0000000..59d4917 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/main.ts @@ -0,0 +1,8 @@ +import { createApp } from 'vue' +import ElementPlus from 'element-plus' +import 'element-plus/dist/index.css' +import App from './App.vue' +import router from './router' +import './styles/app.css' + +createApp(App).use(router).use(ElementPlus).mount('#app') diff --git a/example-project/docs/features/iteration1/prototypes/src/nav.ts b/example-project/docs/features/iteration1/prototypes/src/nav.ts new file mode 100644 index 0000000..9260a3b --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/nav.ts @@ -0,0 +1,17 @@ +export const consultantNav = [ + { path: '/consultant', label: '工作台' }, + { path: '/consultant/application', label: '入驻申请' }, + { path: '/consultant/profile', label: '档案维护' }, + { path: '/consultant/schedule', label: '档期管理' }, + { path: '/consultant/orders', label: '预约管理' }, + { path: '/consultant/settlements', label: '收入结算' }, +] as const + +export const adminNav = [ + { path: '/admin', label: '运营看板' }, + { path: '/admin/applications', label: '入驻审核' }, + { path: '/admin/categories', label: '分类与标签' }, + { path: '/admin/users', label: '用户管理' }, + { path: '/admin/orders', label: '订单监控' }, + { path: '/admin/reports', label: '举报处理' }, +] as const diff --git a/example-project/docs/features/iteration1/prototypes/src/router/index.ts b/example-project/docs/features/iteration1/prototypes/src/router/index.ts new file mode 100644 index 0000000..d3b564b --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/router/index.ts @@ -0,0 +1,70 @@ +import { createRouter, createWebHistory } from 'vue-router' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/', name: 'home', component: () => import('@/views/Home.vue') }, + { path: '/user', name: 'user-home', component: () => import('@/views/user/Home.vue') }, + { path: '/user/login', name: 'user-login', component: () => import('@/views/user/Login.vue') }, + { path: '/user/search', name: 'user-search', component: () => import('@/views/user/Search.vue') }, + { + path: '/user/consultant-detail', + name: 'user-consultant-detail', + component: () => import('@/views/user/ConsultantDetail.vue'), + }, + { path: '/user/booking', name: 'user-booking', component: () => import('@/views/user/Booking.vue') }, + { path: '/user/my-orders', name: 'user-my-orders', component: () => import('@/views/user/MyOrders.vue') }, + { + path: '/user/order-detail', + name: 'user-order-detail', + component: () => import('@/views/user/OrderDetail.vue'), + }, + { path: '/user/profile', name: 'user-profile', component: () => import('@/views/user/Profile.vue') }, + { + path: '/consultant', + name: 'consultant-home', + component: () => import('@/views/consultant/Dashboard.vue'), + }, + { + path: '/consultant/application', + name: 'consultant-application', + component: () => import('@/views/consultant/Application.vue'), + }, + { + path: '/consultant/profile', + name: 'consultant-profile', + component: () => import('@/views/consultant/Profile.vue'), + }, + { + path: '/consultant/schedule', + name: 'consultant-schedule', + component: () => import('@/views/consultant/Schedule.vue'), + }, + { + path: '/consultant/orders', + name: 'consultant-orders', + component: () => import('@/views/consultant/Orders.vue'), + }, + { + path: '/consultant/settlements', + name: 'consultant-settlements', + component: () => import('@/views/consultant/Settlements.vue'), + }, + { path: '/admin', name: 'admin-home', component: () => import('@/views/admin/Dashboard.vue') }, + { + path: '/admin/applications', + name: 'admin-applications', + component: () => import('@/views/admin/Applications.vue'), + }, + { + path: '/admin/categories', + name: 'admin-categories', + component: () => import('@/views/admin/Categories.vue'), + }, + { path: '/admin/users', name: 'admin-users', component: () => import('@/views/admin/Users.vue') }, + { path: '/admin/orders', name: 'admin-orders', component: () => import('@/views/admin/Orders.vue') }, + { path: '/admin/reports', name: 'admin-reports', component: () => import('@/views/admin/Reports.vue') }, + ], +}) + +export default router diff --git a/example-project/docs/features/iteration1/prototypes/src/styles/app.css b/example-project/docs/features/iteration1/prototypes/src/styles/app.css new file mode 100644 index 0000000..bdccadb --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/styles/app.css @@ -0,0 +1,126 @@ +:root { + --proto-bg: #f5f7fa; + --proto-side: #001529; +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + min-height: 100%; + background: var(--proto-bg); + font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif; +} + +#app { + min-height: 100vh; +} + +.proto-topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 0 24px; + height: 56px; + background: #fff; + border-bottom: 1px solid var(--el-border-color-light, #ebeef5); +} + +.proto-brand { + font-weight: 700; + color: #409eff; + white-space: nowrap; + cursor: pointer; +} + +.proto-layout { + display: flex; + min-height: 100vh; +} + +.proto-aside { + width: 220px; + background: var(--proto-side); + color: #fff; + padding: 16px 0; + flex-shrink: 0; +} + +.proto-aside h2 { + margin: 0 16px 16px; + font-size: 15px; + font-weight: 600; +} + +.proto-aside .muted { + margin: 16px; + font-size: 12px; + opacity: 0.65; +} + +.proto-main { + flex: 1; + padding: 20px 24px 40px; + min-width: 0; +} + +.proto-page-title { + margin: 0 0 4px; + font-size: 20px; + font-weight: 600; +} + +.proto-page-desc { + margin: 0 0 16px; + color: #909399; + font-size: 13px; +} + +.proto-card-gap { + margin-bottom: 16px; +} + +.proto-metrics { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + gap: 12px; + margin-bottom: 16px; +} + +.proto-metric { + background: #fff; + border-radius: 8px; + padding: 14px 16px; + border: 1px solid var(--el-border-color-lighter, #ebeef5); +} + +.proto-metric .value { + font-size: 22px; + font-weight: 700; + line-height: 1.2; +} + +.proto-metric .label { + margin-top: 4px; + color: #909399; + font-size: 12px; +} + +.proto-section-title { + margin: 20px 0 12px; + font-size: 16px; + font-weight: 600; +} + +a.proto-link { + color: #409eff; + text-decoration: none; +} + +a.proto-link:hover { + text-decoration: underline; +} diff --git a/example-project/docs/features/iteration1/prototypes/src/views/Home.vue b/example-project/docs/features/iteration1/prototypes/src/views/Home.vue new file mode 100644 index 0000000..26d79dc --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/Home.vue @@ -0,0 +1,62 @@ + + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/admin/Applications.vue b/example-project/docs/features/iteration1/prototypes/src/views/admin/Applications.vue new file mode 100644 index 0000000..1563456 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/admin/Applications.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/admin/Categories.vue b/example-project/docs/features/iteration1/prototypes/src/views/admin/Categories.vue new file mode 100644 index 0000000..f66d9e9 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/admin/Categories.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/admin/Dashboard.vue b/example-project/docs/features/iteration1/prototypes/src/views/admin/Dashboard.vue new file mode 100644 index 0000000..c7a1d2f --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/admin/Dashboard.vue @@ -0,0 +1,10 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/admin/Orders.vue b/example-project/docs/features/iteration1/prototypes/src/views/admin/Orders.vue new file mode 100644 index 0000000..37836bf --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/admin/Orders.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/admin/Reports.vue b/example-project/docs/features/iteration1/prototypes/src/views/admin/Reports.vue new file mode 100644 index 0000000..ba7fb44 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/admin/Reports.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/admin/Users.vue b/example-project/docs/features/iteration1/prototypes/src/views/admin/Users.vue new file mode 100644 index 0000000..72fb7f4 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/admin/Users.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/consultant/Application.vue b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Application.vue new file mode 100644 index 0000000..5e44c99 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Application.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/consultant/Dashboard.vue b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Dashboard.vue new file mode 100644 index 0000000..0c87cd5 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Dashboard.vue @@ -0,0 +1,11 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/consultant/Orders.vue b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Orders.vue new file mode 100644 index 0000000..b05e3ca --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Orders.vue @@ -0,0 +1,8 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/consultant/Profile.vue b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Profile.vue new file mode 100644 index 0000000..ceb578e --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Profile.vue @@ -0,0 +1,9 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/consultant/Schedule.vue b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Schedule.vue new file mode 100644 index 0000000..3af9074 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Schedule.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/consultant/Settlements.vue b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Settlements.vue new file mode 100644 index 0000000..8e4f410 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/consultant/Settlements.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/Booking.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/Booking.vue new file mode 100644 index 0000000..b45d9db --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/Booking.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/ConsultantDetail.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/ConsultantDetail.vue new file mode 100644 index 0000000..1ac8212 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/ConsultantDetail.vue @@ -0,0 +1,8 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/Home.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/Home.vue new file mode 100644 index 0000000..cec66c9 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/Home.vue @@ -0,0 +1,17 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/Login.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/Login.vue new file mode 100644 index 0000000..9e496d8 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/Login.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/MyOrders.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/MyOrders.vue new file mode 100644 index 0000000..88cd0d3 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/MyOrders.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/OrderDetail.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/OrderDetail.vue new file mode 100644 index 0000000..4d3d832 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/OrderDetail.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/Profile.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/Profile.vue new file mode 100644 index 0000000..6c86b60 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/Profile.vue @@ -0,0 +1,7 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/views/user/Search.vue b/example-project/docs/features/iteration1/prototypes/src/views/user/Search.vue new file mode 100644 index 0000000..afe0509 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/views/user/Search.vue @@ -0,0 +1,10 @@ + + diff --git a/example-project/docs/features/iteration1/prototypes/src/vite-env.d.ts b/example-project/docs/features/iteration1/prototypes/src/vite-env.d.ts new file mode 100644 index 0000000..65c7311 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/src/vite-env.d.ts @@ -0,0 +1,7 @@ +/// + +declare module '*.vue' { + import type { DefineComponent } from 'vue' + const component: DefineComponent + export default component +} diff --git a/example-project/docs/features/iteration1/prototypes/tsconfig.app.json b/example-project/docs/features/iteration1/prototypes/tsconfig.app.json new file mode 100644 index 0000000..195c1a3 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/tsconfig.app.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "preserve", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "paths": { + "@/*": ["./src/*"] + }, + "baseUrl": "." + }, + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] +} diff --git a/example-project/docs/features/iteration1/prototypes/tsconfig.json b/example-project/docs/features/iteration1/prototypes/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/example-project/docs/features/iteration1/prototypes/tsconfig.node.json b/example-project/docs/features/iteration1/prototypes/tsconfig.node.json new file mode 100644 index 0000000..8e5b203 --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/tsconfig.node.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["vite.config.ts"] +} diff --git a/example-project/docs/features/iteration1/prototypes/vite.config.ts b/example-project/docs/features/iteration1/prototypes/vite.config.ts new file mode 100644 index 0000000..78a0a2a --- /dev/null +++ b/example-project/docs/features/iteration1/prototypes/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import { resolve } from 'path' + +export default defineConfig({ + plugins: [vue()], + resolve: { + alias: { '@': resolve(__dirname, 'src') }, + }, + server: { + port: 5174, + }, +}) diff --git a/example-project/docs/features/iteration1/settlement.md b/example-project/docs/features/iteration1/settlement.md new file mode 100644 index 0000000..0707c74 --- /dev/null +++ b/example-project/docs/features/iteration1/settlement.md @@ -0,0 +1,256 @@ +# 需求规格说明书:收入与结算 + +> 文档类型:需求规格 / Feature Specification +> 适用目录:`docs/features/iteration1/` +> 需求类型:NEW +> 版本:v0.1 +> 作者:BA +> 日期:2026-11-16 +> 状态:**v0.1** — 字段/规则/验收已补齐;原型已挂接 +> 源追溯:REQ-011 + +--- + +## 1. 需求说明 + +### 1.1 需求名称 + +收入与结算 + +### 1.2 需求类型 + +NEW + +### 1.3 版本信息 + +| 项目 | 内容 | +|---|---| +| 基线版本 | 无 | +| 目标版本 | v0.1 | + +### 1.4 背景 + +咨询师需要可核对的收入与结算能力,才能持续履约;平台按周期结算并支持提现。 + +### 1.5 目标 + +提供收入概览、月度结算单、提现申请与明细下载。 + +### 1.6 范围 + +本次包含: + +- 收入概览(今日/本月收入、待结算、提现状态) +- 按月结算单(订单明细、服务费、应结金额) +- 提现申请(不超过可提现余额);失败可重提并展示原因 +- 结算单与订单明细文件下载 + +本次不包含: + +- 跨境/多币种/发票税务 +- 费率合同配置后台(费率规则见 platform-capability) +- 支付网关对接细节(platform-capability) + +--- + +## 2. 功能说明 + +### 2.1 功能概述 + +咨询师查看收入与结算单,发起提现并下载明细。 + +### 2.2 适用用户 + +| 用户角色 | 角色说明 | 使用场景 | +|---|---|---| +| CONSULTANT | 咨询师 | 查看收入、提现、下载 | + +### 2.3 主要业务对象 + +| 业务对象 | 说明 | +|---|---| +| IncomeOverview | 收入概览 | +| SettlementBill | 月度结算单 | +| WithdrawalRequest | 提现申请 | + +--- + +## 3. 用户角色与权限 + +| 角色 | 可查看 | 可新增 | 可编辑 | 可删除 | 可审批 | 说明 | +|---|---:|---:|---:|---:|---:|---| +| CONSULTANT | 是(本人) | 是(提现) | 否 | 否 | 否 | 仅本人结算数据 | + +### 3.1 权限规则 + +- PR-001:仅可查看本人结算与提现。 +- PR-002:提现金额不可超过可提现余额。 +- PR-003:未提及操作一律不允许。 + +--- + +## 4. 业务流程 + +### 4.1 主流程 + +1. 咨询师打开收入页查看概览。 +2. 按月查看结算单与明细。 +3. 发起提现;成功则扣减可提现余额;失败展示原因可重提。 +4. 下载结算单/明细文件。 + +### 4.2 异常流程 + +| 编号 | 触发条件 | 系统行为 | 结果 | +|---|---|---|---| +| EX-001 | 提现超额 | 拒绝 | 提示余额不足 | +| EX-002 | 提现失败 | 记录失败原因 | 可重新发起 | + +--- + +## 5. 字段表 + +### 5.1 IncomeOverview / SettlementBill + +| 字段名 | 中文名 | 类型 | 必填 | 描述 | 取值 / 枚举 / 来源 | 创建时必填 | 可修改 | +|---|---|---|---:|---|---|---|---:|---:| +| overview.todayIncome | 今日收入 | decimal(12,2) | 是 | 今日完成订单净收入 | 系统聚合 | 否 | 否 | +| overview.monthIncome | 本月收入 | decimal(12,2) | 是 | 本月完成订单净收入 | 系统聚合 | 否 | 否 | +| overview.pendingSettlement | 待结算金额 | decimal(12,2) | 是 | 未出账净收入 | 系统聚合 | 否 | 否 | +| overview.withdrawableBalance | 可提现余额 | decimal(12,2) | 是 | 已结算未冻结余额 | 系统计算 | 否 | 否 | +| overview.frozenBalance | 冻结金额 | decimal(12,2) | 是 | 提现处理中金额 | 系统计算 | 否 | 否 | +| bill.id | 结算单 ID | string | 是 | 月账单标识 | 系统生成 | 否 | 否 | +| bill.consultantId | 咨询师 ID | string | 是 | 账单所有者 | Consultant.id | 否 | 否 | +| bill.period | 账期 | string(7) | 是 | 月度账期 | YYYY-MM | 否 | 否 | +| bill.status | 账单状态 | enum | 是 | 结算状态 | calculating / issued / adjusted | 系统 | 系统 | +| bill.grossAmount | 订单总额 | decimal(12,2) | 是 | 成交合计 | 明细汇总 | 否 | 否 | +| bill.platformFee | 服务费 | decimal(12,2) | 是 | 平台佣金 | 明细汇总 | 否 | 否 | +| bill.refundAmount | 退款金额 | decimal(12,2) | 是 | 本期退款 | 明细汇总 | 否 | 否 | +| bill.netAmount | 应结金额 | decimal(12,2) | 是 | gross-fee-refund | 系统计算 | 否 | 否 | +| bill.issuedAt | 出账时间 | datetime | 否 | 账单生成完成时间 | 系统生成 | 否 | 否 | + +### 5.2 SettlementLine / WithdrawalRequest + +| 字段名 | 中文名 | 类型 | 必填 | 描述 | 取值 / 枚举 / 来源 | 创建时必填 | 可修改 | +|---|---|---|---:|---|---|---:|---:| +| line.id | 明细 ID | string | 是 | 结算明细标识 | 系统生成 | 否 | 否 | +| line.billId | 结算单 ID | string | 是 | 所属账单 | SettlementBill.id | 否 | 否 | +| line.orderId | 订单 ID | string | 是 | 来源订单 | BookingOrder.id | 否 | 否 | +| line.completedAt | 完成时间 | datetime | 是 | 归属账期依据 | BookingOrder | 否 | 否 | +| line.grossAmount | 订单金额 | decimal(10,2) | 是 | 支付成功金额 | 订单快照 | 否 | 否 | +| line.feeRateVersion | 费率版本 | string | 是 | 订单适用费率 | FeeRateVersion | 否 | 否 | +| line.platformFee | 服务费 | decimal(10,2) | 是 | 按费率计算 | 系统计算 | 否 | 否 | +| line.netAmount | 净收入 | decimal(10,2) | 是 | 可结算金额 | 系统计算 | 否 | 否 | +| withdrawal.id | 提现单 ID | string | 是 | 提现标识 | 系统生成 | 否 | 否 | +| withdrawal.amount | 提现金额 | decimal(12,2) | 是 | 大于 0 | 咨询师输入 | 是 | 否 | +| withdrawal.accountSnapshot | 收款账户快照 | object | 是 | 脱敏展示、加密存储 | 已验证账户 | 是 | 否 | +| withdrawal.status | 提现状态 | enum | 是 | 处理状态 | pending / processing / success / failed | 是 | 系统 | +| withdrawal.gatewayTradeNo | 渠道流水号 | string | 否 | 出款凭据 | 支付网关 | 否 | 否 | +| withdrawal.failureCode | 失败码 | string | 条件 | 失败原因编码 | 支付网关 | 否 | 否 | +| withdrawal.failureReason | 失败原因 | string(500) | 条件 | 用户可见原因 | 系统映射 | 否 | 否 | +| withdrawal.createdAt | 申请时间 | datetime | 是 | 提交时间 | 系统生成 | 否 | 否 | +| withdrawal.completedAt | 完成时间 | datetime | 否 | 成功/失败时间 | 系统生成 | 否 | 否 | + +--- + +## 6. 字段变更说明 + +无 + +--- + +## 7. 业务规则 + +1. **R-CREATE-001(出账范围)**:月度账单仅纳入该账期内 completed 且未被上一账单纳入的订单,并按订单费率版本计算。 +2. **R-CREATE-002(提现金额)**:提现金额须大于 0 且不超过提交瞬间可提现余额;校验与冻结余额在同一事务完成。 +3. **R-CREATE-003(提现幂等)**:客户端幂等键相同的重复申请返回原提现单,不重复冻结余额。 +4. **R-CREATE-004(失败重提)**:提现 failed 后解冻金额,咨询师可新建提现申请;原失败记录不可改写。 +5. **R-QUERY-001(本人隔离)**:咨询师仅可查询、下载本人的概览、账单、明细和提现记录。 +6. **R-QUERY-002(金额口径)**:今日/本月按 Asia/Shanghai 完成时间统计;待结算、可提现、冻结三者不得重叠计入。 +7. **R-QUERY-003(下载一致性)**:下载文件金额、行数和账期必须与页面账单一致,并包含生成时间与账单 ID。 +8. **R-UPDATE-001(出款成功)**:验签成功的网关回调将 processing 置 success 并扣减冻结余额;重复回调幂等。 +9. **R-UPDATE-002(出款失败)**:失败回调将状态置 failed、记录可读原因并原子解冻金额。 +10. **R-UPDATE-003(账单调整)**:已出账订单发生退款时生成调整明细,不直接改写原明细,并将账单标记 adjusted。 +11. **R-DELETE-001(财务留存)**:账单、明细与提现记录不可物理删除。 +12. **R-COMMON-001(金额精度)**:人民币以分为最小计算单位,展示保留两位小数,汇总不得使用浮点运算。 + +--- + +## 8. 业务规则变更说明 + +无 + +--- + +## 9. 状态流转规则 + +| 当前状态 | 触发动作 | 目标状态 | 允许角色 | 规则编号 | +|---|---|---|---|---| +| (无) | applyWithdraw | pending | CONSULTANT | R-STATE-001 | +| pending | gatewaySuccess | success | 系统 | R-STATE-002 | +| pending | gatewayFail | failed | 系统 | R-STATE-003 | +| failed | reapply | pending | CONSULTANT | R-STATE-004 | + +--- + +## 10. 数据约束 + +### 10.1 唯一性约束 + +| 字段 | 唯一范围 | 说明 | +|---|---|---| +| consultantId + period | 咨询师+账期 | 每月一份结算单 | + +### 10.2 引用约束 + +| 当前对象字段 | 引用对象 | 引用字段 | 约束说明 | +|---|---|---|---| +| orderLines.orderId | BookingOrder | id | 须已完成可结算 | + +### 10.3 数据保留策略 + +- DATA-001:结算单与提现记录长期保留供核对。 + +--- + +## 11. 影响范围 + +无 + +--- + +## 12. 验收标准 + +- **AC-001**:Given 咨询师存在已完成、待出账及提现中订单,When 打开收入页,Then 今日、本月、待结算、可提现、冻结金额与提现状态按统一口径正确展示。 +- **AC-002**:Given 月度账单已 issued,When 查看该账期,Then 订单明细、费率版本、服务费、退款与应结金额可逐行核对且汇总一致。 +- **AC-003**:Given 可提现余额为 100 元,When 申请 101 元,Then 系统拒绝;When 合法提现失败,Then 展示失败原因、余额解冻且可新建申请。 +- **AC-004**:Given 咨询师打开本人已出账账单,When 下载结算单与订单明细,Then 文件可打开,账单 ID、账期、行数和金额与页面一致。 + +--- + +## 13. 测试场景建议 + +| 场景编号 | 场景名称 | 前置条件 | 操作 | 预期结果 | +|---|---|---|---|---| +| TC-001 | 查看结算单 | 有已完成订单 | 打开账期 | 明细正确 | +| TC-002 | 超额提现 | 余额 100 | 提现 200 | 拒绝 | +| TC-003 | 失败重提 | 上次 failed | 再提现 | 进入 pending | + +--- + +## 14. 原型引用说明 + +- 原型工程:`docs/features/iteration1/prototypes/`(`npm run dev` → :5174) +- 路由:`/consultant/settlements` + +--- + +## 15. 合并说明 + +无 + +--- + +## 16. AI 实现提示 + +1. 服务费率与结算周期以 platform-capability 配置为准。 +2. 提现与支付回调幂等见 platform-capability,本模块不自建网关。 diff --git a/example-project/docs/plans/20260619-project-plan.md b/example-project/docs/plans/20260619-project-plan.md new file mode 100644 index 0000000..82d3a23 --- /dev/null +++ b/example-project/docs/plans/20260619-project-plan.md @@ -0,0 +1,67 @@ +# 20260619 - Consultation Booking Platform 完整开发计划 + +## 总体策略 + +Domain 优先,逐层外扩。每个阶段围绕一个有边界的子域展开: + +``` +分析业务 → 设计 Domain → Infrastructure → Application → Adapter → Frontend +``` + +## 阶段划分 + +### Phase 0:基础骨架 + +**目标**:建立项目物理结构与基础设施基线 + +- 后端:pom.xml + 四层包结构 + 配置类(MyBatisPlus / Web / Jackson / Security / ExceptionHandler)+ JWT 基础设施 + BCrypt +- 前端:package.json + Vite + Vue Router + Pinia + Axios 拦截器 + 全局样式 +- 文档:standards 目录完整(layers / db / api / naming / security) + +### Phase 1:公共首页 + 用户认证 + +- Domain:User(email/password/name/role/status) +- 后端:Register + Login + JWT 签发 + Profile API +- 前端:首页 + 登录 + 注册 + AppHeader +- 数据表:user(含唯一索引 email)+ seed 管理员 + +### Phase 2:咨询师 + 预约管理 + +- Domain:Consultant + Appointment + TimeSlot +- 核心规则:预约冲突检测(唯一索引 + 代码校验)、状态机(PENDING→CONFIRMED→COMPLETED / CANCELLED) +- 后端:Consultant CRUD + Appointment CRUD + 时间段查询 +- 前端:预约四步流程(选咨询师→选日期→选时间→确认)+ 我的预约列表 +- 数据表:consultant + appointment + branch + +### Phase 3:用户中心 + +- 用户 Dashboard 统计 +- 个人信息编辑 + 密码修改 + +### Phase 4:管理后台 + +- 管理仪表盘 +- 用户管理(启用/停用) +- 咨询师管理(CRUD) +- 预约管理 +- 网点管理(CRUD) + +## 依赖关系 + +``` +Phase 0 (骨架) + └─ Phase 1 (认证) ── 依赖 JWT + SecurityConfig + └─ Phase 2 (预约) ── 依赖 Auth 上下文 + ├─ Phase 3 (用户中心) + └─ Phase 4 (管理后台) +``` + +## 技术决策 + +- Java 17 + Spring Boot 3.2 + MyBatis-Plus 3.5.5 +- JWT HMAC-SHA256 + BCrypt +- 主键 UUID VARCHAR(64),公共字段 created_by/created_time/updated_by/updated_time +- 统一错误响应 `{errorCode, errorMessage, data}` +- API 前缀 `/api/v1/`,分页入参 page/pageSize +- 前端 Vue 3 + Composition API + Pinia + Vue Router 4 + Axios +- Vite 代理 `/api` → `localhost:8080` diff --git a/example-project/docs/plans/20261106-businessrule-datadictionary-api-tests.md b/example-project/docs/plans/20261106-businessrule-datadictionary-api-tests.md new file mode 100644 index 0000000..0e0a3ec --- /dev/null +++ b/example-project/docs/plans/20261106-businessrule-datadictionary-api-tests.md @@ -0,0 +1,359 @@ +# 补齐 BusinessRule / DataDictionary API 集成测试 + +> 日期:2026-11-06 +> +> 关联需求:不涉及(本轮不引入新需求,修复的是 AGENTS.md §10 已写明的规范缺口) +> +> 设计 design:docs/designs/topic/businessrule.md、docs/designs/topic/data-dict.md +> +> +> **plan 一旦定稿就不修改。** 同一资源的二次改造新建 `YYYY-MM-DD-{slug}.md`,不修改原计划文件 + +## 1. 文档说明 + +### 1.1 背景 + +`AGENTS.md` §10「开发自测覆盖要求」写得很硬: + +> 每个 API **必须** 有对应的集成测试 +> 至少覆盖:1 个 Happy Path + 关键失败分支(参数错误 / 权限不足 / 业务冲突) + +现状盘点 —— `backend/src/test/java/com/consultation/adapter/rest/`: + +| Controller | 集成测试 | 状态 | +|---|---|---| +| `AdminController` | `AdminControllerTest`(6 例) | ✅ | +| `AppointmentController` | `AppointmentControllerTest`(3 例) | ✅ | +| `AuthController` | `AuthControllerTest`(3 例) | ✅ | +| `ConsultantController` | `ConsultantControllerTest`(3 例) | ✅ | +| `UserController` | `UserControllerTest`(3 例) | ✅ | +| `BusinessRuleController` | — | ❌ **缺** | +| `DataDictionaryController` | — | ❌ **缺** | +| `HomeController` | — | ❌ 缺(纯静态页,无业务规则,留待后续) | + +两个缺口都不是"锦上添花",而是 **对外暴露的公开读接口**,且都 `permitAll`(无需鉴权即可访问), +一旦字段结构漂移(ruleName 改名、字典类型漏注册)不会有任何编译错误,只会静默返回错数据。 + +关键决策点: + +- **只补测试,不动生产代码。** 这两个 Controller 的实现(`BusinessRuleAppService` / `DataDictionaryAppService`) + 本身没有问题,缺的是"证明它们是对的"的用例。改动面越窄,评审与回滚成本越低。 +- **本轮不写 QA 用例。** QA 用例针对"需求规格的验收标准",本轮没有新需求、没有契约变更, + 按 `AGENTS.md` §10 的分层定义,QA 用例库不需要新增条目(见 §11.4 同步检查)。 + +### 1.2 目标 + +- 实现目标: + - 新增 `BusinessRuleControllerTest`,覆盖 `GET /api/v1/business-rules` 的 happy path、规则完整性、YAML 配置透出、免鉴权 + - 新增 `DataDictionaryControllerTest`,覆盖 `GET /api/v1/data-dictionaries` 与 `GET /api/v1/data-dictionaries/{type}` 的 happy path、大小写不敏感、字典项内容、未知类型失败分支 +- 技术边界: + - **只新增 2 个测试文件**,`backend/src/main/**` 一行不动 + - 不引入新依赖(RestAssured + JUnit 5 + Hamcrest 均已在 `pom.xml`) + - 不改数据库、不改 API 契约、不改前端 + +------ + +## 2. 领域模型(PlantUML) + +本轮不涉及 —— 无领域模型变更。仅在 §9 断言已有模型对外投影的结果。 + +## 3. 数据库设计(SQL DDL) + +本轮不涉及 —— 无表结构变更。目标接口不读写数据库。 + +## 4. API 设计(OpenAPI) + +本轮不涉及 —— **无 API 契约变更**。目标接口的现有契约(只读,仅此如下,不做任何修改): + +```yaml +openapi: 3.0.0 +info: + title: 业务规则 / 数据字典 API(现有契约,本轮不改) + version: 1.0.0 +paths: + /api/v1/business-rules: + get: + summary: 列出全部业务规则 + responses: + '200': + description: 规则数组 + content: + application/json: + schema: + type: array + items: + type: object + properties: + ruleName: { type: string } + description: { type: string } + config: { type: object } + /api/v1/data-dictionaries: + get: + summary: 列出全部数据字典类型 + responses: + '200': { description: 字典数组 } + /api/v1/data-dictionaries/{type}: + get: + summary: 按类型取数据字典 + parameters: + - name: type + in: path + required: true + schema: { type: string } + responses: + '200': { description: 单个字典 } + '400': { description: 字典类型不存在 } +``` + +## 5. 时序图(PlantUML) + +```plantuml +@startuml +actor Client +participant "BusinessRuleController\n/ DataDictionaryController" as API +participant "BusinessRuleAppService\n/ DataDictionaryAppService" as Service +participant "BusinessRuleProvider\n/ DataDictionaryUtil" as Domain + +Client -> API : GET /api/v1/business-rules +API -> Service : getAllRules() +Service -> Domain : ruleCache.values() +Domain --> Service : List> +Service --> API : List> +API --> Client : 200 JSON + +Client -> API : GET /api/v1/data-dictionaries/{unknown} +API -> Service : getByType(type) +Service -> Domain : values() 过滤 +Domain --> Service : empty +Service -> API : IllegalArgumentException +API --> Client : 400 ErrorResponse +@enduml +``` + +------ + +## 6. 专题设计(Markdown) + +### 6.1 权限设计 + +`SecurityConfig` 中 `/api/v1/data-dictionaries/**` 与 `/api/v1/business-rules/**` 均为 `permitAll`。 +本轮新增用例 **一律不带 token**,顺带把"这两个接口免鉴权"这条契约钉死 —— 将来有人误加 +`.authenticated()` 时,用例会立刻红。 + +### 6.2 并发控制 + +不涉及(只读接口,无写操作)。 + +### 6.3 事务设计 + +不涉及(只读,不涉及事务边界)。 + +### 6.4 异常处理 + +**这是本轮唯一的"契约断言"重点。** + +`GET /api/v1/data-dictionaries/{type}` 传入未知类型时: + +`DataDictionaryAppService.getByType()` → `IllegalArgumentException("字典类型不存在: " + typeName)` +→ `GlobalExceptionHandler.handleBadArg()` → HTTP 400,body 为 `ErrorResponse`: + +```json +{ + "errorCode": "PARAM_ERROR", + "errorMessage": "字典类型不存在: NOT_EXIST", + "data": null +} +``` + +> ⚠️ **发现的既有文档不一致(本轮不修,仅记录)** +> +> `AGENTS.md` §7 给的示例 JSON 写的是 `"message"` 字段: +> ```json +> { "errorCode": "APPOINTMENT_CONFLICT", "message": "该时间段已被占用", "timestamp": "..." } +> ``` +> 而 `GlobalExceptionHandler.ErrorResponse` 这个 record 的实际字段是 +> **`errorCode` / `errorMessage` / `data`**,既没有 `message` 也没有 `timestamp`。 +> +> 事实文档与代码不一致,按 `AGENTS.md` §13 的同步要求应当修正 `AGENTS.md` §7, +> 但那属于"改事实文档"而非"补测试",**建议单独开一轮**处理,本轮不动 `AGENTS.md`。 +> +> 本轮测试 **以代码实际契约为准**(断言 `errorCode` + `errorMessage`)。 + +### 6.5 性能设计 + +不涉及。 + +### 6.6 扩展性设计 + +不涉及。 + +------ + +## 7. 一致性约束(必须遵守) + +* 断言里的字段名必须与实际 JSON 一致: + * 业务规则项:`ruleName` / `description` / `config` + * 数据字典:`typeName` / `description` / `items[]`,字典项 `code` / `description` + * 错误响应:`errorCode` / `errorMessage` / `data` +* 枚举 code 一律等于枚举名(`Description.getCode()` → `name()`): + * `USER_ROLE` → `ROLE_USER` / `ROLE_ADMIN` + * `USER_STATUS` → `ACTIVE` / `DISABLED` + * `APPOINTMENT_STATUS` → `PENDING` / `CONFIRMED` / `COMPLETED` / `CANCELLED` + * `CONSULTANT_STATUS` → `ACTIVE` / `DISABLED` + * `BRANCH_STATUS` → `ACTIVE` / `DISABLED` +* 业务规则 `ruleName` 取自 `AppointmentRule` / `AuthRule` 枚举,共 **7 条**(4 + 3) +* 命名规范: + * 测试类名 `{被测Controller}Test` → `BusinessRuleControllerTest` / `DataDictionaryControllerTest` + * 方法名 `should_{action}_{expectedResult}` + * **不写 `TC-` 编号** —— `TC-xxx` 是 QA 用例的编号体系,开发自测不进入编号空间 + (`AGENTS.md` §10 用例编号列:「开发自测 = 无编号,命名表达意图」) +* 归属:这两个文件属于 **开发自测**(验证"代码按 Plan 的设计工作"), + **不是 QA 测试**,不进 `docs/test-cases/e2e-cases/`,也不进 `e2e/tests/qa/` + +------ + +## 8. 单元测试设计 + +本轮不涉及 —— 不改 domain/application 层,不新增单元测试。 +`BusinessRuleProvider` 的 YAML 装载逻辑与 `DataDictionaryUtil` 的投影逻辑 +由 §9 的集成测试经由 HTTP 端到端覆盖。 + +------ + +## 9. API 集成测试设计 + +### 9.1 测试范围 + +* 切片类型:全链路集成(`@SpringBootTest(webEnvironment = RANDOM_PORT)` + RestAssured) +* 真实加载组件:Controller → AppService → domain(`BusinessRuleProvider` / `DataDictionaryUtil`) +* Mock 边界:**无**。两个接口都不触碰 DB,也不调外部服务,全链路真实 +* 继承 `com.consultation.TestBase`(已含 `@BeforeEach` 的 `resetDbService.resetAll()`, + 本轮用例不写库,但沿用同一隔离机制,保证可重复执行、与执行顺序无关) + +### 9.2 测试环境 + +* 数据库:MariaDB4j(`TestBase` 已配好)—— 本轮用例不读写 +* 中间件:无 +* 下游服务:无 +* 迁移脚本:`spring.flyway.enabled=false`(test profile 已有) +* 鉴权:两个端点 `permitAll`,**用例不带 Authorization 头** + +### 9.3 用例覆盖场景 + +- [x] 契约校验:状态码、响应字段、错误返回结构 +- [x] 鉴权场景:免鉴权可访问(`permitAll` 契约) +- [x] 业务闭环:不涉及(只读接口) +- [x] 数据一致性:YAML 配置 → 接口透出;枚举 → 字典项 +- [ ] 状态机 / 并发幂等 / 下游异常:不涉及(只读接口,无状态流转) + +### 9.4 测试数据 + +* 数据准备:**不需要**。无 DB 写入 +* 隔离策略:沿用 `TestBase.setUp()` 的 `resetDbService.resetAll()` +* 断言规范:RestAssured + Hamcrest(`not(empty())` / `hasItem` / `hasKey` / `containsString`) + +### 9.5 用例清单 + +#### BusinessRuleControllerTest — `GET /api/v1/business-rules` + +| # | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :--: | :------: | :------ | :------ | :------ | +| 1 | 正常场景 | 列出全部业务规则 | 200;数组非空;长度为 7(4 条预约规则 + 3 条鉴权规则) | §7 | +| 2 | 正常场景 | 包含预约冲突检测规则 | 200;含 `ruleName == "appointment_conflict_detection"`,其 `description` 非空 | §7 | +| 3 | 正常场景 | 包含鉴权令牌过期规则 | 200;含 `ruleName == "auth_token_expiration"` | §7 | +| 4 | 数据一致性 | YAML 配置透出到 `config` | 200;每条规则含 `config`;`config.appointment.slot.minMinutes == 30`;`config.auth.token.expirationMs == 86400000` | §7 | +| 5 | 鉴权场景 | 不带 token 也能访问 | 200(`permitAll` 契约) | §6.1 | + +#### DataDictionaryControllerTest + +| # | 接口 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :--: | :--: | :------: | :------ | :------ | :------ | +| 1 | `GET /api/v1/data-dictionaries` | 正常场景 | 列出全部数据字典类型 | 200;长度为 5;每项 `typeName` / `description` / `items` 非空 | §7 | +| 2 | `GET /api/v1/data-dictionaries/USER_ROLE` | 正常场景 | 按类型取字典 | 200;`typeName == "USER_ROLE"`;`items` 含 `code == "ROLE_USER"` 与 `code == "ROLE_ADMIN"`,各自 `description` 非空 | §7 | +| 3 | `GET /api/v1/data-dictionaries/user_role` | 边界场景 | 类型名大小写不敏感 | 200;`typeName == "USER_ROLE"`(`equalsIgnoreCase` 契约) | §7 | +| 4 | `GET /api/v1/data-dictionaries/APPOINTMENT_STATUS` | 正常场景 | 状态字典项完整 | 200;`items` 含 `PENDING` / `CONFIRMED` / `COMPLETED` / `CANCELLED` 四个 code | §7 | +| 5 | `GET /api/v1/data-dictionaries/NOT_EXIST` | 异常场景 | 未知字典类型 | 400;`errorCode == "PARAM_ERROR"`;`errorMessage` 含 `"字典类型不存在"` | §6.4 | + +**合计 10 个用例。** 覆盖 2 个 Controller 的全部对外方法与全部可达失败分支。 + +------ + +## 11. 修改清单 + +### 11.1 代码修改 + +**无。** `backend/src/main/**` 本轮一行不改。 + +### 11.1.2 新增文件 + +| 操作 | 文件 | 用途 | +| :--: | :-- | :-- | +| 新增 | `backend/src/test/java/com/consultation/adapter/rest/BusinessRuleControllerTest.java` | 5 个用例,覆盖 `GET /api/v1/business-rules` | +| 新增 | `backend/src/test/java/com/consultation/adapter/rest/DataDictionaryControllerTest.java` | 5 个用例,覆盖两个数据字典接口 | + +#### 11.1.x 关键文件速查 + +| 操作 | 文件 | 备注 | +| :--: | :-- | :-- | +| 新增 | `backend/src/test/java/com/consultation/adapter/rest/BusinessRuleControllerTest.java` | 继承 `TestBase`,`should_*` 命名 | +| 新增 | `backend/src/test/java/com/consultation/adapter/rest/DataDictionaryControllerTest.java` | 继承 `TestBase`,`should_*` 命名 | + +### 11.2 接口变更 + +无。 + +### 11.3 数据库变更 + +无。 + +### 11.4 文档同步检查 + +| 文档 | 是否需要更新 | 理由 | +|---|---|---| +| `docs/designs/api.yaml` | **不涉及** | 无 API 契约变更 | +| `docs/designs/db-schema.md` | **不涉及** | 无表结构变更 | +| `docs/designs/topic/businessrule.md` | **不涉及** | 规则定义未变,只是给它补了测试 | +| `docs/designs/topic/data-dict.md` | **不涉及** | 字典定义未变,只是给它补了测试 | +| `docs/test-cases/e2e-cases/test-cases.md` | **不涉及** | 属开发自测,不是 QA 用例;无新需求、无验收标准变化 | +| `AGENTS.md` §7 | **本轮不修,建议单独开一轮** | 见 §6.4 记录的 `ErrorResponse` 字段名不一致 | + +--- + +## 12. 验证步骤 + +1. **基线(改动前)**:`cd backend && mvn -o -B test` → 期望 `Tests run: 18, Failures: 0, Errors: 0` +2. **实现后**:`cd backend && mvn -o -B test` → 期望 `Tests run: 28, Failures: 0, Errors: 0` + (18 基线 + 10 新增) +3. **只看新用例**:`cd backend && mvn -o -B test -Dtest='BusinessRuleControllerTest,DataDictionaryControllerTest'` + → 期望 `Tests run: 10, Failures: 0, Errors: 0` +4. **确认没碰生产代码**:`git status --short` → 只应出现 2 个新增测试文件 +5. **确认没有引入 `TC-` 编号**:`grep -rn "TC-" backend/src/test/` → 无输出 + +--- + +## 13. 风险与回滚 + +* 风险点 1:**用例断言过细导致脆**。例如把 `config.appointment.slot.minMinutes == 30` 写死, + 将来 YAML 改了分钟数,用例会红 —— 这是**预期的**,配置项被改动本来就应该有测试提醒。 + 但要避免断言整个 `config` 的 JSON 全等。 +* 风险点 2:**规则条数 7 会随业务规则增减而变**。同理,属预期提醒。 + 若担心太脆,可只断言"包含 X 条规则"而非"恰好 7 条";本轮选择断言恰好 7 条, + 因为新增/删除业务规则是低频且需要评审的动作。 +* 风险点 3:**未知类型分支被 Spring 兜底成 500**。若 `IllegalArgumentException` 未被 + `GlobalExceptionHandler` 捕获,会落到 `handleOther` → 500 `SYSTEM_ERROR`。 + 用例 5 会直接暴露这个问题。 +* 回滚方案:删除 2 个新增测试文件即可,**零生产代码回滚风险**。 + +--- + +## 14. 实施后需更新的 design 文档 + +不涉及(见 §11.4)。 + +--- + +## 15. 变更记录(可选) + +| 版本 | 日期 | 变更内容 | +| ---- | ---------- | -------- | +| v1.0 | 2026-11-06 | 初始版本 | diff --git a/example-project/docs/plans/20261106-fix-public-endpoints-and-error-doc.md b/example-project/docs/plans/20261106-fix-public-endpoints-and-error-doc.md new file mode 100644 index 0000000..f1dde59 --- /dev/null +++ b/example-project/docs/plans/20261106-fix-public-endpoints-and-error-doc.md @@ -0,0 +1,449 @@ +# 修复业务规则配置绑定缺陷,并让错误模型文档与实现对齐 + +> 日期:2026-11-06 +> +> 关联需求:不涉及(本轮修的是实现与事实文档之间的既有偏差,偏差来源见 §1.1) +> +> 设计 design:docs/designs/topic/businessrule.md、docs/designs/topic/error-code.md +> +> +> **plan 一旦定稿就不修改。** 同一资源的二次改造新建 `YYYY-MM-DD-{slug}.md`,不修改原计划文件 + +## 1. 文档说明 + +### 1.1 背景 + +上一轮(`20261106-businessrule-datadictionary-api-tests.md`)补齐了 BusinessRule / +DataDictionary 的集成测试,runner 在无人值守下记录了 **3 项"发现但未修"**。 +本轮把其中 2 项真正修掉,外加 1 项上一轮之后新核实的问题: + +| # | 问题 | 性质 | 本轮处理 | +|---|---|---|---| +| 1 | `config.auth.publicEndpoints` 被序列化成 `{"0":"/api/v1/auth/**",...}` 而非 JSON 数组 | **实现缺陷** | 修(§11.1) | +| 2 | `AGENTS.md` §7 描述了一套不存在的错误模型 | **事实文档与实现不符** | 修(§11.3) | +| 3 | `config.auth.*` 的来源与 `docs/designs/topic/businessrule.md` 的"配置路径"列对不上 | **事实文档与实现不符** | 修(§11.3) | +| 4 | `docs/standards/error.md` 描述的 `IError` / `AbstractException` / `ErrorGroup` 体系在代码里 **完全不存在** | **事实文档与实现不符** | 修(§11.3) | +| 5 | 6 处引用 `docs/dev/design-fact/**` 的死链(该目录不存在) | **死链** | 修(§11.3) | + +**问题 1 的根因**(已实测确认,不是猜测): + +`BusinessRuleConfig.auth` 声明为 `Map`,Spring Boot 的 binder 拿到 YAML 里的 +**序列**(`publicEndpoints: ["...","..."]`)时,无法确定该绑成数组还是 Map,于是退化成 +**以 0/1/2… 为键的 Map**。于是 Jackson 序列化出 `{"0":"...","1":"..."}` —— +下游任何按数组消费的客户端都会拿到错误结构。 + +同一份 `auth.yml` 里的 `password` / `token` 是纯标量子结构,绑成 Map 没问题。 +**只有列表这一种形状会被绑坏。** + +**问题 2/4 的根因**:`AGENTS.md` §7 与 `docs/standards/error.md` 描述的是一套 +"照抄自别的项目"的错误模型 —— `BusinessException`、`IError`、`ErrorGroup`、 +`{errorCode, message, timestamp}`。本仓库的代码里 **一个都不存在**。 +实际实现是: + +``` +GlobalExceptionHandler(@RestControllerAdvice) +├── IllegalArgumentException → 400 PARAM_ERROR +├── IllegalStateException → 409 BUSINESS_CONFLICT +├── MethodArgumentNotValidException → 400 VALIDATION_ERROR +└── Exception(兜底) → 500 SYSTEM_ERROR +响应体:ErrorResponse{errorCode, errorMessage, data} +``` + +新人按 §7 写代码会直接编译不过(`BusinessException` 不存在), +按文档里的示例 JSON 解析响应也会拿到 `null`(字段叫 `errorMessage` 不叫 `message`)。 + +关键决策点: + +- **问题 1 改 `BusinessRuleConfig` 的类型声明,不改 YAML。** + YAML 里的列表写法是 **正确且符合直觉的**(`publicEndpoints` 就是个列表), + 错的是 Java 侧用 `Map` 去接它。改 YAML 去迁就错误的类型声明是本末倒置。 +- **问题 1 只把 `auth` 改成有类型的嵌套类,`appointment` 保持 `Map`。** + `appointment` 当前全是标量子结构,没有列表,绑 Map 是安全的;把它也类型化要新增 4 个 + 嵌套类、放大 diff 与回归面,而它今天 **没有暴露出任何问题**。留作后续。 +- **问题 2/3/4/5 改文档,不改代码。** 代码是对的(`error-code.md` 的"当前实现映射"表 + 已经如实记录了现状),错的是文档。 + +### 1.2 目标 + +- 实现目标: + - `GET /api/v1/business-rules` 返回的 `config.auth.publicEndpoints` 是 **JSON 数组** + - `AGENTS.md` §7 / §12 与 `docs/standards/error.md` 的错误模型描述与代码 **完全一致** + - `docs/designs/topic/businessrule.md` 的"配置路径"列指向 **真实生效** 的配置来源 + - 仓库内不再有指向 `docs/dev/design-fact/**` 的死链 +- 技术边界: + - 生产代码改动 **限 2 个文件**:`BusinessRuleConfig`、`BusinessRuleProvider` + - YAML 内容 **不改** + - API 契约 **不改**(`docs/designs/api.yaml` 的 `config: {type: object}` 不动) + - 前端、数据库、QA 用例 **不涉及** + +--- + +## 2. 领域模型(PlantUML) + +本轮 **无领域模型变更**。`BusinessRuleConfig` 的类型收紧属于配置绑定细节, +不改变任何聚合、值对象或状态机。 + +```plantuml +@startuml +skinparam classAttributeIconSize 0 + +class BusinessRuleConfig { + - appointment : Map + - auth : AuthConfig +} + +class AuthConfig { + - password : PasswordConfig + - token : TokenConfig + - publicEndpoints : List +} + +class PasswordConfig { + - minLength : int + - algorithm : String +} + +class TokenConfig { + - expirationMs : long + - algorithm : String +} + +BusinessRuleConfig *-- AuthConfig +AuthConfig *-- PasswordConfig +AuthConfig *-- TokenConfig +AuthConfig *-- "publicEndpoints : String" <> +@enduml +``` + +--- + +## 3. 数据库设计(SQL DDL) + +不涉及 —— 本轮目标接口不读写数据库,无表结构变更。 + +--- + +## 4. API 设计(OpenAPI) + +**无契约变更。** `docs/designs/api.yaml` 里 `BusinessRuleResponse.config` 是 +`{ type: object }`,本轮不细化它(细化属于契约变更,需另行评审)。 + +本轮修复后响应体的 **实际形状**(`config` 部分,现状 vs 修复后): + +```yaml +# 现状(publicEndpoints 是被绑坏的索引 Map) +config: + auth: + password: { minLength: 8, algorithm: BCrypt } + token: { expirationMs: 86400000, algorithm: HMAC-SHA256 } + publicEndpoints: { "0": "/api/v1/auth/**", "1": "/api/v1/home/**", ... } + +# 修复后(publicEndpoints 是真正的数组) +config: + auth: + password: { minLength: 8, algorithm: BCrypt } + token: { expirationMs: 86400000, algorithm: HMAC-SHA256 } + publicEndpoints: [ "/api/v1/auth/**", "/api/v1/home/**", "/api/v1/consultants/**", + "/api/v1/data-dictionaries/**", "/api/v1/business-rules/**" ] +``` + +> `config.appointment` 子树保持原样(`conflict` / `slot` / `available` / `cancel`), +> 不在本轮变更范围内。 + +--- + +## 5. 时序图(PlantUML) + +```plantuml +@startuml +participant "Spring Environment\n(含 business-rules/*.yml)" as Env +participant "BusinessRuleConfig\n(@ConfigurationProperties)" as Cfg +participant "BusinessRuleProvider\n(@PostConstruct)" as Prov +database "HTTP 响应\nList>" as Res + +Env -> Cfg : 绑定 appointment / auth +Cfg -> Cfg : auth.publicEndpoints\n→ List(不再是索引 Map) +Cfg -> Prov : 注入配置 Bean +Prov -> Prov : ObjectMapper.convertValue(cfg)\n→ Map(投影) +Prov -> Res : config.auth.publicEndpoints = ["...","..."] +@enduml +``` + +--- + +## 6. 专题设计(Markdown) + +### 6.1 权限设计 + +不涉及 —— `GET /api/v1/business-rules` 仍是 `permitAll`,本轮不改鉴权。 + +### 6.2 并发控制 + +不涉及 —— `BusinessRuleProvider` 在 `@PostConstruct` 里一次性建缓存,之后只读。 + +### 6.3 事务设计 + +不涉及 —— 只读接口,无写操作、无事务边界变化。 + +### 6.4 异常处理 + +本轮 **不改任何异常处理**。 + +要改的是 **文档对异常处理的描述**。改完之后 `AGENTS.md` §7 必须能回答三个问题: + +1. 有哪些异常 → 各自映射什么 HTTP 状态码与 errorCode? +2. 响应体长什么样? +3. 新代码该抛什么异常? + +答案(以 `GlobalExceptionHandler` 当前实现为准): + +| 抛出什么 | HTTP | errorCode | 什么时候用 | +|---|---|---|---| +| `IllegalArgumentException` | 400 | `PARAM_ERROR` | 参数不合法、查不到的资源(消息即 `errorMessage`) | +| `IllegalStateException` | 409 | `BUSINESS_CONFLICT` | 业务状态冲突(如同一时段被占用) | +| `MethodArgumentNotValidException` | 400 | `VALIDATION_ERROR` | `@Valid` 字段级校验失败(自动抛出,不手写) | +| 其它 `Exception` | 500 | `SYSTEM_ERROR` | 兜底,消息固定为「系统繁忙」 | + +响应体(`GlobalExceptionHandler.ErrorResponse` 这个 record 的实际字段): + +```json +{ + "errorCode": "BUSINESS_CONFLICT", + "errorMessage": "该时段已被占用", + "data": null +} +``` + +鉴权失败由 Spring Security 直接返回 **401 / 403**,**不走** `ErrorResponse` 包装。 + +### 6.5 性能设计 + +不涉及 —— 投影在 `@PostConstruct` 里做一次,运行时开销不变。 + +### 6.6 扩展性设计 + +**这条是本轮的核心收益。** + +现在 `auth` 有了类型,`AuthConfig` 就是契约本身: + +- YAML 里少写一个键 → 绑定时用类里的默认值,**不会静默丢字段** +- YAML 里多写一个键 → Spring Boot 绑定到未知属性时会 **fail fast**(取决于 + `ignoreUnknownFields`,默认 true 则是静默忽略 —— 所以 §6.7 要求 YAML 与类同时改) +- YAML 里把列表写错形状 → 类型不匹配,启动即报错,而不是像现在这样 **静默产出 `{"0":...}`** + +`appointment` 保持 `Map`:它没有列表,今天是安全的; +但**如果将来往 `appointment.yml` 里加列表,会重现同一个 bug**。 +本轮在 `docs/standards/business-rule.md` 里把这条约束写清楚(§11.3)。 + +### 6.7 一致性约束(必须遵守) + +* **YAML 与 Java 类必须同时改。** `auth.yml` 的键结构 = `AuthConfig` 的字段结构, + 一一对应: + * `auth.password.minLength` → `PasswordConfig.minLength`(`int`) + * `auth.password.algorithm` → `PasswordConfig.algorithm`(`String`) + * `auth.token.expirationMs` → `TokenConfig.expirationMs`(`long`) + * `auth.token.algorithm` → `TokenConfig.algorithm`(`String`) + * `auth.publicEndpoints` → `AuthConfig.publicEndpoints`(`List`) +* **默认值必须与 YAML 一致。** 类里的字段默认值写死当前 YAML 里的值 + (8 / BCrypt / 86400000 / HMAC-SHA256 / 5 个端点), + 这样即使 YAML 加载失败,接口也不会返回"空壳"配置。 +* **`appointment` 子树保持 `Map`**,其 YAML 键与值本轮 **一个字都不改**。 +* **不改 YAML 文件内容**(`backend/src/main/resources/business-rules/*.yml`), + 只改它对应的 Java 类型声明。 +* **不改 API 契约**:`docs/designs/api.yaml` 不动。 +* **不改 `SecurityConfig`、`GlobalExceptionHandler`、`ErrorResponse`**。 +* 命名: + * 测试方法名 `should_{action}_{expectedResult}` + * **不写 `TC-` 编号**(`TC-xxx` 是 QA 用例的编号体系,开发自测不进入编号空间, + 见 `AGENTS.md` §10) +* 归属:新增/修改的测试属于 **开发自测**(验证"代码按 Plan 的设计工作"), + **不是 QA 测试**,不进 `docs/test-cases/e2e-cases/`,也不进 `e2e/tests/qa/`。 + +--- + +## 7. 单元测试设计 + +本轮 **不新增单元测试**。 + +`BusinessRuleProvider` 的投影逻辑由 §9 的集成测试经由 HTTP 端到端覆盖 —— +它依赖 Spring 的 binder 与 YAML 装载,脱离 Spring 上下文做单元测试意义有限 +(且项目现有约定就是 API 层集成测试覆盖,见 `AGENTS.md` §10)。 + +--- + +## 8. 单元测试设计(补充:投影的内部契约) + +不涉及。 + +--- + +## 9. API 集成测试设计 + +### 9.1 测试范围 + +* 切片类型:全链路集成(`@SpringBootTest(webEnvironment = RANDOM_PORT)` + RestAssured) +* 真实加载组件:Controller → AppService → `BusinessRuleProvider` → `BusinessRuleConfig` → YAML +* Mock 边界:**无** +* 继承 `com.consultation.TestBase`(沿用 `@BeforeEach` 的 `resetDbService.resetAll()`) + +### 9.2 测试环境 + +* 数据库:MariaDB4j —— 本轮用例不读写 +* 中间件:无;下游服务:无 +* 迁移脚本:`spring.flyway.enabled=false`(test profile 已有) +* 鉴权:`permitAll`,用例不带 `Authorization` 头 + +### 9.3 用例覆盖场景 + +- [x] 契约校验:状态码、响应字段、错误返回结构 +- [x] 鉴权场景:免鉴权可访问(`permitAll` 契约) +- [x] 业务闭环:不涉及(只读接口) +- [x] 数据一致性:YAML → 接口透出(`publicEndpoints` 数组化 + 标量不回归) +- [ ] 状态机 / 并发幂等 / 下游异常:不涉及(只读接口,无状态流转) + +### 9.4 测试数据 + +* 数据准备:**不需要**。无 DB 写入 +* 隔离策略:沿用 `TestBase.setUp()` 的 `resetDbService.resetAll()` +* 断言规范:**RestAssured + Hamcrest + 少量 Java 断言** + +> ⚠️ **GPath 限制(上一轮踩过的坑)** +> +> RestAssured 5.3.2 走 Jayway/GPath,**`$[*]` 这类写法不被支持**, +> 且嵌套列表的展开行为不可靠。 +> 本轮涉及列表的断言 **一律走 `jsonPath().getList("$")` 取出 `List>`, +> 再用 Java 断言遍历**,不依赖 GPath 对嵌套列表的展开。 + +### 9.5 用例清单 + +#### 新增:`BusinessRuleControllerTest` 补 2 例 + +| # | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :--: | :------: | :------ | :------ | :------ | +| 1 | 数据一致性 | `publicEndpoints` 是 JSON 数组 | 200;`config.auth.publicEndpoints` 是 `List`(**不是 Map**);长度 5;含 `/api/v1/auth/**`、`/api/v1/business-rules/**`;每项以 `/api/v1/` 开头 | §6.6 §6.7 | +| 2 | 数据一致性 | `auth` 下的标量配置未被类型化改动破坏 | 200;`config.auth.password.minLength == 8`、`password.algorithm == "BCrypt"`、`token.expirationMs == 86400000`、`token.algorithm == "HMAC-SHA256"` | §6.7 | + +用例 2 是 **防回归锚点**:把 `Map` 换成有类型的类时,最容易出的错就是 +数字类型被 Jackson 变成另一种数值类型、或字段名拼错 —— 用例 1 断言不出这类问题。 + +**合计 2 个新增用例。** 现有 5 例保持不变(`should_expose_yaml_config_for_each_rule` +里的 `config.appointment.slot.minMinutes` 与 `config.auth.token.expirationMs` 断言 +在改造后必须 **继续通过** —— 这是天然的回归网)。 + +--- + +## 11. 修改清单 + +### 11.1 代码修改 + +| 操作 | 文件 | 改动 | +| :--: | :-- | :-- | +| 改 | `backend/src/main/java/com/consultation/domain/businessrule/BusinessRuleConfig.java` | `auth` 由 `Map` 改为有类型的嵌套类 `AuthConfig`(含 `PasswordConfig` / `TokenConfig` / `List publicEndpoints`);`appointment` 保持 `Map` | +| 改 | `backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleProvider.java` | 注入 `ObjectMapper`,在 `@PostConstruct` 里把 `BusinessRuleConfig` 投影为 `Map` 后再挂进 `config`,保证对外返回结构不变(除 `publicEndpoints` 变回数组) | + +> **为什么投影放在 Provider(infrastructure)而不是让 domain 直接返回 POJO**: +> `BusinessRuleConfig` 在 `domain` 层,`AGENTS.md` §3 要求 domain 不依赖基础设施; +> 而 JSON 形状是基础设施关注点。所以 domain 保持纯 Java 类型, +> 由 infrastructure 用 `ObjectMapper` 做投影,对外契约 +> `List>` **一个字都不变**, +> `BusinessRuleAppService` / `BusinessRuleController` **不需要改**。 + +### 11.2 接口变更 + +无。 + +### 11.3 文档修改 + +| 操作 | 文件 | 改动 | +| :--: | :-- | :-- | +| 改 | `AGENTS.md` §7 | 按 `GlobalExceptionHandler` 实际实现重写错误模型:4 条异常映射表 + 真实响应体 `{errorCode, errorMessage, data}`;删除不存在的 `BusinessException` / `APPOINTMENT_CONFLICT` / `message` / `timestamp` | +| 改 | `AGENTS.md` §12 | 检查清单里「业务校验使用 `BusinessException`」改为实际异常类型(`IllegalArgumentException` / `IllegalStateException`);3 条 `docs/dev/design-fact/**` 死链改指 `docs/designs/**` | +| 改 | `docs/standards/error.md` | 删除 `IError` / `ErrorGroup` / `AbstractException` 异常类层次(代码里不存在);换成 §6.4 的实际映射表;错误码表指向 `docs/designs/topic/error-code.md`(修死链) | +| 改 | `docs/standards/business-rule.md` | 结尾死链 `docs/dev/design-fact/others/businessrule.md` → `docs/designs/topic/businessrule.md`;补一条约束:**只有列表会被 `Map` 绑坏**,将来往 YAML 加列表前必须先给对应配置类加类型 | +| 改 | `docs/standards/data-dictionary.md` | 结尾死链 `docs/dev/design-fact/others/data-dict.md` → `docs/designs/topic/data-dict.md` | +| 改 | `docs/designs/topic/businessrule.md` | 认证规则表的「配置路径」列改为真实来源(`auth.yml → token.expirationMs` 而非 `application.yml → jwt.expiration`;`auth.yml → password.algorithm` 而非 `SecurityConfig (hardcoded)`) | + +### 11.4 文档同步检查 + +| 文档 | 是否需要更新 | 理由 | +|---|---|---| +| `docs/designs/api.yaml` | **不涉及** | 无 API 契约变更(`config` 仍是自由 object) | +| `docs/designs/db-schema.md` | **不涉及** | 无表结构变更 | +| `docs/designs/topic/businessrule.md` | **已更新** | 配置路径列与实现对齐(§11.3) | +| `docs/designs/topic/data-dict.md` | **不涉及** | 字典定义未变 | +| `docs/designs/topic/error-code.md` | **不涉及** | 其"当前实现映射"表已如实记录现状,无需改 | +| `docs/test-cases/e2e-cases/test-cases.md` | **不涉及** | 属开发自测,不是 QA 用例;无新需求、无验收标准变化 | +| `docs/standards/error.md` | **已更新** | 见 §11.3 | +| `docs/standards/business-rule.md` | **已更新** | 见 §11.3 | +| `docs/standards/data-dictionary.md` | **已更新** | 见 §11.3 | +| `AGENTS.md` | **已更新** | §7 / §12,见 §11.3 | + +--- + +## 12. 验证步骤 + +1. **基线(改动前)**:`cd backend && mvn -o -B test` → 期望 `Tests run: 28, Failures: 0, Errors: 0` +2. **实现后**:`cd backend && mvn -o -B test` → 期望 `Tests run: 30, Failures: 0, Errors: 0` + (28 基线 + 2 新增) +3. **只看新用例**:`cd backend && mvn -o -B test -Dtest='BusinessRuleControllerTest'` + → 期望 `Tests run: 7, Failures: 0, Errors: 0`(原 5 + 新 2) +4. **确认没碰不该碰的**: + * `git status --short` → 只应出现 §11.1 / §11.3 列出的文件 + * `git diff -- backend/src/main/resources/business-rules/` → **必须为空**(YAML 不改) + * `git diff -- backend/src/main/java/com/consultation/adapter/` → **必须为空** + * `git diff -- backend/src/main/java/com/consultation/application/` → **必须为空** + * `git diff -- docs/designs/api.yaml` → **必须为空** +5. **确认死链已清**:`grep -rn "design-fact" --include="*.md" . | grep -v "docs/plans/"` + → 无输出(`docs/plans/` 下会命中本 Plan 自身对死链路径的引用,属正常) +6. **确认文档里的错误码与代码一致**: + `grep -rn 'new ErrorResponse("' backend/src/main` 的 4 个错误码, + 与 `AGENTS.md` §7 表格逐条对得上 +7. **确认没有引入 `TC-` 编号**:`grep -rn "TC-" backend/src/test/` → 无输出 + +--- + +## 13. 风险与回滚 + +* **风险点 1:类型化后默认值与 YAML 不一致。** + 缓解:`AuthConfig` 各字段默认值 **写死当前 YAML 的值**; + 用例 2 会断言实际透出的值,任何一边改了另一边没跟上都会红。 + +* **风险点 2:`ObjectMapper` 投影改变了数值类型。** + 例:`expirationMs` 若声明成 `int` 而非 `long`,大数会溢出; + `minMinutes` 若声明成 `String`,JSON 里会变成 `"30"`。 + 缓解:用例 2 用 `((Number) x).intValue()` 取值再断言, + 既能挡住类型漂移,又不受 Integer/Long 装箱差异影响。 + +* **风险点 3:投影把 `appointment` 子树也洗了一遍。** + `appointment` 本来就是 `Map`,Jackson 往返后值类型可能从 + `Integer` 变 `Integer`、从 `String` 变 `String`(不变), + 但理论上可能出现 `LinkedHashMap` → `LinkedHashMap` 的键序变化。 + 缓解:现有用例 `should_expose_yaml_config_for_each_rule` 断言 + `config.appointment.slot.minMinutes == 30`,它必须继续通过; + 若它变红,说明投影方式选错了 —— **此时应改实现,不是改断言**。 + +* **风险点 4:`publicEndpoints` 变数组属于"对外可见的行为变更"。** + 下游若已按 `{"0":...}` 消费,改完会坏。 + 但 `{"0":...}` 从来不是任何文档承诺过的形状(`api.yaml` 只说 `config: {type: object}`), + 且当前没有任何消费方依赖这个形状(已核实:`frontend/src` 无引用; + `e2e/tests/qa/app.spec.ts` 的 TC-004 只断言该接口 HTTP 200,不读 `config`)。 + 结论:**属于修 bug,不是破坏兼容**。 + +* **回滚方案**: + 生产代码改动集中在 2 个文件,`git checkout` 这 2 个文件即可完全回滚; + 测试是新增 2 例,删除即可;文档改动可单独回滚。 + 全程无 DDL、无数据迁移、无配置中心变更,**回滚零副作用**。 + +--- + +## 14. 实施后需更新的 design 文档 + +见 §11.3(`docs/designs/topic/businessrule.md` 已列入本轮修改清单)。 + +--- + +## 15. 变更记录(可选) + +| 版本 | 日期 | 变更内容 | +| ---- | ---------- | -------- | +| v1.0 | 2026-11-06 | 初始版本 | diff --git a/example-project/docs/plans/20261116-iteration1-feature-skeletons.md b/example-project/docs/plans/20261116-iteration1-feature-skeletons.md new file mode 100644 index 0000000..ac5266b --- /dev/null +++ b/example-project/docs/plans/20261116-iteration1-feature-skeletons.md @@ -0,0 +1,58 @@ +# iteration1 需求样例骨架 + +>日期: 2026-11-16 +> +>关联需求:docs/features/iteration1/ +> +>设计 design:本轮仅需求骨架,不改 designs/ +> +>**plan一旦定稿就不修改。** 同一资源的二次改造新建 `YYYY-MM-DD-{slug}.md`,不修改原计划文件 + +## 1. 文档说明 + +### 1.1 背景 + +- 将 `ai4se-sow-estimate-skill/examples` 中的「咨询师预约平台」PRD 样例迁入 example-project,作为 harness 管理下的标准需求样例。 +- 旧 `docs/features/{auth,appointment,admin}.md` 为简化版,与新样例重叠,本轮删除。 +- 原型将使用 Element Plus 与前端工程同构;本轮只落需求骨架,原型下一轮。 + +### 1.2 目标 + +- 在 `docs/features/iteration1/` 建立 9 份特性 spec 骨架 + 迭代 README。 +- 每份 spec 覆盖:背景/目标/范围、功能概述、角色、主流程要点、关键业务对象、REQ 追溯、待补章节标记。 +- 同步 `AGENTS.md` 文档树引用。 + +### 1.3 技术边界 + +- 不改 backend / frontend 代码。 +- 不写完整字段表、业务规则细项、验收 Given-When-Then(标 TODO)。 +- 不生成 Element Plus 原型 HTML(目录预留)。 + +## 2. 特性拆分 + +| Spec | 源 REQ / 章节 | 说明 | +|---|---|---| +| account.md | §6.1 + REQ-006 | 账号体系与个人中心 | +| consultant-discovery.md | REQ-001、002 | 检索与咨询师主页 | +| booking.md | REQ-003、004、005 | 下单支付、订单、评价 | +| consultant-onboarding.md | REQ-007、008 | 入驻与档案 | +| consultant-schedule.md | REQ-009 | 档期管理 | +| consultant-fulfillment.md | REQ-010、012 | 履约与工作台 | +| settlement.md | REQ-011 | 收入结算 | +| admin-ops.md | REQ-013~017 | 管理端运营治理 | +| platform-capability.md | §6.2~6.6 | 通知/支付/性能/安全/审计 | + +## 3. 任务拆分 + +1. 删除旧 features 三文件。 +2. 创建 `iteration1/README.md`(索引 + 里程碑 + 原型约定)。 +3. 创建 9 份骨架 spec。 +4. 预留 `iteration1/prototypes/` 说明。 +5. 同步 `AGENTS.md` 与相关 skill 示例路径。 + +## 4. 验收 + +- [x] `docs/features/` 下仅保留 `_template.md` 与 `iteration1/` +- [x] 9 份 spec 均可从 README 索引跳到 +- [x] 每份 spec 标注骨架状态与待补章节 +- [x] `AGENTS.md` §13 文档树已更新 diff --git a/example-project/docs/plans/20261116-iteration1-prototypes-and-specs.md b/example-project/docs/plans/20261116-iteration1-prototypes-and-specs.md new file mode 100644 index 0000000..7d19cb5 --- /dev/null +++ b/example-project/docs/plans/20261116-iteration1-prototypes-and-specs.md @@ -0,0 +1,36 @@ +# iteration1 原型与特性补全 + +>日期: 2026-11-16 +> +>关联需求:docs/features/iteration1/ +> +>设计 design:本轮不改 designs/ 业务事实;原型仅 UI 表达 +> +>**plan一旦定稿就不修改。** + +## 1. 背景与目标 + +- 上一轮已落 9 份骨架 spec;本轮补全字段表、业务规则、GWT 验收,并落地 Element Plus 静态原型。 +- 原型与前端工程同构:Element Plus + Vue 3(CDN 静态页,便于评审;后续 `frontend/` 可装同库)。 + +## 2. 交付物 + +1. `docs/features/iteration1/prototypes/` 全套页面(入口 + user + consultant + admin) +2. 9 份 spec:状态由骨架 → v0.1,补齐 §5/§7/§12 并挂接 §14 +3. 更新 iteration1 README 待办勾选 + +## 3. 原型页面清单 + +| 角色 | 页面 | +|---|---| +| 入口 | index.html | +| 用户 | login, index, search, consultant-detail, booking, my-orders, order-detail, profile | +| 咨询师 | index, application, profile, schedule, orders, settlements | +| 管理 | index, applications, categories, users, orders, reports | + +## 4. 验收 + +- [x] 浏览器直接打开入口可跳转三端各页 +- [x] 页面使用 Element Plus 组件(按钮/表单/表格/标签/步骤条等) +- [x] 每份 spec §14 路径可对应到真实 HTML +- [x] 每份 spec 不再标「骨架」,含完整字段表与 GWT 验收 diff --git a/example-project/docs/plans/20261116-iteration1-prototypes-vite.md b/example-project/docs/plans/20261116-iteration1-prototypes-vite.md new file mode 100644 index 0000000..1b1134a --- /dev/null +++ b/example-project/docs/plans/20261116-iteration1-prototypes-vite.md @@ -0,0 +1,24 @@ +# iteration1 原型改为独立 Vite 工程 + +>日期: 2026-11-16 +> +>关联需求:docs/features/iteration1/ +> +>**plan一旦定稿就不修改。** + +## 1. 背景与目标 + +- 将 CDN 静态多页原型改为独立 Vite + Vue 3 + Element Plus demo。 +- 不并入 `example-project/frontend/`。 + +## 2. 交付 + +- `docs/features/iteration1/prototypes/` 成为可 `npm run dev` 的工程(端口 5174)。 +- 删除 CDN HTML、`_gen.py`、旧 `assets/`。 +- Spec §14 改为路由路径。 + +## 3. 验收 + +- [x] `npm install && npm run build` 通过 +- [x] 无 `unpkg.com` / `_gen.py` 残留 +- [x] README / AGENTS / §14 已同步 diff --git a/example-project/docs/plans/_template.md b/example-project/docs/plans/_template.md new file mode 100644 index 0000000..a7e8ba0 --- /dev/null +++ b/example-project/docs/plans/_template.md @@ -0,0 +1,438 @@ +# {方案标题} + +>日期: YYYY-MM-DD +> +>关联需求:docs/features/{file}.md +> +>设计 design:docs/design/topics/{资源}-{操作}.md(实施后会写到原design文件) +> +> +> +>**plan一旦定稿就不修改。** 同一资源的二次改造新建 `YYYY-MM-DD-{slug}.md`,不修改原计划文件 + + + +> TODO:生成计划文档内容较长,执行计划时可以配合步骤进度文件实时落地执行进度 + +## 1. 文档说明 + +### 1.1 背景 + +- 业务 / 技术动机 +- 关联的 features 或 issue +- 关联的 design +- 关键决策点(讨论后定义的方向、放弃的备选方案等) + +### 1.2 目标 + +- 实现目标: +- 技术边界: + +------ + +## 2. 领域模型(PlantUML) + +```plantuml +@startuml +' 在此定义实体、属性、关系 + +entity User { + +id: string + +name: string +} + +entity Order { + +id: string + +userId: string +} + +User ||--o{ Order : places +@enduml +``` + +--- + +## 3. 数据库设计(SQL DDL) + +```sql +-- 在此定义表结构(必须可执行) + +CREATE TABLE user ( + id VARCHAR(64) PRIMARY KEY, + name VARCHAR(255) NOT NULL +); + +CREATE TABLE `order` ( + id VARCHAR(64) PRIMARY KEY, + user_id VARCHAR(64) NOT NULL +); +``` + +--- + +## 4. API 设计(OpenAPI) + +```yaml +openapi: 3.0.0 +info: + title: XXX API + version: 1.0.0 + +paths: + /example: + post: + summary: 示例接口 + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + field: + type: string + responses: + '200': + description: 成功响应 +``` + +--- + +## 5. 时序图(PlantUML) + +```plantuml +@startuml +actor Client +participant API +participant Service +participant DB + +Client -> API : 请求 +API -> Service : 处理 +Service -> DB : 操作 +DB --> Service : 返回 +Service --> API : 返回 +API --> Client : 响应 +@enduml +``` + +--- + +## 6. 专题设计(Markdown) + +### 6.1 权限设计 + +* (鉴权方式,如 JWT / Session) +* (权限模型,如 RBAC / ABAC) + +### 6.2 并发控制 + +* (乐观锁 / 悲观锁) +* (幂等设计) + +### 6.3 事务设计 + +* (单体事务 / 分布式事务) +* (一致性策略) + +### 6.4 异常处理 + +* (错误码规范) +* (统一返回结构) + +### 6.5 性能设计 + +* (缓存策略) +* (索引设计原则) + +### 6.6 扩展性设计 + +* (服务拆分) +* (事件驱动 / 消息队列) + +--- + +## 7. 一致性约束(必须遵守) + +* 领域模型 ↔ 数据库字段必须一致 +* 数据库 ↔ API 字段必须一致 +* 枚举值必须统一定义 +* 命名规范统一(如:API camelCase,DB snake_case) + +------ + +## 8. 单元测试设计 + +### 8.1 测试范围 + +* 被测单元粒度:(单个类 / 单个方法) +* 依赖处理:(Mock / Stub / Fake / Spy 的使用边界) +* 测试隔离:(独立、无副作用、可并行) + +### 8.2 测试策略 + +* 用例组织:(AAA 模式 Arrange-Act-Assert / Given-When-Then) +* 设计原则:(FIRST:Fast / Independent / Repeatable / Self-Validating / Timely) +* 测试框架:(JUnit 5 / Mockito / AssertJ) + +### 8.3 用例覆盖场景 + +每个被测单元的用例需覆盖以下场景: + +- [ ] 正常场景:合法输入,验证正确输出 +- [ ] 边界场景:最大/最小值、临界值 +- [ ] 异常场景:非法输入、越界、抛出预期异常 +- [ ] 特殊值:null、0、空字符串、空集合 +- [ ] 分支覆盖:每个 if/else、switch 分支 +- [ ] 状态机:状态流转与非法跳转 +- [ ] 并发幂等:竞态、重复调用 +- [ ] 一致性约束:领域模型↔数据库字段、枚举值校验(关联第 7 节) + +### 8.4 测试质量 + +* 命名规范:(should_xxx_when_yyy / given_when_then) +* 断言规范:(单一断言焦点 / 精准断言 / AssertJ) +* 数据构造:(TestDataBuilder / Object Mother) +* 覆盖率目标:(行覆盖 / 分支覆盖 阈值,如 ≥ 80%) +* 覆盖率排除:(DTO / 配置类 / generated code) + +### 8.5 用例清单 + +| 被测单元 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :------: | :------: | :------: | :------: | :------: | +| | | | | | + +------ + +## 9. API 集成测试设计 + +### 9.1 测试范围 + +* 切片类型:(Controller 切片 / Repository 切片 / 全链路集成) +* 真实加载组件:(Controller / Service / Repository / ...) +* Mock 边界:(外部服务 / 第三方接口 / 消息队列 / 下游 RPC) + +### 9.2 测试环境 + +* 数据库:(H2 内存库 / Testcontainers MySQL) +* 中间件:(Redis / MQ 依赖方案) +* 下游服务:(WireMock / MockServer) +* 迁移脚本:是否执行真实 Flyway 脚本(是 / 否) + +### 9.3 用例覆盖场景 + +- [ ] 契约校验:状态码、请求/响应字段、错误返回结构 +- [ ] 鉴权场景:无 token / 失效 token / 越权角色 +- [ ] 业务闭环:完整业务流程串联 +- [ ] 数据一致性:写入后查询验证、跨表对齐 +- [ ] 并发幂等:重复请求、并发写入 +- [ ] 下游异常:超时 / 失败 / 降级 + +### 9.4 测试数据 + +* 数据准备:(@Sql / @BeforeEach / TestDataBuilder) +* 隔离策略:(事务回滚 / 清表) +* 断言规范:(JSONPath / AssertJ) + +### 9.5 用例清单 + +| 接口 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :--: | :------: | :------: | :------: | :------: | +| | | | | | + +--- + +## 10. E2E 测试设计 + +### 10.1 测试范围 + +* 核心业务闭环:(列出 P0 链路,如 下单→支付→发货) +* 覆盖边界:(端到端全链路,不 Mock 内部组件) +* 数量约束:(核心链路 N 条) + +### 10.2 测试环境 + +* 部署方式:(Docker Compose / Testcontainers 全套) +* 依赖服务:(DB / Redis / MQ / 下游) +* 测试账号 / 种子数据:(可重入 / 可自清理) +* 外部第三方:(沙箱 / Mock,注明) + +### 10.3 用例覆盖场景 + +- [ ] 核心业务 user journey:完整业务闭环 +- [ ] 状态流转:状态机端到端跳转 +- [ ] 数据落库验证:接口成功后查 DB 校验 +- [ ] 异步链路:消息发送→消费→副作用(显式等待) +- [ ] 跨服务联动:服务间调用、最终一致性 +- [ ] 前端交互(可选):浏览器驱动 E2E + +### 10.4 稳定性与诊断 + +* 等待策略:(显式等待 / 禁止硬等待) +* Flaky 处理:(重试策略 + 记录) +* 失败诊断产物:(截图 / 录屏 / HAR / 日志) + +### 10.5 执行策略 + +* 运行时机:(夜跑 / 发版前 / 手动触发) +* 并行化:(是 / 否) +* 环境治理:(专用 E2E 环境 / 数据重置) + +### 10.6 用例清单 + +| 链路名称 | 覆盖步骤 | 验证点 | 关联章节 | +| :------: | :------: | :----: | :------: | +| | | | | + +------ + +## 11. 修改清单 + +### 11.1 代码修改 + +#### 11.1.1 修改{模块/资源} + +**修改** `src/main/java/.../File.java` + +- 改动点1 +- 改动点2 +- ... + +源代码(原功能概述): + +``` +涉及修改的源代码内容 +``` + +变动后的代码(新功能概述) + +``` +新代码内容 +``` + + + +#### 11.1.2 新增{模块/资源} + +- 用途与职责 +- 关键方法签名 + + + +#### 11.1.3 删除{模块/资源} + +- 用途与职责 +- 删除原因 +- 删除影响 + +#### ... + + + +#### 11.1.x 关键文件速查 + +| 操作 | 文件 | 备注 | +| :--: | :----------------------------: | :--: | +| 新增 | `src/main/java/.../FIlEA.java` | | +| 新增 | `src/main/java/.../FIlEB.java` | | +| ... | `...` | | +| 修改 | `src/main/java/.../FIlEC.java` | | +| 修改 | `src/main/java/.../FIlED.java` | | +| ... | `...` | | +| 删除 | `src/main/java/.../FIlEE.java` | | +| 删除 | `src/main/java/.../FIlEF.java` | | +| ... | `...` | | + +### 11.2 接口变更 + +| 路径 | 方法 | 变更类型 | 说明 | | +| :---------: | :--: | :------: | :--: | :--: | +| `/api/xxx` | POST | 新增 | xxxx | | +| `/api/xxx1` | GET | 修改 | xxxx | | + + + +### 11.3 数据库变更 + +- FLyway 脚本:`V{N}__{desc}.sql` + +- + +- 影响表: + + - `table_b`(新建) + + - 原因:xxxx + + - 影响:xxxx + + - sql脚本: + + ```sql + 对应sql脚本 + ``` + + - `tabel_a`(加字段 `xxx`) + + - 原因:xxxx + + - 影响:xxxx + + - sql脚本: + + ```sql + 对应sql脚本 + ``` + + - `table_b`(删字段 `xxx`) + + - 原因:xxxx + + - 影响:xxxx + + - sql脚本: + + ```sql + 对应sql脚本 + ``` + + + +- 数据迁移: + + - 迁移原因:xxxx + - 迁移方案:对应``V{N}__{desc}.sql` + - 注意事项:xxx + - 回滚方案:xxx + +------ + +## 12. 验证步骤 + +1. 本地启动后调 `curl ...` 期望返回 ... + +2. 检查数据库 `select ... from ... where ...` + +3. 看日志 grep `xxx` + + ------ + +## 13. 风险与回滚 + +- 风险点:xxxx + +- 回滚方案:Flyway 脚本 `V{N+1}__rollback_xxx.sql`,或代码会退到上一个commit + + ------ + +## 14. 实施后需更新的 design 文档 + +- `docs/design/topics/{主题}.md`(新建/更新) + + ------ + +## 15. 变更记录(可选) + +| 版本 | 日期 | 变更内容 | +| ---- | ---------- | -------- | +| v1.0 | YYYY-MM-DD | 初始版本 | diff --git a/example-project/docs/standards/api-design.md b/example-project/docs/standards/api-design.md new file mode 100644 index 0000000..7b450dd --- /dev/null +++ b/example-project/docs/standards/api-design.md @@ -0,0 +1,93 @@ +# API 规范 + +## 基础 + +- RESTful 风格 +- URL 一律小写连字符(kebab-case) +- 名词使用复数(如 `/users`、`/appointments`) +- API 前缀 `/api/v1/` + +## 请求 + +- GET/DELETE 参数通过 Query String +- POST/PUT 参数通过 JSON Body +- Content-Type: `application/json` +- 认证通过 `Authorization: Bearer ` 请求头 + +## 响应 + +- 成功:直接返回数据体 +- 错误:统一格式 `{errorCode, errorMessage, data}` + +## HTTP 状态码 + +| 状态码 | 含义 | 使用场景 | +|--------|------|----------| +| 200 | 成功 | 正常返回 | +| 400 | 参数错误 | 参数校验失败 / 业务参数错误 | +| 401 | 未授权 | Token 缺失 / 无效 / 过期 | +| 403 | 无权限 | 非管理员访问 /admin | +| 404 | 不存在 | 资源 ID 不存在 | +| 409 | 业务冲突 | 重复预约 / 状态冲突 | +| 500 | 服务器错误 | 未捕获异常 | + +## 分页 + +- 入参:`page`(从 1 开始)、`pageSize`(默认 20) +- 出参:`{records, total, page, pageSize}` + +--- + +## 前端 API 调用规范 + +### Service 层封装 + +每个领域对应一个 service 文件,统一通过 Axios 实例调用: + +```typescript +// src/services/appointmentService.ts +import api from '@/utils/axios' + +export const appointmentService = { + list: () => api.get('/appointments'), + getById: (id: string) => api.get(`/appointments/${id}`), + create: (data: CreateAppointmentDto) => api.post('/appointments', data), + cancel: (id: string, reason?: string) => api.put(`/appointments/${id}/cancel`, { reason }), +} +``` + +### Axios 实例配置 + +```typescript +// src/utils/axios.ts +import axios from 'axios' + +const api = axios.create({ baseURL: '/api/v1' }) + +// 请求拦截器:自动附加 JWT +api.interceptors.request.use(config => { + const token = localStorage.getItem('token') + if (token) config.headers.Authorization = `Bearer ${token}` + return config +}) + +// 响应拦截器:统一错误处理与 401 跳转 +api.interceptors.response.use( + res => res, + error => { + if (error.response?.status === 401) { + localStorage.removeItem('token') + window.location.href = '/login' + } + return Promise.reject(error) + } +) + +export default api +``` + +### 响应处理 + +- 成功响应直接返回 data +- 业务错误(400/409)在调用处 catch 处理,展示错误消息 +- 网络/系统错误(500)由拦截器统一提示 diff --git a/example-project/docs/standards/architecture.md b/example-project/docs/standards/architecture.md new file mode 100644 index 0000000..86dc0a9 --- /dev/null +++ b/example-project/docs/standards/architecture.md @@ -0,0 +1,123 @@ +# 系统架构设计 + +> 本文档描述咨询预约平台的事实架构(as-built)。 + +## 部署形态 + +``` +┌─────────────────────────────────────────────────────────┐ +│ 单机部署 (Monolith) │ +│ ┌──────────┐ ┌──────────────────────────────────┐ │ +│ │ │ │ Spring Boot 3.2 │ │ +│ │ Vite │ /api│ ┌────────────────────────────┐ │ │ +│ │ Dev │─────│ │ adapter/rest │ │ │ +│ │ Server │ │ │ (Controller, 协议转换) │ │ │ +│ │ :5173 │ │ └──────────┬─────────────────┘ │ │ +│ │ │ │ ↓ │ │ +│ │ or │ │ ┌────────────────────────────┐ │ │ +│ │ Nginx │ │ │ application/service │ │ │ +│ │ :80 │ │ │ (用例编排, 事务边界) │ │ │ +│ └──────────┘ │ └──────────┬─────────────────┘ │ │ +│ │ ↓ │ │ +│ │ ┌────────────────────────────┐ │ │ +│ │ │ domain/aggregate │ │ │ +│ │ │ (业务不变量, 状态机) │ │ │ +│ │ └──────────┬─────────────────┘ │ │ +│ │ ↑ │ │ +│ │ ┌──────────┴─────────────────┐ │ │ +│ │ │ infrastructure/ │ │ │ +│ │ │ (DB/外部API/安全/配置) │ │ │ +│ │ └────────────────────────────┘ │ │ +│ │ │ │ │ +│ │ ↓ │ │ +│ │ ┌────────────┐ │ │ +│ │ │ MySQL │ │ │ +│ │ │ :3306 │ │ │ +│ │ └────────────┘ │ │ +│ └──────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────┘ +``` + +## 通信方式 + +| 端 | 目标 | 协议 | 说明 | +|----|------|------|------| +| 浏览器 → Vite Dev Server | 前端静态资源 | HTTP | 开发模式,Vite 热更新 | +| Vite Dev Server → Spring Boot | 后端 API | HTTP (proxy) | `/api` → `localhost:8080`,由 `vite.config.ts` 配置 | +| Spring Boot → MySQL | 数据库 | JDBC | MyBatis-Plus 连接池,默认 3306 | +| Nginx (生产) → 静态文件 | 前端 | HTTP | 打包后的 dist/ | +| Nginx (生产) → Spring Boot | 后端 API | HTTP | 反向代理 `/api` | + +## 四层依赖方向 + +``` +adapter → application → domain ← infrastructure +``` + +- **adapter**:仅做 HTTP 协议转换与参数校验,不包含业务逻辑 +- **application**:用例编排、事务管理、DTO ↔ Domain 转换(Assembler) +- **domain**:纯 POJO + Lombok,无 Spring 注解,承载业务不变量 +- **infrastructure**:实现 domain 的 Repository 接口 + 安全 + 配置 + +## 前端架构(Vue 3) + +``` +src/ +├── views/ # 页面级组件(按子系统分) +│ ├── user/ # 用户端(dashboard, book, appointments, profile) +│ └── admin/ # 管理端(dashboard, users, consultants, appointments, branches) +├── components/ # 通用 UI 组件 +│ ├── layout/ # 布局组件(AppHeader, AppSidebar, AppFooter) +│ └── common/ # 通用组件(StatCard, BookingCalendar, DataTable) +├── composables/ # 可复用组合式逻辑 +│ ├── useAuth.ts # 登录/注册/登出逻辑 +│ ├── useBooking.ts # 预约流程状态管理 +│ └── usePagination.ts # 分页逻辑 +├── services/ # API 服务层 +│ ├── axios.ts # Axios 实例(拦截器配置) +│ ├── authService.ts # 认证相关 API +│ ├── appointmentService.ts # 预约相关 API +│ └── consultantService.ts # 咨询师相关 API +├── stores/ # Pinia 全局状态 +│ ├── authStore.ts # 用户认证状态 +│ └── bookingStore.ts # 预约流程临时状态 +├── router/ # Vue Router 配置 +│ └── index.ts # 路由定义 + 守卫 +├── styles/ # 全局样式 +│ └── variables.css # CSS 变量 +└── types/ # TypeScript 类型定义 + └── index.ts # 接口 DTO 类型 +``` + +## 技术栈 + +| 组件 | 技术 | 版本 | +|------|------|------| +| JDK | OpenJDK | 17 | +| 框架 | Spring Boot | 3.2.0 | +| ORM | MyBatis-Plus | 3.5.5 | +| DB | MySQL 8.0 / H2 (test) | - | +| Migration | Flyway | (Boot managed) | +| 安全 | Spring Security + JWT (jjwt) | 0.12.3 | +| 前端框架 | Vue 3 + Composition API + TypeScript | - | +| 构建 | Vite | 5.x | +| 状态管理 | Pinia | - | +| 路由 | Vue Router 4 | - | +| 测试 | JUnit 5 + RestAssured | - | + +## 包结构 + +``` +com.consultation +├── ConsultationApplication.java +├── adapter.rest.* # Controller +├── application.assembler.* # Response/Command DTO +├── application.service.* # AppService +├── domain.aggregate.* # 聚合根 +├── domain.repository.* # 仓储接口 +├── domain.service.* # 领域服务 +├── domain.vo.* # 值对象 +├── domain.businessrule.* # 业务规则接口 (Phase 2) +├── domain.datadictionary.* # 数据字典接口 (Phase 3) +└── infrastructure.* # 配置/持久化/安全/规则实现 +``` diff --git a/example-project/docs/standards/business-rule.md b/example-project/docs/standards/business-rule.md new file mode 100644 index 0000000..7974bae --- /dev/null +++ b/example-project/docs/standards/business-rule.md @@ -0,0 +1,65 @@ +# 业务规则规范 + +## 定义方式 + +业务规则通过 `IBusinessRule` 接口定义: + +```java +public interface IBusinessRule { + String getRuleName(); // 唯一规则名 + String getDescription(); // 描述 +} +``` + +## 配置存储 + +- 规则配置存储在 `resources/business-rules/*.yml` 中 +- 命名:`{domain}.yml`(如 `appointment.yml`、`auth.yml`) +- 格式: + +```yaml +appointment: + conflict: + detection: "同一咨询师同一时段不可重复预约" + slot: + minMinutes: 30 + maxMinutes: 120 + intervalMinutes: 60 +``` + +- 加载方式:`application.yml` 通过 `spring.config.import` 显式导入这些 YAML, + 导入后的顶层键(`appointment` / `auth`)作为根级属性绑定到 `BusinessRuleConfig`。 + 漏掉 `spring.config.import` 时 YAML 不会进入 Environment,接口将**静默少返回 `config` 字段**。 + +## 查询 + +- `BusinessRuleProvider` 在启动时加载所有 YAML 规则 +- 通过 `GET /api/v1/business-rules` 公开查询 + +## 配置类型绑定 + +顶层键绑定到 `domain/businessrule/BusinessRuleConfig`: + +| 顶层键 | Java 类型 | 说明 | +|--------|-----------|------| +| `appointment` | `Map` | 目前全是标量子结构,绑 Map 安全 | +| `auth` | `AuthConfig`(有类型嵌套类) | `password` / `token` / `publicEndpoints` 均为强类型 | + +**约束:往 YAML 里加列表前,必须先给对应的配置类加类型。** + +Spring Boot 的 binder 拿到 YAML 里的 **序列** 而目标类型是 `Map` 时, +无法判断该绑成数组还是 Map,会退化成 **以 0/1/2… 为键的 Map**, +最终序列化出 `{"0": "...", "1": "..."}` 这种错误结构(而不是 JSON 数组)。 + +只有 **列表** 这一种形状会被绑坏 —— 纯标量子结构绑 Map 没问题。 +`auth.publicEndpoints` 就是踩过这个坑的地方,现在由 `AuthConfig.publicEndpoints` +(`List`)承接。 + +同时约定: + +- YAML 与 Java 类必须 **同时改**,键结构一一对应 +- 类里的字段默认值写死当前 YAML 的值,避免 YAML 加载失败时接口返回"空壳"配置 + +## 同步 + +新增或修改业务规则后,同步更新 `docs/designs/topic/businessrule.md`。 diff --git a/example-project/docs/standards/data-dictionary.md b/example-project/docs/standards/data-dictionary.md new file mode 100644 index 0000000..d2ee5d5 --- /dev/null +++ b/example-project/docs/standards/data-dictionary.md @@ -0,0 +1,38 @@ +# 数据字典规范 + +## 接口定义 + +所有业务枚举需实现 `Description` 接口: + +```java +public interface Description { + String getCode(); // enum.name(),如 "PENDING" + String getDescription(); // 中文描述,如 "待确认" + default Map getExtraFields() { return Collections.emptyMap(); } +} +``` + +## 注册 + +枚举通过 `DataDictionaryType` 注册为字典类型: + +```java +public interface DataDictionaryType { + Class getClazz(); // 枚举类 + String getDescription(); // 字典类型描述 +} +``` + +系统中实现 `DataDictionaryType` 的枚举统一管理所有字典注册。 + +## 动态查询 + +| 端点 | 说明 | +|------|------| +| `GET /api/v1/data-dictionaries` | 获取所有字典类型列表 | +| `GET /api/v1/data-dictionaries/{type}` | 获取指定字典的条目列表 | + +## docs 同步 + +修改枚举后,运行 `DataDictionaryUtil` 的 `generateMarkdown()` 更新 `docs/designs/topic/data-dict.md`。 +也可以在 AGENTS.md 中约定手动同步。 diff --git a/example-project/docs/standards/db.md b/example-project/docs/standards/db.md new file mode 100644 index 0000000..8d43cce --- /dev/null +++ b/example-project/docs/standards/db.md @@ -0,0 +1,6 @@ +# 数据库规范 + +- 字符集 utf8mb4,排序 utf8mb4_bin,引擎 InnoDB +- 表名/字段小写蛇形,表名单数,主键 VARCHAR(64) UUID +- 公共字段:created_by, created_time, updated_by, updated_time +- Flyway 迁移 V__.sql diff --git a/example-project/docs/standards/error.md b/example-project/docs/standards/error.md new file mode 100644 index 0000000..c595e26 --- /dev/null +++ b/example-project/docs/standards/error.md @@ -0,0 +1,104 @@ +# 错误码规范 + +## 全局异常处理 + +本项目 **没有** 自定义异常类体系。所有异常由 +`infrastructure/config/GlobalExceptionHandler`(`@RestControllerAdvice`)统一转换: + +| 抛出什么 | HTTP | errorCode | 什么时候用 | +|---|---|---|---| +| `IllegalArgumentException` | 400 | `PARAM_ERROR` | 参数不合法、查不到的资源(异常消息即 `errorMessage`) | +| `IllegalStateException` | 409 | `BUSINESS_CONFLICT` | 业务状态冲突(如同一时段被占用) | +| `MethodArgumentNotValidException` | 400 | `VALIDATION_ERROR` | `@Valid` 字段级校验失败(自动抛出,不手写) | +| 其它 `Exception` | 500 | `SYSTEM_ERROR` | 兜底,消息固定为「系统繁忙」 | + +## 写新代码的约定 + +- 参数不合法 / 资源不存在 → 抛 `IllegalArgumentException` +- 业务状态冲突 → 抛 `IllegalStateException` +- 不要裸抛 `RuntimeException`:会落到 500 兜底,业务语义丢失 +- 鉴权失败由 Spring Security 直接返回 401 / 403,不走 `ErrorResponse` 包装 + +## 响应体格式 + +`GlobalExceptionHandler.ErrorResponse` 的字段是 `errorCode` / `errorMessage` / `data` +(**不是** `message`): + +```json +{ + "errorCode": "BUSINESS_CONFLICT", + "errorMessage": "该时段已被占用", + "data": null +} +``` + +## 错误码表 + +全量错误码与"当前实现映射"见 `docs/designs/topic/error-code.md`。 + +--- + +## 前端错误处理 + +### Axios 响应拦截器 + +```typescript +api.interceptors.response.use( + res => res, + error => { + const { status, data } = error.response || {} + + if (status === 401) { + // Token 过期或无效 → 清除登录状态,跳转登录页 + localStorage.removeItem('token') + window.location.href = '/login' + return Promise.reject(error) + } + + if (status === 403) { + // 无权限 → 显示提示 + ElMessage.error('无权访问该资源') + return Promise.reject(error) + } + + if (status === 409) { + // 业务冲突 → 将错误消息透传给调用方显示 + ElMessage.warning(data?.errorMessage || '操作冲突') + return Promise.reject(error) + } + + if (status >= 500) { + ElMessage.error('系统繁忙,请稍后重试') + return Promise.reject(error) + } + + return Promise.reject(error) + } +) +``` + +### 业务调用处处理 + +```typescript +try { + await appointmentService.cancel(id, reason) + ElMessage.success('取消成功') + refreshList() +} catch (err: any) { + // 409 已在拦截器中处理 toast + // 400 错误展示具体提示 + if (err.response?.status === 400) { + ElMessage.warning(err.response.data?.errorMessage || '参数错误') + } +} +``` + +### 错误提示原则 + +| HTTP Status | 用户提示方式 | 说明 | +|-------------|-------------|------| +| 400 | `ElMessage.warning` | 参数错误,具体消息来自后端 | +| 401 | 自动跳转登录页 | Token 失效,静默处理 | +| 403 | `ElMessage.error` | 无权限,阻断操作 | +| 409 | `ElMessage.warning` | 业务冲突,具体消息来自后端 | +| 500 | `ElMessage.error` | 系统繁忙,通用提示 | diff --git a/example-project/docs/standards/layers.md b/example-project/docs/standards/layers.md new file mode 100644 index 0000000..b3c6669 --- /dev/null +++ b/example-project/docs/standards/layers.md @@ -0,0 +1,44 @@ +# 分层架构规范 + +## 四层架构 + +``` +adapter → application → domain ← infrastructure +``` + +## adapter +HTTP Controller 入/出参协议转换、参数基础校验。不含业务逻辑。 + +## application +用例编排、事务边界管理、Command→domain→Response 转换(Assembler)。 + +## domain +核心业务逻辑、Entity/Aggregate/ValueObject、Repository 接口定义。不依赖 infrastructure。 + +## infrastructure +PO + Mapper + Converter + RepositoryImpl + 安全 + 配置。 + +--- + +## 前端(Vue 3)分层 + +``` +view (页面路由) → component (UI 组件) → composable (可复用逻辑) → service (API 调用) + ↓ + store (Pinia 全局状态) +``` + +### view +页面级组件,对应 Vue Router 路由。负责布局与页面组合,不含业务逻辑。 + +### component +通用 UI 组件(表单、表格、卡片等),接收 props、发射 events。 + +### composable +可复用的组合式逻辑(`useAuth`、`useBooking` 等),封装响应式状态与方法。 + +### service +Axios API 调用封装,每个领域一个 service 文件(`authService.ts`、`appointmentService.ts`)。 + +### store(Pinia) +全局状态管理(`authStore`、`bookingStore`),使用 Composition API 风格定义。 diff --git a/example-project/docs/standards/naming.md b/example-project/docs/standards/naming.md new file mode 100644 index 0000000..bb02d50 --- /dev/null +++ b/example-project/docs/standards/naming.md @@ -0,0 +1,37 @@ +# 命名规范 + +## 后端 + +| 类型 | 约定 | 示例 | +|------|------|------| +| Controller | `XxxController` | `AppointmentController` | +| Service | `XxxService` | `AppointmentService` | +| Repository 接口 | `XxxRepository` | `AppointmentRepository` | +| Repository 实现 | `XxxRepositoryImpl` | `AppointmentRepositoryImpl` | +| Mapper | `XxxMapper` | `AppointmentMapper` | +| PO | `XxxPO` | `AppointmentPO` | +| Assembler | `XxxAssembler` | `AppointmentAssembler` | +| Converter | `XxxConverter` | `AppointmentConverter` | + +## 前端 + +| 类型 | 约定 | 示例 | +|------|------|------| +| 组件文件 | PascalCase `.vue` | `BookingWizard.vue` | +| 视图文件 | PascalCase `.vue` | `UserDashboard.vue` | +| Service 文件 | camelCase `.ts` | `appointmentService.ts` | +| Store 文件 | camelCase `.ts` | `authStore.ts` | +| Composable | `useXxx` `.ts` | `useBooking.ts` | +| 变量/方法 | camelCase | `currentUser`, `fetchAppointments()` | +| 目录名 | kebab-case | `user-dashboard/` | +| 路由路径 | kebab-case | `/user/dashboard` | +| 组件名(多词) | PascalCase | `` | +| Props 定义 | camelCase | `:userName="..."` | +| Events | kebab-case | `@update-profile` | + +## 数据库 + +- 小写蛇形,单数表名:`appointment`、`consultant` +- 字段小写蛇形:`appointment_date`、`start_time` +- 唯一索引前缀 `uk_`:`uk_appointment_slot` +- 普通索引前缀 `idx_`:`idx_user_id` diff --git a/example-project/docs/standards/security.md b/example-project/docs/standards/security.md new file mode 100644 index 0000000..0e6c067 --- /dev/null +++ b/example-project/docs/standards/security.md @@ -0,0 +1,61 @@ +# 安全规范 + +## 后端 + +- 密码 BCrypt 加密,至少 8 位含字母+数字 +- JWT HMAC-SHA256,24h 有效期,载荷含 userId/email/role +- 无状态鉴权,Token 传 `Authorization: Bearer ` +- 公开端点:`/auth/**`, `/home/**`, `GET /consultants` +- 管理端点:`/admin/**` 需 `ROLE_ADMIN` + +## 前端 + +### Token 存储 + +```typescript +// 登录成功后 +localStorage.setItem('token', response.token) +localStorage.setItem('user', JSON.stringify(response.user)) +``` + +- Token 存入 `localStorage`,JWT 不涉及 XSS 时相对安全 +- 用户信息同步存入 Pinia store:`authStore.setUser(user)` + +### Axios 请求拦截器 + +```typescript +api.interceptors.request.use(config => { + const token = localStorage.getItem('token') + if (token) config.headers.Authorization = `Bearer ${token}` + return config +}) +``` + +### 路由守卫 + +```typescript +// src/router/index.ts +router.beforeEach((to, from, next) => { + const token = localStorage.getItem('token') + const user = JSON.parse(localStorage.getItem('user') || 'null') + + if (to.meta.requiresAuth && !token) return next('/login') + if (to.meta.requiresAdmin && user?.role !== 'ROLE_ADMIN') return next('/') + next() +}) +``` + +### 登出 + +```typescript +localStorage.removeItem('token') +localStorage.removeItem('user') +authStore.clear() +router.push('/login') +``` + +### 安全注意事项 + +- 不在 localStorage 存储敏感信息(如 BCrypt 密码 hash) +- 后端返回的 JWT 不包含密码等敏感字段 +- 前端不校验权限,仅做 UI 显示控制;权限校验由后端 `SecurityConfig` 强制执行 diff --git a/example-project/docs/standards/templates/01-ddd-controller.md b/example-project/docs/standards/templates/01-ddd-controller.md new file mode 100644 index 0000000..0f387bf --- /dev/null +++ b/example-project/docs/standards/templates/01-ddd-controller.md @@ -0,0 +1,58 @@ +# REST Controller(Adapter 层) + +```java +package com.xxx.adapter.rest; + +import com.xxx.application.service.XxxService; +import com.xxx.infrastructure.security.SecurityUtils; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/api/v1/xxx") +@RequiredArgsConstructor +public class XxxController { + + private final XxxService xxxService; + + @GetMapping + public ResponseEntity list() { + return ResponseEntity.ok(xxxService.getMyXxx(SecurityUtils.currentUserId())); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable String id) { + return ResponseEntity.ok(xxxService.getById(id)); + } + + @PostMapping + public ResponseEntity create(@Valid @RequestBody CreateRequest r) { + return ResponseEntity.ok(xxxService.create(SecurityUtils.currentUserId(), r.field1, r.field2)); + } + + @PutMapping("/{id}/action") + public ResponseEntity action(@PathVariable String id, @RequestBody Map body) { + xxxService.action(id, SecurityUtils.currentUserId(), body.getOrDefault("reason", "默认原因")); + return ResponseEntity.ok().build(); + } + + @Data + public static class CreateRequest { + @NotBlank String field1; + String field2; + } +} +``` + +## 要点 + +- Controller 只做协议转换,不包含业务逻辑 +- 使用 `@Valid` 做参数校验,内联 DTO 类 +- 通过 `SecurityUtils.currentUserId()` 获取当前用户 +- 返回 `ResponseEntity` 统一响应格式 diff --git a/example-project/docs/standards/templates/02-ddd-appservice.md b/example-project/docs/standards/templates/02-ddd-appservice.md new file mode 100644 index 0000000..8f37bb9 --- /dev/null +++ b/example-project/docs/standards/templates/02-ddd-appservice.md @@ -0,0 +1,54 @@ +# AppService(Application 层) + +```java +package com.xxx.application.service; + +import com.xxx.application.assembler.XxxAssembler; +import com.xxx.domain.aggregate.Xxx; +import com.xxx.domain.repository.XxxRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +public class XxxService { + + private final XxxRepository xxxRepo; + private final XxxAssembler assembler; + + public XxxAssembler.XxxResponse getById(String id) { + return assembler.toResponse(xxxRepo.findById(id) + .orElseThrow(() -> new IllegalArgumentException("记录不存在"))); + } + + public List getMyXxx(String userId) { + return xxxRepo.findByUserId(userId, 1, 100).stream() + .map(assembler::toResponse).toList(); + } + + @Transactional + public XxxAssembler.XxxResponse create(String userId, String field1, String field2) { + // 1. 校验(通过 repository 或 domain service) + // 2. 构建聚合根 + Xxx xxx = xxxRepo.save(Xxx.builder() + .id(UUID.randomUUID().toString()) + .userId(userId) + .field1(field1) + .field2(field2) + .status(XxxStatus.PENDING) + .build()); + return assembler.toResponse(xxx); + } +} +``` + +## 要点 + +- `@Transactional` 标记在用例方法上,事务边界在 application 层 +- 组合 repository、domain service 完成用例编排 +- 使用 assembler 将 domain 转为 DTO 返回给调用方(controller) +- 异常使用 `IllegalArgumentException`(400)或 `IllegalStateException`(409) diff --git a/example-project/docs/standards/templates/03-ddd-assembler.md b/example-project/docs/standards/templates/03-ddd-assembler.md new file mode 100644 index 0000000..05b3a9c --- /dev/null +++ b/example-project/docs/standards/templates/03-ddd-assembler.md @@ -0,0 +1,40 @@ +# Assembler(Domain → DTO 转换) + +```java +package com.xxx.application.assembler; + +import com.xxx.domain.aggregate.Xxx; +import lombok.Builder; +import lombok.Data; +import org.springframework.stereotype.Component; + +@Component +public class XxxAssembler { + + public XxxResponse toResponse(Xxx xxx) { + if (xxx == null) return null; + return XxxResponse.builder() + .id(xxx.getId()) + .userId(xxx.getUserId()) + .field1(xxx.getField1()) + .field2(xxx.getField2()) + .status(xxx.getStatus().name()) + .build(); + } + + @Data @Builder + public static class XxxResponse { + String id; + String userId; + String field1; + String field2; + String status; + } +} +``` + +## 要点 + +- Assembler 负责 Domain → DTO 的转换,在 Application 层 +- Converter(Infrastructure 层)负责 Domain ⟷ PO 的转换 — 见 `08-ddd-converter.md` +- DTO 使用 `@Data @Builder`,内联为静态类 diff --git a/example-project/docs/standards/templates/04-ddd-aggregate.md b/example-project/docs/standards/templates/04-ddd-aggregate.md new file mode 100644 index 0000000..380ea88 --- /dev/null +++ b/example-project/docs/standards/templates/04-ddd-aggregate.md @@ -0,0 +1,57 @@ +# 聚合根(Domain 层) + +```java +package com.xxx.domain.aggregate; + +import com.xxx.domain.vo.XxxStatus; +import lombok.Builder; +import lombok.Value; +import java.time.LocalDate; + +@Value @Builder +public class Xxx { + String id; + String userId; + String field1; + String field2; + LocalDate date; + XxxStatus status; + String note; + + // 业务守卫方法 + public boolean isOwnedBy(String uid) { return userId.equals(uid); } + + public boolean canCancel() { + return status == XxxStatus.PENDING || status == XxxStatus.CONFIRMED; + } +} +``` + +## 要点 + +- 使用 `@Value @Builder` 实现不可变对象 +- 业务逻辑以守卫方法(guard method)形式封装在聚合根内 +- 不含框架注解,纯 Java POJO +- 枚举实现 `Description` 接口用于数据字典注册(见 `04b-ddd-enum.md`) + +### 示例:带枚举的聚合根 + +```java +@Value @Builder +public class Consultant { + String id; String name; String title; String bio; + String specialties; String avatar; String branchId; + ConsultantStatus status; int sortOrder; + + public enum ConsultantStatus implements com.xxx.domain.datadictionary.Description { + ACTIVE("可预约"), DISABLED("不可预约"); + + private final String description; + ConsultantStatus(String description) { this.description = description; } + @Override public String getCode() { return name(); } + @Override public String getDescription() { return description; } + } + + public boolean isAvailable() { return status == ConsultantStatus.ACTIVE; } +} +``` diff --git a/example-project/docs/standards/templates/05-ddd-domain-service.md b/example-project/docs/standards/templates/05-ddd-domain-service.md new file mode 100644 index 0000000..dc2851d --- /dev/null +++ b/example-project/docs/standards/templates/05-ddd-domain-service.md @@ -0,0 +1,31 @@ +# Domain Service(Domain 层) + +```java +package com.xxx.domain.service; + +import com.xxx.domain.aggregate.Xxx; +import com.xxx.domain.vo.XxxStatus; +import java.util.List; + +public class XxxConflictService { + + /** + * 校验新建记录与已有记录不冲突。 + * 冲突时抛出 IllegalStateException(HTTP 409)。 + */ + public void validateNoConflict(List existing, CheckParam param) { + boolean conflict = existing.stream().anyMatch(a -> + a.getField1().equals(param.field1()) && + a.getStatus() != XxxStatus.CANCELLED); + if (conflict) throw new IllegalStateException("冲突:该条件已存在"); + } + + public record CheckParam(String field1) {} +} +``` + +## 要点 + +- Domain Service 处理跨聚合的业务校验,不在任何一个聚合根内 +- 不依赖 Spring,纯 Java +- 在 AppService 中组合使用 diff --git a/example-project/docs/standards/templates/06-ddd-repository-interface.md b/example-project/docs/standards/templates/06-ddd-repository-interface.md new file mode 100644 index 0000000..e139d1d --- /dev/null +++ b/example-project/docs/standards/templates/06-ddd-repository-interface.md @@ -0,0 +1,26 @@ +# Repository 接口(Domain 层) + +```java +package com.xxx.domain.repository; + +import com.xxx.domain.aggregate.Xxx; +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +public interface XxxRepository { + Optional findById(String id); + List findByUserId(String userId, int page, int pageSize); + List findByField1(String field1); + List findAll(int page, int pageSize); + Xxx save(Xxx xxx); + void update(Xxx xxx); + long count(); +} +``` + +## 要点 + +- 接口定义在 Domain 层,实现放在 Infrastructure 层(依赖反转) +- 方法操作的是 Domain 对象(`Xxx`),而非 PO +- 方法命名贴近业务语言 diff --git a/example-project/docs/standards/templates/07-ddd-repository-impl.md b/example-project/docs/standards/templates/07-ddd-repository-impl.md new file mode 100644 index 0000000..d2c300d --- /dev/null +++ b/example-project/docs/standards/templates/07-ddd-repository-impl.md @@ -0,0 +1,82 @@ +# Repository 实现(Infrastructure 层 — MyBatis-Plus) + +```java +package com.xxx.infrastructure.repositoryimpl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xxx.domain.aggregate.Xxx; +import com.xxx.domain.repository.XxxRepository; +import com.xxx.infrastructure.persistence.converter.XxxConverter; +import com.xxx.infrastructure.persistence.mapper.XxxMapper; +import com.xxx.infrastructure.persistence.po.XxxPO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +@Repository +@RequiredArgsConstructor +public class XxxRepositoryImpl implements XxxRepository { + + private final XxxMapper mapper; + private final XxxConverter converter; + + @Override public Optional findById(String id) { + return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); + } + + @Override + public List findByUserId(String userId, int page, int pageSize) { + return mapper.selectPage(new Page<>(page, pageSize), + new LambdaQueryWrapper() + .eq(XxxPO::getUserId, userId) + .orderByDesc(XxxPO::getCreatedTime)) + .getRecords().stream() + .map(converter::toDomain).toList(); + } + + @Override + public List findByField1(String field1) { + return mapper.selectList(new LambdaQueryWrapper() + .eq(XxxPO::getField1, field1)) + .stream().map(converter::toDomain).toList(); + } + + @Override public List findAll(int page, int pageSize) { + return mapper.selectPage(new Page<>(page, pageSize), null) + .getRecords().stream().map(converter::toDomain).toList(); + } + + @Override + public Xxx save(Xxx xxx) { + XxxPO po = converter.toPO(xxx); + po.setCreatedBy(xxx.getUserId()); + po.setCreatedTime(LocalDateTime.now()); + po.setUpdatedBy(xxx.getUserId()); + po.setUpdatedTime(LocalDateTime.now()); + mapper.insert(po); + return xxx; + } + + @Override + public void update(Xxx xxx) { + XxxPO po = converter.toPO(xxx); + po.setUpdatedTime(LocalDateTime.now()); + mapper.updateById(po); + } + + @Override public long count() { + return mapper.selectCount(null); + } +} +``` + +## 要点 + +- `@Repository` 标记,实现 Domain 层的接口 +- 通过 Converter 在 PO 和 Domain 之间转换 +- 使用 LambdaQueryWrapper 做类型安全的查询 +- 审计字段(createdBy/createdTime/updatedBy/updatedTime)在持久化时设置 diff --git a/example-project/docs/standards/templates/08-ddd-converter.md b/example-project/docs/standards/templates/08-ddd-converter.md new file mode 100644 index 0000000..9301085 --- /dev/null +++ b/example-project/docs/standards/templates/08-ddd-converter.md @@ -0,0 +1,47 @@ +# Converter(Infrastructure 层 — PO ⟷ Domain 转换) + +```java +package com.xxx.infrastructure.persistence.converter; + +import com.xxx.domain.aggregate.Xxx; +import com.xxx.domain.vo.XxxStatus; +import com.xxx.infrastructure.persistence.po.XxxPO; +import org.springframework.stereotype.Component; + +@Component +public class XxxConverter { + + public Xxx toDomain(XxxPO po) { + if (po == null) return null; + return Xxx.builder() + .id(po.getId()) + .userId(po.getUserId()) + .field1(po.getField1()) + .field2(po.getField2()) + .date(po.getDate()) + .status(XxxStatus.valueOf(po.getStatus())) + .note(po.getNote()) + .build(); + } + + public XxxPO toPO(Xxx xxx) { + if (xxx == null) return null; + XxxPO po = new XxxPO(); + po.setId(xxx.getId()); + po.setUserId(xxx.getUserId()); + po.setField1(xxx.getField1()); + po.setField2(xxx.getField2()); + po.setDate(xxx.getDate()); + po.setStatus(xxx.getStatus().name()); + po.setNote(xxx.getNote()); + return po; + } +} +``` + +## 要点 + +- `@Component`,两层双向转换 +- `toDomain` 使用 Domain 的 `@Builder` 构建 +- `toPO` 使用 PO 的 setter(Lombok `@Data`) +- 枚举字段通过 `.name()` / `valueOf()` 与字符串互转 diff --git a/example-project/docs/standards/templates/09-ddd-po-mapper.md b/example-project/docs/standards/templates/09-ddd-po-mapper.md new file mode 100644 index 0000000..844835a --- /dev/null +++ b/example-project/docs/standards/templates/09-ddd-po-mapper.md @@ -0,0 +1,50 @@ +# PO 与 Mapper(Infrastructure 层 — MyBatis-Plus) + +## PO(持久化对象) + +```java +package com.xxx.infrastructure.persistence.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("xxx") +public class XxxPO { + private String id; + private String userId; + private String field1; + private String field2; + private LocalDate date; + private String status; + private String note; + // 审计字段 + private String createdBy; + private LocalDateTime createdTime; + private String updatedBy; + private LocalDateTime updatedTime; +} +``` + +## Mapper + +```java +package com.xxx.infrastructure.persistence.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xxx.infrastructure.persistence.po.XxxPO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface XxxMapper extends BaseMapper {} +``` + +## 要点 + +- PO 使用 `@Data` + `@TableName`,字段与数据库列一一对应 +- 枚举字段存为 `String`(`status`),通过 Converter 与 Domain 枚举互转 +- Mapper 继承 `BaseMapper`,无需手写 SQL +- 主键为 UUID 字符串(`VARCHAR(64)`),由应用层生成 +- 审计字段(createdBy/createdTime/updatedBy/updatedTime)在每个 PO 中定义 diff --git a/example-project/docs/standards/templates/10-global-exception-handler.md b/example-project/docs/standards/templates/10-global-exception-handler.md new file mode 100644 index 0000000..55467b2 --- /dev/null +++ b/example-project/docs/standards/templates/10-global-exception-handler.md @@ -0,0 +1,65 @@ +# 全局异常处理(Infrastructure 层) + +```java +package com.xxx.infrastructure.config; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleBadArg(IllegalArgumentException e) { + return ResponseEntity.badRequest().body(new ErrorResponse("PARAM_ERROR", e.getMessage())); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleConflict(IllegalStateException e) { + return ResponseEntity.status(HttpStatus.CONFLICT) + .body(new ErrorResponse("BUSINESS_CONFLICT", e.getMessage())); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidation(MethodArgumentNotValidException e) { + var msg = e.getBindingResult().getFieldError(); + return ResponseEntity.badRequest().body( + new ErrorResponse("VALIDATION_ERROR", + msg != null ? msg.getDefaultMessage() : "参数错误")); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleOther(Exception e) { + log.error("Unexpected error", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ErrorResponse("SYSTEM_ERROR", "系统繁忙")); + } + + public record ErrorResponse(String errorCode, String errorMessage, Object data) { + public ErrorResponse(String errorCode, String errorMessage) { + this(errorCode, errorMessage, null); + } + } +} +``` + +## 异常 → HTTP 状态码映射 + +| 异常 | HTTP | errorCode | +|------|------|-----------| +| `IllegalArgumentException` | 400 | `PARAM_ERROR` | +| `MethodArgumentNotValidException` | 400 | `VALIDATION_ERROR` | +| `IllegalStateException` | 409 | `BUSINESS_CONFLICT` | +| `Exception`(未预期) | 500 | `SYSTEM_ERROR` | + +## 要点 + +- 业务参数错误用 `IllegalArgumentException`,返回 400 +- 业务冲突用 `IllegalStateException`,返回 409 +- 未预期异常记录日志并返回 500,不暴露内部信息 +- 响应体统一为 `ErrorResponse` 结构 diff --git a/example-project/docs/standards/templates/README.md b/example-project/docs/standards/templates/README.md new file mode 100644 index 0000000..f018828 --- /dev/null +++ b/example-project/docs/standards/templates/README.md @@ -0,0 +1,18 @@ +# Snippet — 常见业务代码模版 + +存放 DDD 四层架构的代码打样,供新功能开发时参考复制。所有模版均来自本项目的实现代码。 + +## 目录 + +| # | 文件 | 层 | 用途 | +|---|------|-----|------| +| 1 | `01-ddd-controller.md` | Adapter | REST Controller 模版 | +| 2 | `02-ddd-appservice.md` | Application | AppService 用例编排模版 | +| 3 | `03-ddd-assembler.md` | Application | Domain → DTO 转换器模版 | +| 4 | `04-ddd-aggregate.md` | Domain | 聚合根模版(含业务守卫方法) | +| 5 | `05-ddd-domain-service.md` | Domain | Domain Service 模版 | +| 6 | `06-ddd-repository-interface.md` | Domain | Repository 接口模版 | +| 7 | `07-ddd-repository-impl.md` | Infrastructure | MyBatis-Plus Repository 实现模版 | +| 8 | `08-ddd-converter.md` | Infrastructure | PO ⟷ Domain 转换器模版 | +| 9 | `09-ddd-po-mapper.md` | Infrastructure | PO 与 Mapper 模版 | +| 10 | `10-global-exception-handler.md` | Infrastructure | 全局异常处理模版 | diff --git a/example-project/docs/standards/test.md b/example-project/docs/standards/test.md new file mode 100644 index 0000000..f608227 --- /dev/null +++ b/example-project/docs/standards/test.md @@ -0,0 +1,149 @@ +# 测试规范 + +## 0. 两类用例:开发自测 vs QA 测试 + +本项目的测试用例分两层,**归属看"谁定义、谁判定",不是"谁敲的代码"**。 + +| 维度 | 开发自测(Dev Self-Test) | QA 测试(QA Test) | +|---|---|---| +| **验证什么** | 代码按 **Plan** 的设计工作 | 系统符合 **需求规格** | +| **用例来源** | Plan(技术方案) | 需求规格 `docs/features/` + 业务规则编号 | +| **谁定义** | 开发本人 | QA(与 PO 对齐业务规则) | +| **谁判定** | 开发本人 | **QA** | +| **什么时候写** | 实现过程中,边写边补 | 实现完成后的验收阶段 | +| **用例编号** | 无编号,用命名表达意图 | `TC-xxx`,与文本用例一一对应 | +| **存放位置** | 源码旁(`*Test.java`、`*.test.ts`) | `docs/` 用例库 + `e2e/tests/qa/` | +| **是不是合并闸门** | 否(自测不通过,开发自己不能提交) | **是**(QA 用例不通过,不能验收、不能合并) | +| **失败意味着** | 代码写错了 | 需求没实现 / 理解有偏差 / 规格有歧义 | +| **谁修** | 开发 | 开发(QA 判定并跟单) | + +### 关键约定 + +1. **QA 用例的自动化实现可以由开发代写**,但用例的 **定义权与判定权归 QA**。 +2. **开发自测不能替代 QA 测试**。开发自测全绿 ≠ 需求被实现。 +3. **QA 用例必须先有文本用例**(`docs/test-cases/e2e-cases/`),再写自动化。反过来做会漏场景。 +4. 发现实现中出现 **需求规格之外** 的行为,是缺陷(除非 PO 明确认可)。 + +--- + +## 1. 用例归属速查 + +| 层 | 类型 | 归属 | 位置 | 框架 | +|---|---|---|---|---| +| Adapter | 集成测试 | 开发自测 | `backend/src/test/**/*Test.java` | SpringBootTest + RestAssured | +| Application | 单元测试 | 开发自测 | `backend/src/test/**/*Test.java` | JUnit 5 + Mockito | +| Domain | 单元测试 | 开发自测 | `backend/src/test/**/*Test.java` | JUnit 5 | +| Infrastructure | 集成测试 | 开发自测 | `backend/src/test/**/*Test.java` | SpringBootTest + MariaDB4j | +| View | E2E 验收 | **QA 测试** | `e2e/tests/qa/` | Playwright | +| — | E2E 自测 | 开发自测 | `e2e/tests/dev/` | Playwright | +| Composable / Store / Component | 单元测试 | 开发自测 | `frontend/src/**/*.test.ts` | Vitest | +| — | 手动用例 | **QA 测试** | `docs/test-cases/manual-cases/` | 人工 | +| — | 冒烟用例 | **QA 测试** | `docs/test-cases/smoking-cases/` | 人工 / 自动化 | +| — | 自测场景索引 | 开发自测 | `docs/test-cases/dev-self-cases/` | 可选文本索引 | + +--- + +## 2. 开发自测规范 + +### 2.1 后端分层测试策略 + +| 层次 | 测试类型 | 关注点 | +|------|----------|--------| +| Adapter | 集成测试 | 请求/响应/状态码/错误码 | +| Application | 单元测试 | 用例编排/事务边界 | +| Domain | 单元测试 | 业务不变量/状态机 | +| Infrastructure | 集成测试 | 持久化/映射正确性 | + +### 2.2 Adapter 层集成测试约定 + +- 基类:`TestBase` 继承 `@SpringBootTest(webEnvironment = RANDOM_PORT)` +- HTTP 客户端:RestAssured(配置端口 + 日志) +- 数据隔离:`@BeforeEach` 重置所有表 +- 认证:使用 `loginAsUser()` / `loginAsAdmin()` 辅助方法获取 Token + +### 2.3 命名 + +- 类名:`{被测Controller}Test`(如 `AuthControllerTest`) +- 方法名:`should_{action}_{expectedResult}`(如 `should_register_and_return_token`) +- 用例名 **不写** `TC-` 编号 —— 编号属于 QA 用例 + +### 2.4 覆盖要求(每个 Controller 测试) + +- 1 个 happy path +- 2 个错误分支 +- 涉及聚合写入的,补 1 个业务冲突分支 + +### 2.5 前端单元测试(Vitest) + +- 测试文件与源码同目录,以 `.test.ts` 结尾 +- Composable 测试:mock service 层,验证响应式状态 +- Store 测试:使用 `setActivePinia(createPinia())` 隔离 store 实例 + +--- + +## 3. QA 测试规范 + +### 3.1 四类 QA 产物 + +| 产物 | 位置 | 说明 | +|---|---|---| +| 文本验收用例 | `docs/test-cases/e2e-cases/test-cases.md` | QA 用例的 **基线**,先写这里 | +| E2E 自动化 | `e2e/tests/qa/*.spec.ts` | 文本用例的自动化实现,编号一一对应 | +| 手动用例 | `docs/test-cases/manual-cases/manual-test-cases.md` | 自动化难覆盖 / 需人工判断 | +| 冒烟用例 | `docs/test-cases/smoking-cases/smoking-test-cases.md` | 发版前 5 分钟跑完的最小集 | +| 开发自测索引 | `docs/test-cases/dev-self-cases/` | 可选;可执行用例仍在源码旁 / `e2e/tests/dev/` | + +### 3.2 编号约定 + +- QA 用例统一编号 `TC-xxx`(文本用例与自动化用例 **共用** 同一编号) +- 业务规则编号(`R-xxx`)与用例编号(`TC-xxx`)是 **映射关系**,不是同一个编号空间 +- 自动化用例的 `test()` 标题里带上 `TC-xxx`,便于双向追溯: + +```ts +test('TC-021 预约成功后出现在预约列表中', async ({ page }) => { + ... +}) +``` + +### 3.3 覆盖要求 + +- 需求规格 §12 的 **每条** 验收标准 → 至少 1 条 QA 用例 +- 每条业务规则(`R-xxx`)→ 至少 1 条 QA 用例 +- 至少覆盖:Happy Path / 参数错误 / 权限不足 / 业务冲突 / 边界 + +### 3.4 可重复执行 + +- 用例之间 **不能有顺序依赖** +- 每个用例自己准备数据、自己清理数据 +- 不依赖真实外部服务的时间点、随机数、当前时间 + +### 3.5 运行 + +```bash +cd e2e +npm run test:qa # 只跑 QA 验收用例(合并闸门) +npm run test:dev # 只跑开发自测用例 +npm test # 全部 +``` + +--- + +## 4. 合并闸门 + +| 闸门 | 要求 | 谁判定 | +|---|---|---| +| 开发自测 | `mvn test` 全绿、`npm run build` 通过、`npm run test:dev` 不阻塞 | 开发 | +| QA 验收 | `npm run test:qa` 全绿 + 文本用例逐条勾选 | QA | + +**QA 闸门未过,不能合并。** 开发自测不过,先修再提。 + +--- + +## 5. 测试环境 + +- 测试使用 `application.yml`(test resources),配置 MariaDB4j +- Flyway 在测试中禁用(`spring.flyway.enabled=false`) +- `@ActiveProfiles("test")` 在 TestBase 中设置 +- 测试使用 `schema.sql` + `data.sql` 初始化数据 +- ResetDbService 在每个 `@BeforeEach` 中 TRUNCATE 全表 +- DB 相关用例必须可重复执行,不依赖执行顺序 diff --git a/example-project/docs/test-cases/README.md b/example-project/docs/test-cases/README.md new file mode 100644 index 0000000..6f40a00 --- /dev/null +++ b/example-project/docs/test-cases/README.md @@ -0,0 +1,13 @@ +# 测试用例(`docs/test-cases/`) + +本目录集中存放 **文本用例基线**(与自动化目录 `e2e/tests/` 分离)。 + +| 子目录 | 归属 | 内容 | +|---|---|---| +| `e2e-cases/` | **QA 测试** | E2E 验收用例文本基线(`TC-xxx`),合并闸门 | +| `manual-cases/` | **QA 测试** | 需人工执行的用例(`TC-Mxx`) | +| `smoking-cases/` | **QA 测试** | 发版前冒烟用例(`TC-Sxx`,≤ 5 分钟) | +| `dev-self-cases/` | **开发自测** | 开发自测场景清单(可选文本索引;实现仍在源码旁 / `e2e/tests/dev/`) | + +> QA 三目录:定义权与判定权归 QA。 +> `dev-self-cases/`:对开发本人负责,**不是**合并闸门。 diff --git a/example-project/docs/test-cases/dev-self-cases/README.md b/example-project/docs/test-cases/dev-self-cases/README.md new file mode 100644 index 0000000..d6830c4 --- /dev/null +++ b/example-project/docs/test-cases/dev-self-cases/README.md @@ -0,0 +1,13 @@ +# 开发自测用例索引(可选) + +> **归属:开发自测。** 本目录用于记录本迭开发自测场景清单(可选文本索引)。 +> +> - 真正的可执行用例放在源码旁(`*Test.java`、`*.test.ts`)与 `e2e/tests/dev/` +> - **不写 `TC-` 编号**(`TC-` 是 QA 用例编号空间) +> - 自测全绿 ≠ 需求已验收 + +## 本迭索引(示例) + +| 场景 | 位置 | 备注 | +|---|---|---| +| (按 Plan 补) | `backend/src/test/...` | Happy Path + 失败分支 | diff --git a/example-project/docs/test-cases/e2e-cases/test-cases.md b/example-project/docs/test-cases/e2e-cases/test-cases.md new file mode 100644 index 0000000..4f28e9c --- /dev/null +++ b/example-project/docs/test-cases/e2e-cases/test-cases.md @@ -0,0 +1,84 @@ +# E2E 测试用例 — 咨询预约平台 + +> **归属:QA 测试。** 本文件是 QA 验收用例的 **文本基线**,由 QA 定义与判定。 +> +> - 自动化实现位于 `e2e/tests/qa/app.spec.ts`,编号与本文件一一对应 +> - 自动化代码可由开发代写,但用例的 **定义权与判定权归 QA** +> - 需求规格的每条验收标准(`docs/features/*/§12`)与每条业务规则(`R-xxx`)都必须有对应用例 +> - **合并闸门**:本文件的用例未全部通过验收,不能合并 + +> **不属于本文件的**:开发自测用例放在源码旁与 `e2e/tests/dev/`,只对开发本人负责,不是验收依据。 + +## 1. 公共页面 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-001 | 首页加载 | 访问 `/` | 页面显示标题"专业咨询服务"、"免费注册"、"立即预约"按钮、版权信息 | +| TC-002 | 登录页渲染 | 访问 `/login` | 显示邮箱/密码输入框、登录按钮、注册链接 | +| TC-003 | 注册页渲染 | 访问 `/register` | 显示姓名/邮箱/手机/密码输入框、注册按钮、登录链接 | +| TC-004 | 公开 API 可用 | GET `/api/v1/data-dictionaries`、`/api/v1/business-rules`、`/api/v1/consultants` | 均返回 200,咨询师列表 ≥ 3 条 | +| TC-005 | 导航跳转 | 首页点击"登录" → 点击"立即注册" | URL 依次变为 `/login` → `/register` | + +## 2. 认证 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-006 | 管理员登录成功 | 填写 admin@test.com / password → 提交 | 跳转到 `/admin/dashboard`,显示"管理仪表盘" | +| TC-007 | 错误密码提示 | 填写 admin@test.com / wrongpassword → 提交 | 显示错误提示 | +| TC-008 | 注册新用户 | 填写姓名/邮箱/手机/密码 → 提交 | 跳转到 `/user/dashboard`,显示用户姓名 | +| TC-009 | 重复邮箱注册 | 使用已注册邮箱再次注册 | 显示错误提示 | +| TC-010 | 新用户登录 | 使用刚注册的账号登录 | 跳转到 `/user/dashboard`,显示"用户中心" | + +## 3. 用户流程 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-011 | 用户仪表盘 | 登录后访问 `/user/dashboard` | 显示"总预约"、"待确认"、"已完成"统计卡片 | +| TC-012 | 浏览咨询师 | 访问 `/user/book` | 显示张医生、李律师、王教练三条记录 | +| TC-013 | 预约 + 取消 | 选咨询师 → 选日期 → 选时间 → 填备注 → 提交 → 取消 | 预约成功跳转预约列表 → 取消后显示"已取消"状态 | +| TC-014 | 编辑个人信息 | 访问 `/user/profile` → 修改姓名 → 保存 | 弹出"保存成功"提示 | + +## 4. 管理员流程 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-015 | 仪表盘统计 | 管理员登录 → 访问 `/admin/dashboard` | 显示用户数 / 咨询师 / 总预约 / 待确认 / 网点五个卡片 | +| TC-016 | 用户管理 | 访问 `/admin/users` | 表格显示 admin@test.com、管理员;可点击禁用/启用 | +| TC-017 | 咨询师管理 | 侧栏点击"咨询师管理" | 表格显示张医生、李律师、王教练 | +| TC-018 | 预约管理 | 侧栏点击"预约管理" | 页面标题为"预约管理" | +| TC-019 | 网点 CRUD | 新增网点(名称/地址/电话) → 保存 → 编辑 → 保存 → 删除 | 表格显示新建条目 → 修改后名称更新 → 删除后消失 | + +## 5. 边界情况 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-020 | 未登录访问管理页 | 清除 localStorage → 访问 `/admin/dashboard` | 跳转到 `/login` | +| TC-021 | 未登录访问用户页 | 清除 localStorage → 访问 `/user/dashboard` | 跳转到 `/login` | +| TC-022 | 首页 CTA 可见 | 未登录状态下访问 `/` | "免费注册"按钮可见 | + +## 测试数据 + +| 角色 | 邮箱 | 密码 | +|---|---|---| +| 管理员 | admin@test.com | password | +| 新注册用户 | (动态生成) | Test123456 | + +种子数据:3 位咨询师(张医生、李律师、王教练)、3 个网点(朝阳、海淀、浦东)。 + +## 用例 ↔ 自动化对照 + +| 文本用例 | 自动化用例(`e2e/tests/qa/app.spec.ts`) | 状态 | +|---|---|---| +| TC-001 ~ TC-022 | 同名 `test('TC-xxx ...')` | 22 / 22 已实现 | + +新增文本用例时,同步在自动化里加同名 `TC-xxx` 用例,并把状态改为"待实现"。 + +## 与开发自测的边界 + +| | 本文件(QA 测试) | 开发自测 | +|---|---|---| +| 位置 | `docs/test-cases/e2e-cases/` + `e2e/tests/qa/` | `backend/src/test/`、`frontend/src/**/*.test.ts`、`e2e/tests/dev/` | +| 依据 | 需求规格 | Plan | +| 闸门 | **是** | 否 | + +`e2e/tests/dev/` 下的用例(视觉冒烟等)是开发自测,**不能** 作为本文件的验收依据。 diff --git a/example-project/docs/test-cases/manual-cases/manual-test-cases.md b/example-project/docs/test-cases/manual-cases/manual-test-cases.md new file mode 100644 index 0000000..f09fe44 --- /dev/null +++ b/example-project/docs/test-cases/manual-cases/manual-test-cases.md @@ -0,0 +1,14 @@ +# 手动执行用例 — 咨询预约平台 + +> **归属:QA 测试。** 自动化难以覆盖、或需要人工主观判断的场景写在这里。 +> 由 QA 定义与判定,是 **合并闸门** 的一部分。 + +## 用例清单 + +| # | 用例 | 前置条件 | 步骤 | 预期 | 执行人 | +|---|---|---|---|---|---| +| TC-M01 | 后台禁用用户后其登录态失效 | 存在普通用户 `user@test.com` | 管理员禁用该用户 → 用户端刷新页面 | 用户被强制登出,跳转登录页 | | +| TC-M02 | 同一时段重复预约的提示文案 | 已有 咨询师A + 某时段 的预约 | 用另一账号预约同一时段 | 提示"该时间段已被占用",errorCode = `APPOINTMENT_CONFLICT` | | +| TC-M03 | 移动端视口下布局不塌陷 | 已登录 | 视口宽度调至 375px | 首页与预约页排版正常,无横向滚动条 | | +| TC-M04 | 弱网下的加载态 | 浏览器限速 Slow 3G | 打开预约列表 | 显示加载态骨架,不出现空白页 | | +| TC-M05 | 刷新后表单草稿保留 | — | 在个人资料页填写昵称但不保存 → 刷新 | 昵称仍在输入框中 | | diff --git a/example-project/docs/test-cases/smoking-cases/smoking-test-cases.md b/example-project/docs/test-cases/smoking-cases/smoking-test-cases.md new file mode 100644 index 0000000..4c02d75 --- /dev/null +++ b/example-project/docs/test-cases/smoking-cases/smoking-test-cases.md @@ -0,0 +1,22 @@ +# 冒烟用例 — 咨询预约平台 + +> **归属:QA 测试。** 发版前必须全绿的一组最小用例集。 +> 目标:**5 分钟内跑完**,用于快速判断"能不能发"。 +> 自动化实现位于 `e2e/tests/qa/app.spec.ts`,本文件是它的精简视图。 + +## 用例清单 + +| # | 用例 | 冒烟点 | 预期 | 自动化 | +|---|---|---|---|---| +| TC-S01 | 服务启动 | 后端可启动、前端可加载 | 无启动错误,首页 200 | `qa/app.spec.ts` → Public Pages | +| TC-S02 | 登录 | 管理员正确凭据登录 | 跳转到 `/admin/dashboard` | `qa/app.spec.ts` → Auth | +| TC-S03 | 用户注册 | 全新邮箱注册 | 跳转到 `/user/dashboard`,显示用户名 | `qa/app.spec.ts` → Auth | +| TC-S04 | 核心预约链路 | 选咨询师 → 选时间 → 提交 | 预约成功,出现在预约列表 | `qa/app.spec.ts` → User Flows | +| TC-S05 | 管理端可读 | 管理员查看用户/预约/网点列表 | 三个列表均正常渲染 | `qa/app.spec.ts` → Admin Flows | +| TC-S06 | 数据库连通 | 写入后可读回 | 无连接错误,数据一致 | `qa/app.spec.ts` | + +## 执行 + +```bash +cd e2e && npm run test:qa +``` diff --git a/example-project/e2e-run.sh b/example-project/e2e-run.sh new file mode 100755 index 0000000..c5c73f7 --- /dev/null +++ b/example-project/e2e-run.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")" && pwd)" +BACKEND_DIR="$ROOT/backend" +FRONTEND_DIR="$ROOT/frontend" +E2E_DIR="$ROOT/e2e" +BACKEND_PORT=8080 +FRONTEND_PORT=5173 +BACKEND_PID="" +FRONTEND_PID="" + +cleanup() { + echo "" + echo "🛑 Cleaning up..." + [ -n "$FRONTEND_PID" ] && kill "$FRONTEND_PID" 2>/dev/null && echo " Frontend (PID $FRONTEND_PID) stopped" + [ -n "$BACKEND_PID" ] && kill "$BACKEND_PID" 2>/dev/null && echo " Backend (PID $BACKEND_PID) stopped" + wait 2>/dev/null + echo "✅ Cleanup done" +} + +trap cleanup EXIT INT TERM + +# ── Start backend ── +echo "🚀 Starting backend (port $BACKEND_PORT)..." +cd "$BACKEND_DIR" +mvn spring-boot:run -q > /tmp/e2e-backend.log 2>&1 & +BACKEND_PID=$! +echo " Backend PID: $BACKEND_PID" + +echo " Waiting for backend..." +for i in $(seq 1 60); do + if curl -s -o /dev/null -w "%{http_code}" "http://localhost:$BACKEND_PORT/api/v1/home/info" 2>/dev/null | grep -q 200; then + echo " Backend ready after ${i}s" + break + fi + if [ "$i" -eq 60 ]; then + echo "❌ Backend failed to start within 60s" + tail -20 /tmp/e2e-backend.log + exit 1 + fi + sleep 1 +done + +# ── Start frontend ── +echo "🚀 Starting frontend (port $FRONTEND_PORT)..." +cd "$FRONTEND_DIR" +npm run dev > /tmp/e2e-frontend.log 2>&1 & +FRONTEND_PID=$! +echo " Frontend PID: $FRONTEND_PID" + +echo " Waiting for frontend..." +for i in $(seq 1 30); do + if curl -s -o /dev/null "http://localhost:$FRONTEND_PORT" 2>/dev/null; then + echo " Frontend ready after ${i}s" + break + fi + if [ "$i" -eq 30 ]; then + echo "❌ Frontend failed to start within 30s" + tail -10 /tmp/e2e-frontend.log + exit 1 + fi + sleep 1 +done + +# ── Run E2E tests ── +echo "" +echo "🧪 Running E2E tests..." +cd "$E2E_DIR" +npx playwright test "$@" +EXIT_CODE=$? + +echo "" +if [ $EXIT_CODE -eq 0 ]; then + echo "✅ All E2E tests passed!" +else + echo "❌ Some E2E tests failed (exit code: $EXIT_CODE)" +fi + +exit $EXIT_CODE diff --git a/example-project/e2e/debug.mjs b/example-project/e2e/debug.mjs new file mode 100644 index 0000000..67d49db --- /dev/null +++ b/example-project/e2e/debug.mjs @@ -0,0 +1,51 @@ +import { chromium } from 'playwright'; + +const BASE = 'http://localhost:5173'; + +async function run() { + const browser = await chromium.launch({ headless: false, slowMo: 200 }); + const context = await browser.newContext({ viewport: { width: 1280, height: 800 } }); + const page = await context.newPage(); + + // Listen to console errors + page.on('console', msg => { if (msg.type() === 'error') console.log('CONSOLE ERROR:', msg.text()); }); + page.on('response', resp => { + if (resp.status() >= 400) console.log(`API ${resp.status()} ${resp.url()}`); + }); + + // 1. Homepage + await page.goto(BASE, { waitUntil: 'networkidle' }); + await page.screenshot({ path: 'e2e/screenshots/01-homepage.png', fullPage: true }); + console.log('✓ Homepage loaded'); + + // 2. Navigate to login + await page.click('text=登录'); + await page.waitForURL('**/login'); + await page.screenshot({ path: 'e2e/screenshots/02-login.png', fullPage: true }); + console.log('✓ Login page loaded'); + + // 3. Login as admin + await page.fill('input[type="email"], input[name="email"], input[placeholder*="邮箱"]', 'admin@test.com'); + await page.fill('input[type="password"], input[name="password"], input[placeholder*="密码"]', 'password'); + await page.click('button[type="submit"], button:has-text("登录")'); + await page.waitForTimeout(1500); + await page.screenshot({ path: 'e2e/screenshots/03-after-login.png', fullPage: true }); + console.log('✓ Login submitted, current URL:', page.url()); + + // 4. Navigate to /admin/dashboard + await page.goto(BASE + '/admin/dashboard', { waitUntil: 'networkidle' }); + await page.screenshot({ path: 'e2e/screenshots/04-admin-dashboard.png', fullPage: true }); + console.log('✓ Admin dashboard, current URL:', page.url()); + + // 5. Try different pages + for (const path of ['/admin/users', '/admin/consultants', '/admin/appointments', '/admin/branches']) { + await page.goto(BASE + path, { waitUntil: 'networkidle' }); + await page.screenshot({ path: `e2e/screenshots/05${path.replace(/\//g, '-')}.png`, fullPage: true }); + console.log(`✓ Page ${path}, URL: ${page.url()}`); + } + + await browser.close(); + console.log('\nDone! Check e2e/screenshots/ for results.'); +} + +run().catch(err => { console.error(err); process.exit(1); }); diff --git a/example-project/e2e/helpers/visual-test.ts b/example-project/e2e/helpers/visual-test.ts new file mode 100644 index 0000000..fa9d46b --- /dev/null +++ b/example-project/e2e/helpers/visual-test.ts @@ -0,0 +1,167 @@ +import { type Locator, type Page } from '@playwright/test' + +interface VlmConfig { + baseUrl: string + model: string + apiKey: string + provider: 'openai' | 'anthropic' +} + +interface AnalyzeOptions { + prompt: string + element?: Locator + fullPage?: boolean +} + +function getConfig(): VlmConfig | null { + const apiKey = process.env.VLM_API_KEY + if (!apiKey) return null + + const raw = (process.env.VLM_BASE_URL || 'https://api.openai.com/v1').replace(/\/+$/, '') + const model = process.env.VLM_MODEL || 'gpt-4o-mini' + + const provider: 'openai' | 'anthropic' = + raw.includes('anthropic') || process.env.VLM_PROVIDER === 'anthropic' + ? 'anthropic' + : 'openai' + + // normalize baseUrl: strip trailing /v1 for anthropic, then provider appends /v1/messages + const baseUrl = provider === 'anthropic' ? raw.replace(/\/v1$/, '') : raw + + return { baseUrl, model, apiKey, provider } +} + +async function screenshot(pageOrLocator: Page | Locator, options: AnalyzeOptions): Promise { + let buf: Buffer + if (options.element) { + buf = await options.element.screenshot() + } else if ('context' in pageOrLocator) { + buf = await (pageOrLocator as Page).screenshot({ fullPage: options.fullPage }) + } else { + buf = await (pageOrLocator as Locator).screenshot() + } + return buf.toString('base64') +} + +async function vlmFetch(url: string, init: RequestInit, retries = 3): Promise { + for (let attempt = 1; attempt <= retries; attempt++) { + const resp = await fetch(url, init) + if (resp.ok) return resp + const body = await resp.text() + // retry on 429 (rate limit) and 5xx (server error) + if ((resp.status === 429 || resp.status >= 500) && attempt < retries) { + const delay = 1000 * Math.pow(2, attempt) + Math.random() * 1000 + console.log(` [VLM] API error ${resp.status}, retrying in ${Math.round(delay)}ms (attempt ${attempt}/${retries})`) + await new Promise(r => setTimeout(r, delay)) + continue + } + throw new Error(`VLM API error ${resp.status}: ${body}`) + } + throw new Error('VLM API max retries exceeded') +} + +async function analyzeWithOpenAI( + imageBase64: string, prompt: string, config: VlmConfig +): Promise { + const resp = await vlmFetch(`${config.baseUrl}/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${config.apiKey}`, + }, + body: JSON.stringify({ + model: config.model, + messages: [ + { + role: 'user', + content: [ + { type: 'text', text: prompt }, + { type: 'image_url', image_url: { url: `data:image/png;base64,${imageBase64}`, detail: 'high' } }, + ], + }, + ], + max_tokens: 1024, + }), + }) + const data = await resp.json() + return data.choices?.[0]?.message?.content || '' +} + +async function analyzeWithAnthropic( + imageBase64: string, prompt: string, config: VlmConfig +): Promise { + const resp = await vlmFetch(`${config.baseUrl}/v1/messages`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-api-key': config.apiKey, + 'anthropic-version': '2023-06-01', + }, + body: JSON.stringify({ + model: config.model, + max_tokens: 1024, + messages: [ + { + role: 'user', + content: [ + { + type: 'image', + source: { type: 'base64', media_type: 'image/png', data: imageBase64 }, + }, + { type: 'text', text: prompt }, + ], + }, + ], + }), + }) + const data = await resp.json() + const textBlock = data.content?.find((c: any) => c.type === 'text') + return textBlock?.text || '' +} + +export function visualTest() { + const config = getConfig() + + async function analyze(pageOrLocator: Page | Locator, options: AnalyzeOptions): Promise { + if (!config) { + throw new Error( + 'VLM not configured. Set VLM_API_KEY in environment.\n' + + ' Examples:\n' + + ' OpenAI: VLM_API_KEY=sk-... (default model: gpt-4o-mini)\n' + + ' Ollama (local): VLM_BASE_URL=http://localhost:11434/v1 VLM_MODEL=llava VLM_API_KEY=ollama\n' + + ' Anthropic/Claude: VLM_BASE_URL=https://api.anthropic.com VLM_MODEL=claude-3-5-sonnet-latest VLM_API_KEY=sk-...\n' + + ' Zhipu/GLM-5V-Turbo: VLM_BASE_URL=https://open.bigmodel.cn/api/anthropic VLM_MODEL=glm-5v-turbo VLM_PROVIDER=anthropic VLM_API_KEY=your-key\n' + + ' ⚠️ DeepSeek API does NOT support vision/image input (tested via both OpenAI & Anthropic formats).' + ) + } + + const b64 = await screenshot(pageOrLocator, options) + + if (config.provider === 'anthropic') { + return analyzeWithAnthropic(b64, options.prompt, config) + } + return analyzeWithOpenAI(b64, options.prompt, config) + } + + async function expectPrompt( + pageOrLocator: Page | Locator, + options: AnalyzeOptions & { contains?: string[]; notContains?: string[] } + ): Promise { + const text = await analyze(pageOrLocator, options) + const errors: string[] = [] + for (const substr of options.contains || []) { + if (!text.includes(substr)) { + errors.push(`Expected analysis to contain "${substr}", but got: "${text}"`) + } + } + for (const substr of options.notContains || []) { + if (text.includes(substr)) { + errors.push(`Expected analysis NOT to contain "${substr}", but got: "${text}"`) + } + } + if (errors.length > 0) throw new Error(errors.join('\n')) + return text + } + + return { analyze, expectPrompt, isConfigured: config !== null } +} diff --git a/example-project/e2e/package-lock.json b/example-project/e2e/package-lock.json new file mode 100644 index 0000000..f8d190a --- /dev/null +++ b/example-project/e2e/package-lock.json @@ -0,0 +1,78 @@ +{ + "name": "e2e", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "e2e", + "version": "1.0.0", + "devDependencies": { + "@playwright/test": "^1.61.0" + } + }, + "node_modules/@playwright/test": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.0.tgz", + "integrity": "sha512-cKA5B6lpFEMyMGjxF54QihfYpB4FkEGH+qZhtArDEG+wezQAJY8Pq6C7T1SjWz+FFzt3TbyoXBQYk/0292TdJA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.61.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.0.tgz", + "integrity": "sha512-Z+7BeeqQPRRzklHsVFP4KTGIyMxKUmfeRA4WisM6G3/XW6nwGeX6fX9qYaDa+CiUqpOkb2f6X3nar05R3kSuJQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.0.tgz", + "integrity": "sha512-caX7TrY3Ml6egyDX0WUcTHDxodl/b51y5wJOdCEA36QviK/s2g081hvmGs8eaE3DWb6NYZQ6BjO/QkNRPenoPA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/example-project/e2e/package.json b/example-project/e2e/package.json new file mode 100644 index 0000000..b2179dd --- /dev/null +++ b/example-project/e2e/package.json @@ -0,0 +1,19 @@ +{ + "name": "e2e", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "playwright test", + "test:qa": "playwright test --project=qa", + "test:dev": "playwright test --project=dev", + "test:headed": "playwright test --headed", + "test:debug": "playwright test --debug", + "test:visual": "bash run-visual.sh", + "test:visual:headed": "bash run-visual.sh --headed" + }, + "type": "module", + "devDependencies": { + "@playwright/test": "^1.61.0" + } +} diff --git a/example-project/e2e/playwright.config.ts b/example-project/e2e/playwright.config.ts new file mode 100644 index 0000000..9ba8eb4 --- /dev/null +++ b/example-project/e2e/playwright.config.ts @@ -0,0 +1,24 @@ +import { defineConfig } from '@playwright/test' + +// E2E 用例按归属分两层(详见 tests/README.md): +// tests/qa/ — QA 验收用例,合并闸门,用例基线在 docs/test-cases/e2e-cases/test-cases.md +// tests/dev/ — 开发自测用例,仅供开发期快速反馈 +export default defineConfig({ + testDir: './tests', + timeout: 30000, + retries: 1, + use: { + baseURL: 'http://localhost:5173', + viewport: { width: 1280, height: 800 }, + screenshot: 'only-on-failure', + trace: 'on-first-retry', + }, + projects: [ + { name: 'qa', testDir: './tests/qa' }, + { name: 'dev', testDir: './tests/dev' }, + ], + reporter: [ + ['list'], + ['html', { outputFolder: 'playwright-report' }], + ], +}) diff --git a/example-project/e2e/run-visual.sh b/example-project/e2e/run-visual.sh new file mode 100755 index 0000000..6240746 --- /dev/null +++ b/example-project/e2e/run-visual.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +# ── Visual (VLM) E2E Tests ── +# Requires a Vision Language Model API that supports image input. +# +# Usage: +# OpenAI: VLM_API_KEY=sk-... ./run-visual.sh +# Ollama (local/free): VLM_BASE_URL=http://localhost:11434/v1 VLM_MODEL=llava VLM_API_KEY=ollama ./run-visual.sh +# Anthropic/Claude: VLM_BASE_URL=https://api.anthropic.com VLM_MODEL=claude-3-5-sonnet-latest VLM_API_KEY=sk-... ./run-visual.sh +# Zhipu/GLM-5V-Turbo: VLM_BASE_URL=https://open.bigmodel.cn/api/anthropic VLM_MODEL=glm-5v-turbo VLM_PROVIDER=anthropic VLM_API_KEY=your-key ./run-visual.sh +# +# ⚠️ DeepSeek API does NOT support vision/image input on any model. + +cd "$(dirname "$0")" + +if [ -z "${VLM_API_KEY:-}" ]; then + echo "❌ VLM_API_KEY not set." + echo "" + echo "Usage:" + echo " OpenAI: VLM_API_KEY=sk-... ./run-visual.sh" + echo " Ollama (local): VLM_BASE_URL=http://localhost:11434/v1 VLM_MODEL=llava VLM_API_KEY=ollama ./run-visual.sh" + echo " Anthropic/Claude: VLM_BASE_URL=https://api.anthropic.com VLM_MODEL=claude-3-5-sonnet-latest VLM_API_KEY=sk-... ./run-visual.sh" + echo " Zhipu/GLM-5V-Turbo: VLM_BASE_URL=https://open.bigmodel.cn/api/anthropic VLM_MODEL=glm-5v-turbo VLM_PROVIDER=anthropic VLM_API_KEY=your-key ./run-visual.sh" + exit 1 +fi + +echo "🔍 Running visual E2E tests..." +echo " Model: ${VLM_MODEL:-gpt-4o-mini}" +echo " Base URL: ${VLM_BASE_URL:-https://api.openai.com/v1}" + +npx playwright test tests/dev/visual.spec.ts "$@" diff --git a/example-project/e2e/tests/README.md b/example-project/e2e/tests/README.md new file mode 100644 index 0000000..2fab1fd --- /dev/null +++ b/example-project/e2e/tests/README.md @@ -0,0 +1,32 @@ +# E2E 测试分层 + +本目录下的 E2E 用例按 **归属** 分成两层。两层的验收效力完全不同,不要混。 + +``` +tests/ +├── qa/ # QA 验收用例(自动化实现)—— 合并闸门 +└── dev/ # 开发自测用例(自动化实现)—— 仅供开发反馈 +``` + +| | `qa/` | `dev/` | +|---|---|---| +| 用例来源 | `docs/test-cases/e2e-cases/test-cases.md` 的 QA 验收用例 | 开发按 Plan 自定 | +| 编号 | `TC-xxx` | 无编号,标题自解释 | +| 谁判定 | QA | 开发本人 | +| 合并闸门 | **是** —— 不通过不能合并 | 否 —— 挂了不阻塞别人,但必须自己修 | +| 关注点 | 需求规格有没有被实现 | 我这次改的东西有没有被我改坏 | + +## 约定 + +- `qa/` 下的每个 `test()` 都要能对应到 `docs/test-cases/e2e-cases/test-cases.md` 里的一条用例(编号一致)。 +- `dev/` 下的用例只服务于开发期的快速反馈,**不能** 作为验收依据。 +- 新增 QA 用例时,**先**在 `docs/test-cases/e2e-cases/test-cases.md` 里写文本用例,再写自动化。 +- 自动化实现可以由开发代写,但 **用例的判定权归 QA**。 + +## 运行 + +```bash +npm test # 全部(qa + dev) +npm run test:qa # 只跑 QA 验收用例 +npm run test:dev # 只跑开发自测用例 +``` diff --git a/example-project/e2e/tests/dev/visual.spec.ts b/example-project/e2e/tests/dev/visual.spec.ts new file mode 100644 index 0000000..7bc0a3a --- /dev/null +++ b/example-project/e2e/tests/dev/visual.spec.ts @@ -0,0 +1,153 @@ +import { test, expect } from '@playwright/test' +import { visualTest } from '../../helpers/visual-test' + +const ADMIN_EMAIL = 'admin@test.com' +const ADMIN_PASSWORD = 'password' + +const vlm = visualTest() + +/* ─────────────── Visual Tests ─────────────── */ + +test.describe('Visual Tests', () => { + + test('homepage hero section visual layout', async ({ page }) => { + test.skip(!vlm.isConfigured, 'VLM not configured (set VLM_API_KEY)') + + await page.goto('/') + const analysis = await vlm.analyze(page, { + prompt: `Describe the hero section of this consultation booking website homepage. + What is the main heading text? What buttons/actions are available? + List the exact text content you see.`, + fullPage: true, + }) + expect(analysis).toContain('专业咨询服务') + console.log('[Visual] Homepage analysis:', analysis) + }) + + test('login page form layout', async ({ page }) => { + test.skip(!vlm.isConfigured, 'VLM not configured') + + await page.goto('/login') + const analysis = await vlm.analyze(page, { + prompt: `Describe the login page form. What input fields are visible? + Are there any labels? What does the submit button say? + List all visible text elements.`, + }) + expect(analysis).toContain('登录') + console.log('[Visual] Login page analysis:', analysis) + }) + + test('calendar date picker renders consecutive dates', async ({ page }) => { + test.skip(!vlm.isConfigured, 'VLM not configured (set VLM_API_KEY)') + + // Login and go to book page + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + await page.goto('/user/book') + await expect(page.locator('h1')).toHaveText('预约咨询') + + // Select a consultant to reveal the date picker + await page.locator('text=张医生').click() + await expect(page.locator('text=2. 选择日期')).toBeVisible() + + // Visual analysis of the date picker + const analysis = await vlm.analyze(page.locator('.booking-steps'), { + prompt: `Analyze the date picker section (step 2). + 1. How many date buttons are shown? + 2. List each date in YYYY-MM-DD format. + 3. Are the dates consecutive (no gaps)? + 4. Is today's date included as the first option? + Return the list of dates and your observations.`, + }) + console.log('[Visual] Date picker analysis:', analysis) + + // Verify the date format is correct (YYYY-MM-DD) + const dates = analysis.match(/\d{4}-\d{2}-\d{2}/g) + expect(dates).not.toBeNull() + expect(dates!.length).toBeGreaterThanOrEqual(5) + }) + + test('admin dashboard stat cards layout', async ({ page }) => { + test.skip(!vlm.isConfigured, 'VLM not configured') + + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + const analysis = await vlm.analyze(page.locator('.stats-grid'), { + prompt: `Analyze the dashboard statistics grid. + 1. How many stat cards are visible? + 2. For each card, what is the number/value and what is its label? + 3. Are all cards displayed in a grid layout? + List each card's content.`, + }) + expect(analysis).toContain('用户数') + expect(analysis).toContain('咨询师') + expect(analysis).toContain('总预约') + expect(analysis).toContain('网点') + console.log('[Visual] Dashboard stats analysis:', analysis) + }) + + test('booking flow visual consistency (consultant → date → time → confirm)', async ({ page }) => { + test.skip(!vlm.isConfigured, 'VLM not configured') + + // Login and go to book page + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + await page.goto('/user/book') + await page.locator('text=张医生').click() + await expect(page.locator('text=2. 选择日期')).toBeVisible() + + // Pick a date to reveal time slots + const dateBtn = page.locator('div.date-list button').first() + await dateBtn.click() + await page.waitForTimeout(1500) + + // Full booking form visual analysis + const analysis = await vlm.analyze(page.locator('.booking-steps'), { + prompt: `Analyze this multi-step booking form. + 1. How many steps are currently visible? + 2. Which consultant is currently selected? + 3. What date was chosen? + 4. Are time slots visible? If yes, list the available times. + 5. Describe the overall layout and completeness of the form. + Give a detailed step-by-step description.`, + }) + console.log('[Visual] Booking form analysis:', analysis) + }) + + test('admin sidebar navigation renders all links', async ({ page }) => { + test.skip(!vlm.isConfigured, 'VLM not configured') + + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + const analysis = await vlm.analyze(page.locator('.sidebar'), { + prompt: `Analyze the admin sidebar navigation. + 1. List all navigation links visible. + 2. Is there a logout button? + 3. What is the title of the sidebar? + List all link text.`, + }) + expect(analysis).toContain('仪表盘') + expect(analysis).toContain('用户管理') + expect(analysis).toContain('咨询师管理') + expect(analysis).toContain('预约管理') + expect(analysis).toContain('网点管理') + expect(analysis).toContain('退出') + console.log('[Visual] Sidebar analysis:', analysis) + }) +}) diff --git a/example-project/e2e/tests/qa/app.spec.ts b/example-project/e2e/tests/qa/app.spec.ts new file mode 100644 index 0000000..9aaa2cd --- /dev/null +++ b/example-project/e2e/tests/qa/app.spec.ts @@ -0,0 +1,341 @@ +import { test, expect } from '@playwright/test' + +const BASE = 'http://localhost:5173' +const ADMIN_EMAIL = 'admin@test.com' +const ADMIN_PASSWORD = 'password' + +/* ─────────────── Public Pages ─────────────── */ + +test.describe('Public Pages', () => { + + test('TC-001 首页加载', async ({ page }) => { + await page.goto('/') + await expect(page.locator('h1')).toHaveText('专业咨询服务') + await expect(page.locator('text=免费注册')).toBeVisible() + await expect(page.locator('text=立即预约')).toBeVisible() + await expect(page.locator('text=© 2026 咨询预约平台')).toBeVisible() + }) + + test('TC-002 登录页渲染', async ({ page }) => { + await page.goto('/login') + await expect(page.locator('h2')).toHaveText('登录') + await expect(page.locator('input[type="email"]')).toBeVisible() + await expect(page.locator('input[type="password"]')).toBeVisible() + await expect(page.locator('button[type="submit"]')).toHaveText('登录') + await expect(page.locator('text=还没有账号?')).toBeVisible() + }) + + test('TC-003 注册页渲染', async ({ page }) => { + await page.goto('/register') + await expect(page.locator('h2')).toHaveText('注册') + await expect(page.locator('input[type="email"]')).toBeVisible() + await expect(page.locator('input[type="password"]')).toBeVisible() + await expect(page.locator('button[type="submit"]')).toHaveText('注册') + await expect(page.locator('text=已有账号?')).toBeVisible() + }) + + test('TC-004 公开 API 可用', async ({ request }) => { + let resp = await request.get(`${BASE}/api/v1/data-dictionaries`) + expect(resp.status()).toBe(200) + + resp = await request.get(`${BASE}/api/v1/business-rules`) + expect(resp.status()).toBe(200) + + resp = await request.get(`${BASE}/api/v1/consultants`) + expect(resp.status()).toBe(200) + const body = await resp.json() + expect(body.length).toBeGreaterThanOrEqual(3) + }) + + test('TC-005 导航跳转', async ({ page }) => { + await page.goto('/') + await page.click('text=登录') + await expect(page).toHaveURL('/login') + + await page.click('text=立即注册') + await expect(page).toHaveURL('/register') + }) +}) + +/* ─────────────── Auth & User Lifecycle (serial: share registered email) ─────────────── */ + +let registerEmail = '' + +test.describe.serial('Auth & User Lifecycle', () => { + + test('TC-006 管理员登录成功', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + await expect(page.locator('h1')).toHaveText('管理仪表盘') + }) + + test('TC-007 错误密码提示', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', 'wrongpassword') + await page.click('button[type="submit"]') + await expect(page.locator('.error')).toBeVisible({ timeout: 8000 }) + }) + + test('TC-008 注册新用户', async ({ page }) => { + registerEmail = `e2e_${Date.now()}@test.com` + await page.goto('/register') + + await page.locator('input[placeholder*="姓名"]').fill('E2E用户') + await page.fill('input[type="email"]', registerEmail) + await page.locator('input[placeholder*="选填"]').fill('13800000001') + await page.fill('input[type="password"]', 'Test123456') + + await page.click('button[type="submit"]') + await page.waitForURL('**/user/dashboard', { timeout: 10000 }) + await expect(page.locator('text=E2E用户')).toBeVisible() + }) + + test('TC-009 重复邮箱注册', async ({ page }) => { + await page.goto('/register') + await page.locator('input[placeholder*="姓名"]').fill('重复用户') + await page.fill('input[type="email"]', registerEmail) + await page.fill('input[type="password"]', 'Test123456') + await page.click('button[type="submit"]') + await expect(page.locator('.error')).toBeVisible({ timeout: 8000 }) + }) + + test('TC-010 新用户登录', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', registerEmail) + await page.fill('input[type="password"]', 'Test123456') + await page.click('button[type="submit"]') + await page.waitForURL('**/user/dashboard', { timeout: 10000 }) + await expect(page.locator('h1').first()).toHaveText('用户中心') + }) + + test('TC-011 用户仪表盘', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', registerEmail) + await page.fill('input[type="password"]', 'Test123456') + await page.click('button[type="submit"]') + await page.waitForURL('**/user/dashboard', { timeout: 10000 }) + + await expect(page.locator('.stat-card').filter({ hasText: '总预约' })).toBeVisible() + await expect(page.locator('text=待确认')).toBeVisible() + await expect(page.locator('text=已完成')).toBeVisible() + }) + + test('TC-012 浏览咨询师', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', registerEmail) + await page.fill('input[type="password"]', 'Test123456') + await page.click('button[type="submit"]') + await page.waitForURL('**/user/dashboard', { timeout: 10000 }) + + await page.goto('/user/book') + await expect(page.locator('h1')).toHaveText('预约咨询') + await expect(page.locator('text=张医生')).toBeVisible() + await expect(page.locator('text=李律师')).toBeVisible() + await expect(page.locator('text=王教练')).toBeVisible() + }) + + test('TC-013 预约 + 取消', async ({ page }) => { + // Login + await page.goto('/login') + await page.fill('input[type="email"]', registerEmail) + await page.fill('input[type="password"]', 'Test123456') + await page.click('button[type="submit"]') + await page.waitForURL('**/user/dashboard', { timeout: 10000 }) + + // Go to book page + await page.goto('/user/book') + await expect(page.locator('h1')).toHaveText('预约咨询') + + // Step 1: Select consultant + await page.locator('text=张医生').click() + await expect(page.locator('text=2. 选择日期')).toBeVisible() + + // Step 2: Pick a date + const dateBtn = page.locator('div.date-list button').first() + await expect(dateBtn).toBeVisible() + await dateBtn.click() + await page.waitForTimeout(1500) + + // Step 3: Pick a time slot + const slotBtn = page.locator('div.slot-list button').first() + if (await slotBtn.isVisible({ timeout: 5000 })) { + await slotBtn.click() + await expect(page.locator('text=4. 备注')).toBeVisible() + + // Step 4: Add note and submit + await page.fill('textarea', 'E2E booking test') + await page.click('text=确认预约') + await page.waitForURL('**/user/appointments', { timeout: 10000 }) + + // Verify appointment created + await expect(page.locator('h1')).toHaveText('我的预约') + + // Cancel the appointment + const cancelBtn = page.locator('button:has-text("取消")').first() + if (await cancelBtn.isVisible({ timeout: 5000 })) { + page.once('dialog', dialog => dialog.accept()) + await cancelBtn.click() + await page.waitForTimeout(1500) + await expect(page.locator('.status.cancelled').first()).toBeVisible({ timeout: 5000 }) + } + } + }) + + test('TC-014 编辑个人信息', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', registerEmail) + await page.fill('input[type="password"]', 'Test123456') + await page.click('button[type="submit"]') + await page.waitForURL('**/user/dashboard', { timeout: 10000 }) + + await page.goto('/user/profile') + const nameInput = page.locator('input').nth(1) + await nameInput.fill('E2E用户-已改名') + const [dialog] = await Promise.all([ + page.waitForEvent('dialog', { timeout: 5000 }), + page.click('text=保存'), + ]) + expect(dialog.message()).toContain('保存成功') + await dialog.dismiss() + }) +}) + +/* ─────────────── Admin Flows (independent tests) ─────────────── */ + +test.describe('Admin Flows', () => { + + test('TC-015 仪表盘统计', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + await expect(page.locator('h1')).toHaveText('管理仪表盘') + await expect(page.locator('.stat-card').filter({ hasText: '用户数' })).toBeVisible() + await expect(page.locator('.stat-card').filter({ hasText: '咨询师' })).toBeVisible() + await expect(page.locator('.stat-card').filter({ hasText: '总预约' })).toBeVisible() + await expect(page.locator('.stat-card').filter({ hasText: '待确认' })).toBeVisible() + await expect(page.locator('.stat-card').filter({ hasText: '网点' })).toBeVisible() + }) + + test('TC-016 用户管理', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + await page.goto('/admin/users') + await expect(page.locator('table')).toBeVisible({ timeout: 10000 }) + await expect(page.locator('text=admin@test.com')).toBeVisible() + await expect(page.locator('text=管理员')).toBeVisible() + + const toggleBtn = page.locator('button:has-text("禁用"), button:has-text("启用")').first() + if (await toggleBtn.isVisible()) { + await toggleBtn.click() + await page.waitForTimeout(1000) + } + }) + + test('TC-017 咨询师管理', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + await page.locator('a:has-text("咨询师管理")').click() + await page.waitForURL('**/admin/consultants', { timeout: 10000 }) + await expect(page.locator('table')).toBeVisible({ timeout: 10000 }) + await expect(page.locator('text=张医生')).toBeVisible() + await expect(page.locator('text=李律师')).toBeVisible() + await expect(page.locator('text=王教练')).toBeVisible() + }) + + test('TC-018 预约管理', async ({ page }) => { + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + await page.locator('a:has-text("预约管理")').click() + await page.waitForURL('**/admin/appointments', { timeout: 10000 }) + await expect(page.locator('h1')).toHaveText('预约管理') + }) + + test('TC-019 网点 CRUD', async ({ page }) => { + // Login + await page.goto('/login') + await page.fill('input[type="email"]', ADMIN_EMAIL) + await page.fill('input[type="password"]', ADMIN_PASSWORD) + await page.click('button[type="submit"]') + await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) + + // Go to branches + await page.locator('a:has-text("网点管理")').click() + await page.waitForURL('**/admin/branches', { timeout: 10000 }) + await expect(page.locator('h1')).toHaveText('网点管理') + await expect(page.locator('text=朝阳咨询中心')).toBeVisible({ timeout: 10000 }) + await expect(page.locator('text=海淀咨询中心')).toBeVisible() + await expect(page.locator('text=浦东咨询中心')).toBeVisible() + + // ── CREATE ── + await page.click('text=新增网点') + await expect(page.locator('.modal')).toBeVisible() + + // Modal:
+ await page.locator('.modal .form-group').nth(0).locator('input').fill('E2E测试网点') + await page.locator('.modal .form-group').nth(1).locator('input').fill('东城区测试大街1号') + await page.locator('.modal .form-group').nth(2).locator('input').fill('010-88889999') + await page.locator('.modal button:has-text("保存")').click() + await page.waitForTimeout(1500) + await expect(page.locator('text=E2E测试网点')).toBeVisible({ timeout: 5000 }) + + // ── EDIT ── + await page.locator('tr:has-text("E2E测试网点") button:has-text("编辑")').click() + await expect(page.locator('.modal')).toBeVisible() + await page.locator('.modal .form-group').nth(0).locator('input').fill('E2E测试网点-已改') + await page.locator('.modal button:has-text("保存")').click() + await page.waitForTimeout(1500) + await expect(page.locator('text=E2E测试网点-已改')).toBeVisible({ timeout: 5000 }) + + // ── DELETE ── + page.once('dialog', dialog => dialog.accept()) + await page.locator('tr:has-text("E2E测试网点-已改") button:has-text("删除")').click() + await page.waitForTimeout(1500) + await expect(page.locator('text=E2E测试网点-已改')).toHaveCount(0, { timeout: 5000 }) + }) +}) + +/* ─────────────── Edge Cases ─────────────── */ + +test.describe('Edge Cases', () => { + + test('TC-020 未登录访问管理页', async ({ page }) => { + await page.goto('/') + await page.evaluate(() => localStorage.clear()) + await page.goto('/admin/dashboard') + await expect(page).toHaveURL(/\/login/, { timeout: 5000 }) + }) + + test('TC-021 未登录访问用户页', async ({ page }) => { + await page.goto('/') + await page.evaluate(() => localStorage.clear()) + await page.goto('/user/dashboard') + await expect(page).toHaveURL(/\/login/, { timeout: 5000 }) + }) + + test('TC-022 首页 CTA 可见', async ({ page }) => { + await page.goto('/') + await page.evaluate(() => localStorage.clear()) + await page.goto('/') + const cta = page.locator('text=免费注册') + await expect(cta).toBeVisible() + }) +}) diff --git a/example-project/frontend/index.html b/example-project/frontend/index.html new file mode 100644 index 0000000..0498fdb --- /dev/null +++ b/example-project/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + 咨询预约平台 + + +
+ + + diff --git a/example-project/frontend/package-lock.json b/example-project/frontend/package-lock.json new file mode 100644 index 0000000..94f6a77 --- /dev/null +++ b/example-project/frontend/package-lock.json @@ -0,0 +1,2034 @@ +{ + "name": "consultation-frontend", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "consultation-frontend", + "version": "0.1.0", + "dependencies": { + "axios": "^1.7.0", + "element-plus": "^2.9.0", + "pinia": "^2.2.0", + "vue": "^3.5.13", + "vue-router": "^4.3.0" + }, + "devDependencies": { + "@types/node": "^25.9.3", + "@vitejs/plugin-vue": "^5.0.5", + "typescript": "~5.5.0", + "vite": "^5.4.0", + "vue-tsc": "^2.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", + "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", + "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@ctrl/tinycolor": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-3.6.1.tgz", + "integrity": "sha512-SITSV6aIXsuVNV3f3O0f2n/cgyEDWoSqtZMYiAmcsYHydcKrOz3gUxB/iXd/Qf08+IZX4KpgNbvUdMBmWz+kcA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/@element-plus/icons-vue": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/@element-plus/icons-vue/-/icons-vue-2.3.2.tgz", + "integrity": "sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==", + "license": "MIT", + "peerDependencies": { + "vue": "^3.2.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@popperjs/core": { + "name": "@sxzz/popperjs-es", + "version": "2.11.8", + "resolved": "https://registry.npmjs.org/@sxzz/popperjs-es/-/popperjs-es-2.11.8.tgz", + "integrity": "sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.0.tgz", + "integrity": "sha512-IPIQ55ythEHkfEd9jMEi32OQ7SxURsGA43JI22lj01OLZNt2NUbJX8YUHxkVWyQ6daHPNn0truF5nSj3DQp6YQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.0.tgz", + "integrity": "sha512-M6s9cr10MibETyo8JsOkq+Lo1+lU6hcvb1MApnUql5qte/5hMEgzlN8/ReIKNfRV8rrqX50W1BX9zoUhC192RA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.0.tgz", + "integrity": "sha512-BqCoMoIbn0keKys+dEAdBa70EtOwV1bEsQCUgU9FdiZmmMge/Zk7LlkYGqbrdHR+Frnt0E1FOanly+rlwvvQzw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.0.tgz", + "integrity": "sha512-SIMzST3VFNXDAbeIWDWiFCNM5qncUBDWaEV7NfE7oZbDt2mgfW4MvbKdbYiGOLoM32gbTv608UMd0XktEYSD7w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.0.tgz", + "integrity": "sha512-ezjfSQMP7ArdUsbBwbQIfwAlhE84I2iVnzQNCFSveqV42q+BmKlzVpf7mxv5EchLcoWU4y6/heFzVg1F+hodUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.0.tgz", + "integrity": "sha512-9+qTWGW9AZRhnUgwtTwzNwcPlL87ngkeN0LA+q1bADvmY9aNvWaF2TFW8BZgnQPYxpDI7+rMVLivcd4V737TAQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.0.tgz", + "integrity": "sha512-T1dMEQhXA/jkJ/jyMIw9IovK8bSUq7A8kLIlvZTb/6YIVsp2zLavr4F3oyllHWo7eIVJRyE5n3tUjQJEbE1IuQ==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.0.tgz", + "integrity": "sha512-2as0LgT7qQpyceQq6VUJYnumUMUrgGQCWIiDIN9DE0/tglsk6o66uCB4f3djRawAltvfCNLyZZrsqbPA6inCsA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.0.tgz", + "integrity": "sha512-bVURMg+6eNN9C/yc0aVjooZcwTTtYF4YW3xta5pP0//r3o1V8gXEHXWCndj47w/HhwsFroZrFhR+6uQP5T0n0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.0.tgz", + "integrity": "sha512-Ful8pM/2yYI83PViWdFdpZhdI8HJ5qsXANe5atypbHDf+KIBBDsZsbyy8hbXnULVvW9NsTh5DHwbcBftyLTfiw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.0.tgz", + "integrity": "sha512-9Gp/DgrkzfUBmNPVTyPTvay+4xEP7M/clXpj3efXBcm6uTIVIgDg4rqUpqKXvLEuFRVuEpSAOkhgNeecvaZ4Cg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.0.tgz", + "integrity": "sha512-m9tsJz54LUXkSYM8+8PG81B9IKK5r+2T0clMq4QrS16xFosufU7firBDAZEsDheDs7wTlP7h3++S7lMsU955HA==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.0.tgz", + "integrity": "sha512-3UvJ5PNVU16aJf6M3tFI24pWzAl2/ynfbyRN3ICyQajK1lSkrnVYNnLz3v04J32qKa0FczJc22zeToc0lr2A3w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.0.tgz", + "integrity": "sha512-vRWUAbYLGHBZS6Q8Msb2sfnf1fvJf+47t8l/TwOerM2qArzy+IeNMTHrYLHXh95h8MoatPHI5hhSZNs+mGXKPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.0.tgz", + "integrity": "sha512-c00T5SYENHAt86cfW47URaP3Us5vLC/4QO7GYud1G5VNRffCwwCuBspwqYrriuJB+5m0WFzClCn9wed0FBjKvg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.0.tgz", + "integrity": "sha512-krrCDilhXOwFkSkO3Wm9I/f9H0L92XHHwy2fwxjukxIbh0dem8gZqOW5Y8BsHrpJv5qwlRBV+Wl4ZFyRWhUpwg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.0.tgz", + "integrity": "sha512-7pfYFSTc4/rUC/FtAI0Qp6QthDBCIi6/AuP1xYqFk5vanI6KnL5dWKP60OM/05LOsbwTmIcvr6eXC4CJuJ75IA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.0.tgz", + "integrity": "sha512-7SDIalKeIpG0Ifogbbdn58HmSotYMlf23K3dCJEmiVd9Fg36Vmni82iPQec27N3wY4Bvbxftkxz6vSx9OcouTg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.0.tgz", + "integrity": "sha512-eRZevouTH2i1HeAVLqJuLnt256krQkGY0TN6WsTmsIhuzbh457HuWDMakKwmi0Cjadux983CoSr8Lim2QhUIFw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.0.tgz", + "integrity": "sha512-3oVS7FLGa4U1qcvao9ylGxrjXZyUQqR8UwxEcnUEyPX53O/C/mKDZegNXTdHCP+h3e6ta/f1EN38Yif1mmZHYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.0.tgz", + "integrity": "sha512-yTB9TgfWj5wHe5QgktAgXTLLot1gvEjl1NiPPAUiCs4oPrIWFl5V4nC3GrkNdj9LaAU4s94nVrGbGOCqUpyWsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.0.tgz", + "integrity": "sha512-5LOhoaesY3doG1c+ac/2JtgREpKoJr5bUHH8tKY0V8di7+uSV6BwLs2PlR0/yzefGOkR+wE7ZolZphHCsyG5Rw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.0.tgz", + "integrity": "sha512-yYkWHhmbhRTWTnWos5HC4GcPQfjlzzCNbM9e/+GXrLuaBXYA3qSDR9f0Vgufd5S8yX81U8jPKp7ZnAjZFMtRnw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.0.tgz", + "integrity": "sha512-SoTb6lPg25xZlA2ibwQ++ahCCnH+FP0qmEuafMJ4gznZKOlXioKEAeJLgCrqjM98ACziXM9V1amFjICVL4IFoA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.0.tgz", + "integrity": "sha512-5L+T1fMX4RIEBoZzT0+sQ0PhTS36NULFmMXtl1TZo44TMAROIMHbZufSOjVWt/Y622BtxgxtaNOokbTDvfsrZA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.27", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.27.tgz", + "integrity": "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==", + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz", + "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/node": { + "version": "25.9.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.3.tgz", + "integrity": "sha512-603BddQMv3pUcr4U2dhujk83N2tTDVr/34wII2B6bJy6g+8WD6yUb11jszNs0gdi4PesVWl7ABt8nYMVpnLUcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.16", + "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.16.tgz", + "integrity": "sha512-oh8q2Zc32S6gd/j50GowEjKLoOVOwHP/bWVjKJInBwQqdOYMdPrf1oVlelTlyfFK3CKxL1uahMDAr+vy8T7yMQ==", + "license": "MIT" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", + "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.15", + "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.15.tgz", + "integrity": "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.15" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.15", + "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.15.tgz", + "integrity": "sha512-CPbMWlUN6hVZJYGcU/GSoHu4EnCHiLaXI9n8c9la6RaI9W5JHX+NqG+GSQcB0JdC2FIBLdZJwGsfKyBB71VlTg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.15", + "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.15.tgz", + "integrity": "sha512-2aZ8i0cqPGjXb4BhkMsPYDkkuc2ZQ6yOpqwAuNwUoncELqoy5fRgOQtLR9gB0g902iS0NAkvpIzs27geVyVdPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.15", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.38.tgz", + "integrity": "sha512-s99aGxWYig9ErHbct27KXEGhrBYlRI6c4MwAgXErOAbX9xiW37/uMa+XUDO69zLz83dng8UUZ70CTOJrLrYrEQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@vue/shared": "3.5.38", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.38.tgz", + "integrity": "sha512-JTqp25l8aFfJYF7/KmsXZjAxJz7T+SjmTJLoXVjHtc2BrSgSiW2n9Aem/cWq1OPe68A8JL06B3eVdhlP0H4TVw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.38", + "@vue/shared": "3.5.38" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.38.tgz", + "integrity": "sha512-DuA2GiZawSEW442iw/9+Fkol8hTgb4Ke5KkhmSry65QA7YuyMbIdy8p0XZRMvNwJdgRz307W8g1CSzdvS4nuNg==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@vue/compiler-core": "3.5.38", + "@vue/compiler-dom": "3.5.38", + "@vue/compiler-ssr": "3.5.38", + "@vue/shared": "3.5.38", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.15", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.38.tgz", + "integrity": "sha512-7s+W5Gc42FGxZMcuwl8H5B29T8BJPMdBT7KHFE+BbAuZ/iTEdTtv7z2XiMjiaUUw4w3ZcCEdHs36RuYJ2VA7bA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.38", + "@vue/shared": "3.5.38" + } + }, + "node_modules/@vue/compiler-vue2": { + "version": "2.7.16", + "resolved": "https://registry.npmjs.org/@vue/compiler-vue2/-/compiler-vue2-2.7.16.tgz", + "integrity": "sha512-qYC3Psj9S/mfu9uVi5WvNZIzq+xnXMhOwbTFKKDD7b1lhpnn71jXSFdTQ+WsIEk0ONCd7VV2IMm7ONl6tbQ86A==", + "dev": true, + "license": "MIT", + "dependencies": { + "de-indent": "^1.0.2", + "he": "^1.2.0" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "2.2.12", + "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-2.2.12.tgz", + "integrity": "sha512-IsGljWbKGU1MZpBPN+BvPAdr55YPkj2nB/TBNGNC32Vy2qLG25DYu/NBN2vNtZqdRbTRjaoYrahLrToim2NanA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.15", + "@vue/compiler-dom": "^3.5.0", + "@vue/compiler-vue2": "^2.7.16", + "@vue/shared": "^3.5.0", + "alien-signals": "^1.0.3", + "minimatch": "^9.0.3", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.38.tgz", + "integrity": "sha512-pG6LV/NDNRbKizcUjFFLAfjaL8mcv4DmR9avNcUw2gDHBzZneuS2TWCmp633ynzxz9YYKNeEPK2I8Wraqy2HUQ==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.38" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.38.tgz", + "integrity": "sha512-iyW8WVfF1CpCXxncZY5Ei6rSd6oZr5DgEom//fUjRBRl56AXPD+s9ATvukRt77ZFTuYlnVA1bxY+dJB94tWVYw==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.38", + "@vue/shared": "3.5.38" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.38.tgz", + "integrity": "sha512-apX2wt9sdfDshS+a2xueFZLVpt0GkRJZSoPmrW/SA4yzXTznhfcMVW59gr7h4YQeY0vJhdJkk2rsIDwgfFgC5A==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.38", + "@vue/runtime-core": "3.5.38", + "@vue/shared": "3.5.38", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.38.tgz", + "integrity": "sha512-vue8vbf2QlV4quHqzwmJy6dWfmRhP1J8l4wtZg60CL6VoKqcPY2oe7may3+1d9qfpedjK5PRLFqd5k3Isj9mUw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.38", + "@vue/shared": "3.5.38" + }, + "peerDependencies": { + "vue": "3.5.38" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.38.tgz", + "integrity": "sha512-FTW0AFZNaK5/mOqvGBwVfUlNLU38TiQn4+DQgIFUnrBBJQ1crMJ82yeGQLV5jyKFsO8yRukpbuP7x+nRbH6aug==", + "license": "MIT" + }, + "node_modules/@vueuse/core": { + "version": "9.13.0", + "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-9.13.0.tgz", + "integrity": "sha512-pujnclbeHWxxPRqXWmdkKV5OX4Wk4YeK7wusHqRwU0Q7EFusHoqNA/aPhB6KCh9hEqJkLAJo7bb0Lh9b+OIVzw==", + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.16", + "@vueuse/metadata": "9.13.0", + "@vueuse/shared": "9.13.0", + "vue-demi": "*" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/metadata": { + "version": "9.13.0", + "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-9.13.0.tgz", + "integrity": "sha512-gdU7TKNAUVlXXLbaF+ZCfte8BjRJQWPCa2J55+7/h+yDtzw3vOoGQDRXzI6pyKyo6bXFT5/QoPE4hAknExjRLQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared": { + "version": "9.13.0", + "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-9.13.0.tgz", + "integrity": "sha512-UrnhU+Cnufu4S6JLCPZnkWh0WwZGUp72ktOF2DFptMlOs3TOdVv8xJN53zhHGARmVOsz5KqOls09+J1NR6sBKw==", + "license": "MIT", + "dependencies": { + "vue-demi": "*" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/alien-signals": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-1.0.13.tgz", + "integrity": "sha512-OGj9yyTnJEttvzhTUWuscOvtqxq5vrhF7vL9oS0xJ2mK0ItPYP1/y+vCFebfxoEyAz0++1AIwJ5CMr+Fk3nDmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-validator": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/async-validator/-/async-validator-4.2.5.tgz", + "integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz", + "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.5", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.1.tgz", + "integrity": "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/dayjs": { + "version": "1.11.23", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", + "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", + "license": "MIT" + }, + "node_modules/de-indent": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/de-indent/-/de-indent-1.0.2.tgz", + "integrity": "sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/element-plus": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.9.0.tgz", + "integrity": "sha512-ccOFXKsauo2dtokAr4OX7gZsb7TuAoVxA2zGRZo5o2yyDDBLBaZxOoFQPoxITSLcHbBfQuNDGK5Iag5hnyKkZA==", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^3.4.1", + "@element-plus/icons-vue": "^2.3.1", + "@floating-ui/dom": "^1.0.1", + "@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.7", + "@types/lodash": "^4.14.182", + "@types/lodash-es": "^4.17.6", + "@vueuse/core": "^9.1.0", + "async-validator": "^4.2.5", + "dayjs": "^1.11.13", + "escape-html": "^1.0.3", + "lodash": "^4.17.21", + "lodash-es": "^4.17.21", + "lodash-unified": "^1.0.2", + "memoize-one": "^6.0.0", + "normalize-wheel-es": "^1.2.0" + }, + "peerDependencies": { + "vue": "^3.2.0" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/follow-redirects": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/lodash-unified": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/lodash-unified/-/lodash-unified-1.0.3.tgz", + "integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==", + "license": "MIT", + "peerDependencies": { + "@types/lodash-es": "*", + "lodash": "*", + "lodash-es": "*" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/memoize-one": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-6.0.0.tgz", + "integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==", + "license": "MIT" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", + "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.13", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.13.tgz", + "integrity": "sha512-sPdqC6ByMVVGvF1ynvvMo0/o+oD1VX7DaHhijt1bFgjvBkHBib4t49GoNDhf2NDta4oeUNlaGbSt5K7qjZ955Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-wheel-es": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz", + "integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==", + "license": "BSD-3-Clause" + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/pinia": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/pinia/-/pinia-2.3.1.tgz", + "integrity": "sha512-khUlZSwt9xXCaTbbxFYBKDc/bWAGWJjOgvxETwkTN7KRm66EeT1ZdZj6i2ceh9sP2Pzqsbc704r2yngBrxBVug==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.3", + "vue-demi": "^0.14.10" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "typescript": ">=4.4.4", + "vue": "^2.7.0 || ^3.5.11" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/postcss": { + "version": "8.5.15", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", + "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.12", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/rollup": { + "version": "4.62.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.0.tgz", + "integrity": "sha512-nc72Wgq62I7rtDV4izT5/aaS0zxy3kttkinf9586ApknY3jZO9NYsmtc24fUckA0X7Q2v+ML4a15pdUlV5V/jA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.62.0", + "@rollup/rollup-android-arm64": "4.62.0", + "@rollup/rollup-darwin-arm64": "4.62.0", + "@rollup/rollup-darwin-x64": "4.62.0", + "@rollup/rollup-freebsd-arm64": "4.62.0", + "@rollup/rollup-freebsd-x64": "4.62.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.62.0", + "@rollup/rollup-linux-arm-musleabihf": "4.62.0", + "@rollup/rollup-linux-arm64-gnu": "4.62.0", + "@rollup/rollup-linux-arm64-musl": "4.62.0", + "@rollup/rollup-linux-loong64-gnu": "4.62.0", + "@rollup/rollup-linux-loong64-musl": "4.62.0", + "@rollup/rollup-linux-ppc64-gnu": "4.62.0", + "@rollup/rollup-linux-ppc64-musl": "4.62.0", + "@rollup/rollup-linux-riscv64-gnu": "4.62.0", + "@rollup/rollup-linux-riscv64-musl": "4.62.0", + "@rollup/rollup-linux-s390x-gnu": "4.62.0", + "@rollup/rollup-linux-x64-gnu": "4.62.0", + "@rollup/rollup-linux-x64-musl": "4.62.0", + "@rollup/rollup-openbsd-x64": "4.62.0", + "@rollup/rollup-openharmony-arm64": "4.62.0", + "@rollup/rollup-win32-arm64-msvc": "4.62.0", + "@rollup/rollup-win32-ia32-msvc": "4.62.0", + "@rollup/rollup-win32-x64-gnu": "4.62.0", + "@rollup/rollup-win32-x64-msvc": "4.62.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/typescript": { + "version": "5.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", + "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.38", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.38.tgz", + "integrity": "sha512-vAMKHfImQlYSy0C+PBue4s3ERZ2xGKfgZg5GXAsLInq1dyh2H78ILVP5sK0KPFPVW4kv+OGCIvBEondcjpZp7A==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.38", + "@vue/compiler-sfc": "3.5.38", + "@vue/runtime-dom": "3.5.38", + "@vue/server-renderer": "3.5.38", + "@vue/shared": "3.5.38" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-demi": { + "version": "0.14.10", + "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz", + "integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "vue-demi-fix": "bin/vue-demi-fix.js", + "vue-demi-switch": "bin/vue-demi-switch.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vue/composition-api": "^1.0.0-rc.1", + "vue": "^3.0.0-0 || ^2.6.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "4.6.4", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz", + "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.4" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/vue-tsc": { + "version": "2.2.12", + "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-2.2.12.tgz", + "integrity": "sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.15", + "@vue/language-core": "2.2.12" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + } + } +} diff --git a/example-project/frontend/package.json b/example-project/frontend/package.json new file mode 100644 index 0000000..274fa4d --- /dev/null +++ b/example-project/frontend/package.json @@ -0,0 +1,25 @@ +{ + "name": "consultation-frontend", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc -b && vite build", + "preview": "vite preview" + }, + "dependencies": { + "axios": "^1.7.0", + "element-plus": "^2.9.0", + "pinia": "^2.2.0", + "vue": "^3.5.13", + "vue-router": "^4.3.0" + }, + "devDependencies": { + "@types/node": "^25.9.3", + "@vitejs/plugin-vue": "^5.0.5", + "typescript": "~5.5.0", + "vite": "^5.4.0", + "vue-tsc": "^2.0.0" + } +} diff --git a/example-project/frontend/src/App.vue b/example-project/frontend/src/App.vue new file mode 100644 index 0000000..98240ae --- /dev/null +++ b/example-project/frontend/src/App.vue @@ -0,0 +1,3 @@ + diff --git a/example-project/frontend/src/assets/main.css b/example-project/frontend/src/assets/main.css new file mode 100644 index 0000000..e4e16f0 --- /dev/null +++ b/example-project/frontend/src/assets/main.css @@ -0,0 +1,22 @@ +* { margin: 0; padding: 0; box-sizing: border-box; } +:root { + --primary: #4F46E5; --primary-light: #818CF8; --primary-dark: #3730A3; + --success: #10B981; --warning: #F59E0B; --danger: #EF4444; + --gray-50: #F9FAFB; --gray-100: #F3F4F6; --gray-200: #E5E7EB; + --gray-300: #D1D5DB; --gray-400: #9CA3AF; --gray-500: #6B7280; + --gray-600: #4B5563; --gray-700: #374151; --gray-800: #1F2937; --gray-900: #111827; +} +body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: var(--gray-900); background: var(--gray-50); line-height: 1.6; } +a { color: var(--primary); text-decoration: none; } +button { cursor: pointer; border: none; font-size: inherit; } +.container { max-width: 1200px; margin: 0 auto; padding: 0 1rem; } +.btn { display: inline-flex; align-items: center; justify-content: center; padding: 0.5rem 1rem; border-radius: 0.375rem; font-weight: 500; transition: all 0.2s; } +.btn-primary { background: var(--primary); color: white; } +.btn-primary:hover { background: var(--primary-dark); } +.btn-secondary { background: var(--gray-200); color: var(--gray-700); } +.btn-danger { background: var(--danger); color: white; } +.card { background: white; border-radius: 0.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); padding: 1.5rem; } +.input { width: 100%; padding: 0.5rem 0.75rem; border: 1px solid var(--gray-300); border-radius: 0.375rem; font-size: 0.875rem; } +.input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(79,70,229,0.1); } +.form-group { margin-bottom: 1rem; } +.form-group label { display: block; margin-bottom: 0.25rem; font-weight: 500; font-size: 0.875rem; color: var(--gray-700); } diff --git a/example-project/frontend/src/components/layout/AdminLayout.vue b/example-project/frontend/src/components/layout/AdminLayout.vue new file mode 100644 index 0000000..b8f51c3 --- /dev/null +++ b/example-project/frontend/src/components/layout/AdminLayout.vue @@ -0,0 +1,34 @@ + + + + + diff --git a/example-project/frontend/src/components/layout/AppHeader.vue b/example-project/frontend/src/components/layout/AppHeader.vue new file mode 100644 index 0000000..da3133d --- /dev/null +++ b/example-project/frontend/src/components/layout/AppHeader.vue @@ -0,0 +1,37 @@ + + + + + diff --git a/example-project/frontend/src/components/layout/UserLayout.vue b/example-project/frontend/src/components/layout/UserLayout.vue new file mode 100644 index 0000000..15782c4 --- /dev/null +++ b/example-project/frontend/src/components/layout/UserLayout.vue @@ -0,0 +1,10 @@ + + + diff --git a/example-project/frontend/src/env.d.ts b/example-project/frontend/src/env.d.ts new file mode 100644 index 0000000..b6a7768 --- /dev/null +++ b/example-project/frontend/src/env.d.ts @@ -0,0 +1,6 @@ +/// +declare module '*.vue' { + import type { DefineComponent } from 'vue' + const component: DefineComponent<{}, {}, any> + export default component +} diff --git a/example-project/frontend/src/main.ts b/example-project/frontend/src/main.ts new file mode 100644 index 0000000..6b03443 --- /dev/null +++ b/example-project/frontend/src/main.ts @@ -0,0 +1,13 @@ +import { createApp } from 'vue' +import { createPinia } from 'pinia' +import ElementPlus from 'element-plus' +import 'element-plus/dist/index.css' +import App from './App.vue' +import router from './router' +import './assets/main.css' + +const app = createApp(App) +app.use(createPinia()) +app.use(router) +app.use(ElementPlus) +app.mount('#app') diff --git a/example-project/frontend/src/router/index.ts b/example-project/frontend/src/router/index.ts new file mode 100644 index 0000000..5242bce --- /dev/null +++ b/example-project/frontend/src/router/index.ts @@ -0,0 +1,35 @@ +import { createRouter, createWebHistory } from 'vue-router' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/', name: 'home', component: () => import('@/views/home/HomePage.vue') }, + { path: '/login', name: 'login', component: () => import('@/views/auth/Login.vue') }, + { path: '/register', name: 'register', component: () => import('@/views/auth/Register.vue') }, + { + path: '/user', + component: () => import('@/components/layout/UserLayout.vue'), + children: [ + { path: '', redirect: '/user/dashboard' }, + { path: 'dashboard', component: () => import('@/views/user/Dashboard.vue') }, + { path: 'appointments', component: () => import('@/views/user/MyAppointments.vue') }, + { path: 'book', component: () => import('@/views/user/BookAppointment.vue') }, + { path: 'profile', component: () => import('@/views/user/Profile.vue') }, + ], + }, + { + path: '/admin', + component: () => import('@/components/layout/AdminLayout.vue'), + children: [ + { path: '', redirect: '/admin/dashboard' }, + { path: 'dashboard', component: () => import('@/views/admin/Dashboard.vue') }, + { path: 'appointments', component: () => import('@/views/admin/Appointments.vue') }, + { path: 'consultants', component: () => import('@/views/admin/Consultants.vue') }, + { path: 'users', component: () => import('@/views/admin/Users.vue') }, + { path: 'branches', component: () => import('@/views/admin/Branches.vue') }, + ], + }, + ], +}) + +export default router diff --git a/example-project/frontend/src/stores/auth.ts b/example-project/frontend/src/stores/auth.ts new file mode 100644 index 0000000..f7f646a --- /dev/null +++ b/example-project/frontend/src/stores/auth.ts @@ -0,0 +1,35 @@ +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' +import type { AuthResponse, User } from '@/types' +import http from '@/utils/request' + +export const useAuthStore = defineStore('auth', () => { + const token = ref(localStorage.getItem('token') || '') + const user = ref(JSON.parse(localStorage.getItem('user') || 'null')) + const isLoggedIn = computed(() => !!token.value) + const isAdmin = computed(() => user.value?.role === 'ROLE_ADMIN') + + function setAuth(t: string, u: User) { + token.value = t; user.value = u + localStorage.setItem('token', t); localStorage.setItem('user', JSON.stringify(u)) + } + + async function login(email: string, password: string) { + const r = await http.post('/auth/login', { email, password }) + setAuth(r.data.token, r.data.user) + return r.data + } + + async function register(email: string, password: string, name: string, phone?: string) { + const r = await http.post('/auth/register', { email, password, name, phone }) + setAuth(r.data.token, r.data.user) + return r.data + } + + function logout() { + token.value = ''; user.value = null + localStorage.removeItem('token'); localStorage.removeItem('user') + } + + return { token, user, isLoggedIn, isAdmin, login, register, logout } +}) diff --git a/example-project/frontend/src/types/index.ts b/example-project/frontend/src/types/index.ts new file mode 100644 index 0000000..e9540c3 --- /dev/null +++ b/example-project/frontend/src/types/index.ts @@ -0,0 +1,17 @@ +export interface User { + id: string; email: string; name: string; phone: string; role: string; status: string +} +export interface AuthResponse { token: string; user: User } +export interface Appointment { + id: string; userId: string; consultantId: string; branchId: string; + appointmentDate: string; startTime: string; endTime: string; + durationMinutes: number; status: string; note: string; cancelReason: string +} +export interface Consultant { + id: string; name: string; title: string; bio: string; specialties: string; + avatar: string; branchId: string; status: string; sortOrder: number +} +export interface Branch { + id: string; name: string; address: string; phone: string; status: string +} +export interface TimeSlot { startTime: string; endTime: string } diff --git a/example-project/frontend/src/utils/date.ts b/example-project/frontend/src/utils/date.ts new file mode 100644 index 0000000..0891402 --- /dev/null +++ b/example-project/frontend/src/utils/date.ts @@ -0,0 +1,9 @@ +export function getWeekDates(): string[] { + const dates: string[] = [] + const today = new Date() + for (let i = 0; i < 7; i++) { + const d = new Date(today); d.setDate(d.getDate() + i) + dates.push(d.toISOString().split('T')[0]) + } + return dates +} diff --git a/example-project/frontend/src/utils/request.ts b/example-project/frontend/src/utils/request.ts new file mode 100644 index 0000000..a3e8981 --- /dev/null +++ b/example-project/frontend/src/utils/request.ts @@ -0,0 +1,23 @@ +import axios from 'axios' + +const http = axios.create({ + baseURL: '/api/v1', + timeout: 15000, + headers: { 'Content-Type': 'application/json' }, +}) + +http.interceptors.request.use(cfg => { + const token = localStorage.getItem('token') + if (token) cfg.headers.Authorization = `Bearer ${token}` + return cfg +}) + +http.interceptors.response.use( + r => r, + e => { + if (e.response?.status === 401) { localStorage.removeItem('token'); localStorage.removeItem('user'); window.location.href = '/login' } + return Promise.reject(e) + } +) + +export default http diff --git a/example-project/frontend/src/views/admin/Appointments.vue b/example-project/frontend/src/views/admin/Appointments.vue new file mode 100644 index 0000000..f7075be --- /dev/null +++ b/example-project/frontend/src/views/admin/Appointments.vue @@ -0,0 +1,31 @@ + + + + + diff --git a/example-project/frontend/src/views/admin/Branches.vue b/example-project/frontend/src/views/admin/Branches.vue new file mode 100644 index 0000000..383c6b4 --- /dev/null +++ b/example-project/frontend/src/views/admin/Branches.vue @@ -0,0 +1,65 @@ + + + + + diff --git a/example-project/frontend/src/views/admin/Consultants.vue b/example-project/frontend/src/views/admin/Consultants.vue new file mode 100644 index 0000000..673c01e --- /dev/null +++ b/example-project/frontend/src/views/admin/Consultants.vue @@ -0,0 +1,29 @@ + + + + + diff --git a/example-project/frontend/src/views/admin/Dashboard.vue b/example-project/frontend/src/views/admin/Dashboard.vue new file mode 100644 index 0000000..edc99eb --- /dev/null +++ b/example-project/frontend/src/views/admin/Dashboard.vue @@ -0,0 +1,28 @@ + + + + + diff --git a/example-project/frontend/src/views/admin/Users.vue b/example-project/frontend/src/views/admin/Users.vue new file mode 100644 index 0000000..b5e67ea --- /dev/null +++ b/example-project/frontend/src/views/admin/Users.vue @@ -0,0 +1,32 @@ + + + + + diff --git a/example-project/frontend/src/views/auth/Login.vue b/example-project/frontend/src/views/auth/Login.vue new file mode 100644 index 0000000..c9835a4 --- /dev/null +++ b/example-project/frontend/src/views/auth/Login.vue @@ -0,0 +1,46 @@ + + + + + diff --git a/example-project/frontend/src/views/auth/Register.vue b/example-project/frontend/src/views/auth/Register.vue new file mode 100644 index 0000000..8cc782f --- /dev/null +++ b/example-project/frontend/src/views/auth/Register.vue @@ -0,0 +1,44 @@ + + + + + diff --git a/example-project/frontend/src/views/home/HomePage.vue b/example-project/frontend/src/views/home/HomePage.vue new file mode 100644 index 0000000..8a79633 --- /dev/null +++ b/example-project/frontend/src/views/home/HomePage.vue @@ -0,0 +1,39 @@ + + + + + diff --git a/example-project/frontend/src/views/user/BookAppointment.vue b/example-project/frontend/src/views/user/BookAppointment.vue new file mode 100644 index 0000000..34124c4 --- /dev/null +++ b/example-project/frontend/src/views/user/BookAppointment.vue @@ -0,0 +1,96 @@ + + + + + diff --git a/example-project/frontend/src/views/user/Dashboard.vue b/example-project/frontend/src/views/user/Dashboard.vue new file mode 100644 index 0000000..4cc3cfa --- /dev/null +++ b/example-project/frontend/src/views/user/Dashboard.vue @@ -0,0 +1,41 @@ + + + + + diff --git a/example-project/frontend/src/views/user/MyAppointments.vue b/example-project/frontend/src/views/user/MyAppointments.vue new file mode 100644 index 0000000..6e723a9 --- /dev/null +++ b/example-project/frontend/src/views/user/MyAppointments.vue @@ -0,0 +1,69 @@ + + + + + diff --git a/example-project/frontend/src/views/user/Profile.vue b/example-project/frontend/src/views/user/Profile.vue new file mode 100644 index 0000000..61e2b69 --- /dev/null +++ b/example-project/frontend/src/views/user/Profile.vue @@ -0,0 +1,56 @@ + + + + + diff --git a/example-project/frontend/tsconfig.app.json b/example-project/frontend/tsconfig.app.json new file mode 100644 index 0000000..330665d --- /dev/null +++ b/example-project/frontend/tsconfig.app.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "composite": true, + "target": "ES2020", + "module": "ESNext", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "preserve", + "strict": true, + "paths": { "@/*": ["./src/*"] } + }, + "include": ["src/**/*.ts", "src/**/*.vue"] +} diff --git a/example-project/frontend/tsconfig.json b/example-project/frontend/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/example-project/frontend/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/example-project/frontend/tsconfig.node.json b/example-project/frontend/tsconfig.node.json new file mode 100644 index 0000000..d157835 --- /dev/null +++ b/example-project/frontend/tsconfig.node.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "noEmit": true, + "types": ["node"] + }, + "include": ["vite.config.ts"] +} diff --git a/example-project/frontend/vite.config.ts b/example-project/frontend/vite.config.ts new file mode 100644 index 0000000..f39545c --- /dev/null +++ b/example-project/frontend/vite.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import { resolve } from 'path' + +export default defineConfig({ + plugins: [vue()], + resolve: { alias: { '@': resolve(__dirname, 'src') } }, + server: { port: 5173, proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true } } }, +}) diff --git a/example-project/opencode.jsonc b/example-project/opencode.jsonc new file mode 100644 index 0000000..69e15c9 --- /dev/null +++ b/example-project/opencode.jsonc @@ -0,0 +1,7 @@ +{ + "$schema": "https://opencode.ai/config.json", + + "skills": { + "paths": [".agent/skills"] + } +} diff --git a/example-project/overnight-runner.yaml b/example-project/overnight-runner.yaml new file mode 100644 index 0000000..f2d4124 --- /dev/null +++ b/example-project/overnight-runner.yaml @@ -0,0 +1,38 @@ +# overnight-runner 运行配置(项目级,全队列共享) +# +# 这里回答的是"这个项目怎么跑":agent 是谁 / 看门狗多严 / 决策怎么处理。 +# +# "跑哪些任务"不在这里 —— 队列定义在 +# .overnight-runner/queue/<队列名>/queue.yaml +# 用 `overnight-runner --queue <名字> add docs/plans/xxx.md` 追加。 +runner: + agent: + command: opencode + args: + - run + - "--dangerously-skip-permissions" + env: {} + watchdog: + maxRetries: 2 + backoffSec: 60 + idleTimeoutSec: 1800 + totalTimeoutSec: 7200 + killGraceSec: 15 + # 决策策略:agent 抛 "QUESTION: <问题>" 时怎么办 + decision: + # attended —— 有人值守(白天):打断 agent,TUI 弹决策窗口问你; + # timeoutSec 内没回答就按默认决策规则自动决策 + # unattended —— 无人值守(夜里):不打断 agent,直接按默认决策规则决策 + # 临时切换:overnight-runner run --mode unattended + mode: attended + timeoutSec: 600 + resume: session + outputFormat: json + sessionArgs: ["--session", "{session}"] + + state: + dir: .overnight-runner + workdir: . + ui: + refreshHz: 8 + logTail: 400 diff --git a/example-project/tools/overnight-runner/overnight-runner b/example-project/tools/overnight-runner/overnight-runner new file mode 100755 index 0000000..c3b0bf5 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight-runner @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# overnight-runner 启动脚本(由 install.sh 生成) +set -euo pipefail +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PYTHONPATH="$DIR${PYTHONPATH:+:$PYTHONPATH}" export PYTHONPATH +exec "python3" -m overnight_runner "$@" diff --git a/example-project/tools/overnight-runner/overnight-runner.cmd b/example-project/tools/overnight-runner/overnight-runner.cmd new file mode 100644 index 0000000..e561da9 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight-runner.cmd @@ -0,0 +1,6 @@ +@echo off +REM overnight-runner 启动脚本(Windows,由 install.sh 生成) +setlocal +set "DIR=%~dp0" +set "PYTHONPATH=%DIR%;%PYTHONPATH%" +"python3" -m overnight_runner %* diff --git a/example-project/tools/overnight-runner/overnight_runner/__init__.py b/example-project/tools/overnight-runner/overnight_runner/__init__.py new file mode 100644 index 0000000..e1203da --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/__init__.py @@ -0,0 +1,5 @@ +"""overnight-runner:把一串 plan 交给 coding agent 无人值守地跑一晚上。""" + +__version__ = "0.1.0" + +APP_NAME = "overnight-runner" diff --git a/example-project/tools/overnight-runner/overnight_runner/__main__.py b/example-project/tools/overnight-runner/overnight_runner/__main__.py new file mode 100644 index 0000000..bfdcd0c --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/__main__.py @@ -0,0 +1,4 @@ +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/example-project/tools/overnight-runner/overnight_runner/agent.py b/example-project/tools/overnight-runner/overnight_runner/agent.py new file mode 100644 index 0000000..29edfbe --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/agent.py @@ -0,0 +1,301 @@ +"""调用 coding agent 子进程,实时收集输出。""" + +from __future__ import annotations + +import json +import os +import re +import signal +import subprocess +import sys +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable + +from .util import is_windows + +LineCallback = Callable[[str], None] + + +def extract_session_id(line: str, pattern: str) -> str: + """用正则从 agent 输出里抓 session id(text 模式的兜底)。""" + if not pattern: + return "" + try: + m = re.search(pattern, line) + except re.error: + return "" + return m.group(1) if m else "" + + +def _render_tool(part: dict) -> list[str]: + """把一次工具调用渲染成几行可读文本。""" + state = part.get("state") or {} + inp = state.get("input") or {} + tool = part.get("tool") or "tool" + title = state.get("title") or "" + cmd = inp.get("command") or inp.get("filePath") or inp.get("path") or "" + output = state.get("output") or "" + + lines: list[str] = [] + head = title or cmd or tool + lines.append(f"$ {head}") + if cmd and cmd != head: + lines.append(f" {cmd}") + for ln in str(output).splitlines(): + lines.append(ln) + return lines + + +def parse_agent_output(line: str, output_format: str) -> tuple[list[str], str]: + """把 agent 的一行原始输出解析成 (显示用的行列表, session_id)。 + + - `text` 模式:原样返回,session id 交给正则抓 + - `json` 模式:解析事件 —— `part.type=text` 取文本,`part.type=tool` 取工具摘要, + session id 从事件顶层的 `sessionID` 拿 + """ + if output_format != "json": + return [line], "" + + s = line.strip() + if not (s.startswith("{") and s.endswith("}")): + # 不是 json(agent 的 stderr 混进来了)—— 原样透传 + return [line], "" + + try: + obj = json.loads(s) + except json.JSONDecodeError: + return [line], "" + + if not isinstance(obj, dict): + return [], "" + + session_id = str(obj.get("sessionID") or "") + part = obj.get("part") or {} + ptype = part.get("type") + + if ptype == "text": + text = str(part.get("text") or "") + return (text.splitlines() or [""]), session_id + if ptype == "tool": + return _render_tool(part), session_id + return [], session_id + + + +@dataclass +class AgentResult: + exit_code: int | None = None + timed_out: bool = False + timeout_kind: str = "" # idle | total | "" + killed: bool = False + error: str = "" + duration_sec: float = 0.0 + + +@dataclass +class AgentProcess: + """一次 agent 调用。""" + + command: list[str] + cwd: Path + env: dict[str, str] = field(default_factory=dict) + on_line: LineCallback | None = None + idle_timeout_sec: int = 1800 + total_timeout_sec: int = 7200 + kill_grace_sec: int = 15 + output_format: str = "text" + session_pattern: str = "" + + _proc: subprocess.Popen | None = field(default=None, init=False, repr=False) + _thread: threading.Thread | None = field(default=None, init=False, repr=False) + _last_output_at: float = field(default_factory=time.monotonic, init=False) + _started_at: float = field(default_factory=time.monotonic, init=False) + _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) + _session_id: str = field(default="", init=False) + + # ── 生命周期 ──────────────────────────────────────────────────── + def start(self) -> None: + env = os.environ.copy() + env.update(self.env) + env.setdefault("PYTHONIOENCODING", "utf-8") + # 让 agent 认得非交互终端 + env.setdefault("CI", "1") + + kwargs: dict = dict( + cwd=str(self.cwd), + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, + text=True, + encoding="utf-8", + errors="replace", + bufsize=1, + ) + if is_windows(): + kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP + else: + kwargs["start_new_session"] = True + + self._started_at = time.monotonic() + self._last_output_at = self._started_at + self._proc = subprocess.Popen(self.command, **kwargs) + self._thread = threading.Thread(target=self._pump, name="agent-reader", daemon=True) + self._thread.start() + + def _pump(self) -> None: + proc = self._proc + if proc is None or proc.stdout is None: + return + try: + for raw in proc.stdout: + line = raw.rstrip("\n").rstrip("\r") + with self._lock: + self._last_output_at = time.monotonic() + for out in self._expand(line): + if self.on_line is not None: + try: + self.on_line(out) + except Exception: # noqa: BLE001 - UI 回调不该拖垮 agent + pass + except (ValueError, OSError): + pass + finally: + try: + proc.stdout.close() + except (OSError, AttributeError): + pass + + def _expand(self, line: str) -> list[str]: + """把一行原始输出展开成若干行可读文本,并顺手抓 session id。""" + lines, session_id = parse_agent_output(line, self.output_format) + if session_id: + self._remember_session(session_id) + elif self.output_format != "json" and self.session_pattern: + found = extract_session_id(line, self.session_pattern) + if found: + self._remember_session(found) + return lines + + def _remember_session(self, session_id: str) -> None: + with self._lock: + if not self._session_id: + self._session_id = session_id + + @property + def session_id(self) -> str: + """抓到的 agent session id(用于 `--session` 续跑)。""" + with self._lock: + return self._session_id + + @property + def alive(self) -> bool: + return self._proc is not None and self._proc.poll() is None + + @property + def idle_seconds(self) -> float: + with self._lock: + return time.monotonic() - self._last_output_at + + @property + def total_seconds(self) -> float: + return time.monotonic() - self._started_at + + def poll(self) -> int | None: + return self._proc.poll() if self._proc else None + + def wait(self, timeout: float | None = None) -> int | None: + if self._proc is None: + return None + try: + return self._proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + return None + + # ── 超时判定 ──────────────────────────────────────────────────── + def check_timeout(self) -> tuple[bool, str]: + """返回 (是否超时, 超时类型)。""" + if self.total_timeout_sec and self.total_seconds > self.total_timeout_sec: + return True, "total" + if self.idle_timeout_sec and self.idle_seconds > self.idle_timeout_sec: + return True, "idle" + return False, "" + + # ── 终止 ──────────────────────────────────────────────────────── + def terminate(self) -> bool: + """优雅终止:先 TERM,宽限期后 KILL。返回是否真的杀掉了。""" + proc = self._proc + if proc is None or proc.poll() is not None: + return False + + killed = False + try: + if is_windows(): + proc.send_signal(signal.CTRL_BREAK_EVENT) + else: + os.killpg(os.getpgid(proc.pid), signal.SIGTERM) + killed = True + except (ProcessLookupError, PermissionError, OSError): + try: + proc.terminate() + killed = True + except OSError: + pass + + try: + proc.wait(timeout=self.kill_grace_sec) + except subprocess.TimeoutExpired: + try: + if is_windows(): + proc.kill() + else: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except (ProcessLookupError, PermissionError, OSError): + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + return killed + + +def build_command( + agent_command: str, + agent_args: list[str], + prompt: str, + prompt_file: Path | None = None, +) -> list[str]: + """组装 agent 命令行。 + + 提示词优先通过文件传(避免超长命令行在 Windows 上炸掉); + 只有当 agent 明确支持时才用 stdin。 + """ + cmd = [agent_command, *agent_args] + if prompt_file is not None: + cmd += ["--prompt-file", str(prompt_file)] + else: + cmd.append(prompt) + return cmd + + +def check_agent_available(agent_command: str) -> tuple[bool, str]: + """检查 agent 命令是否可用。""" + import shutil + + if shutil.which(agent_command): + return True, "" + # 允许写成 "python -m foo" 这种形式,取第一段做 which + first = agent_command.split()[0] if agent_command.split() else agent_command + if shutil.which(first): + return True, "" + return False, f"找不到 agent 命令: {agent_command}" + + +def platform_hint() -> str: + return f"{sys.platform} / {'Windows' if is_windows() else 'POSIX'}" diff --git a/example-project/tools/overnight-runner/overnight_runner/cli.py b/example-project/tools/overnight-runner/overnight_runner/cli.py new file mode 100644 index 0000000..3b48e84 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/cli.py @@ -0,0 +1,439 @@ +"""命令行入口。 + +子命令: + init 初始化配置文件(队列 + 项目配置) + add 往队列里追加 plan + list 列出队列 + status 查看运行状态 + decisions 查看决策记录 + queues 列出所有队列 + run 启动(默认分屏面板;--headless 无界面) + +所有子命令都支持全局参数 `--queue `(默认 `default`)。 +""" + +from __future__ import annotations + +import argparse +import json +import sys +import threading +from pathlib import Path + +from . import __version__ +from .config import ( + DECISION_MODE_ATTENDED, + DECISION_MODE_UNATTENDED, + DECISION_MODES, + DEFAULT_AGENT_ARGS, + DEFAULT_AGENT_COMMAND, + DEFAULT_PROJECT_PROMPT, + DEFAULT_QUEUE_NAME, + ProjectConfig, + QueuePaths, + load_project_config, + load_runner_config, + migrate_legacy_queue, + queue_config_path, + queue_names, + queue_paths, + save_project_config, + save_runner_config, +) +from .controller import RunnerController +from .decisions import DecisionLog +from .queue import ( + PENDING, + Queue, + build_task, + load_queue, + load_queue_defs, + save_queue_defs, + save_state, +) +from .util import QueueLock, StopFlag, fmt_duration, fmt_ts, now + + +def _project_root(args) -> Path: + return Path(args.project).expanduser().resolve() + + +def _queue_paths(args) -> QueuePaths: + """解析本次命令要操作的队列(顺带做老布局迁移)。""" + root = _project_root(args) + note = migrate_legacy_queue(root) + if note: + print(f"已迁移旧队列布局 → .overnight-runner/queue/{DEFAULT_QUEUE_NAME}/({note})") + name = getattr(args, "queue", DEFAULT_QUEUE_NAME) or DEFAULT_QUEUE_NAME + try: + return queue_paths(root, name) + except ValueError as exc: + print(f"错误: {exc}", file=sys.stderr) + raise SystemExit(2) + + +def resolve_decision_mode( + cfg, mode_override: str | None = None, headless: bool = False +) -> str: + """决定本次运行用哪个决策模式。 + + 优先级:headless(强制无人值守)> 命令行 --mode > 配置文件。 + """ + if headless: + return DECISION_MODE_UNATTENDED + if mode_override: + return mode_override + return cfg.decision.mode + + +# ── init ──────────────────────────────────────────────────────────── +def cmd_init(args) -> int: + root = _project_root(args) + root.mkdir(parents=True, exist_ok=True) + paths = _queue_paths(args) + + qpath = queue_config_path(root) + if not qpath.exists(): + cfg = load_runner_config(root) + cfg.agent_command = args.agent or cfg.agent_command + cfg.agent_args = list(args.agent_args) if args.agent_args else cfg.agent_args + save_runner_config(root, cfg) + print(f"已创建运行配置: {qpath}") + else: + print(f"运行配置已存在,保持不变: {qpath}") + + if not paths.config.exists(): + paths.dir.mkdir(parents=True, exist_ok=True) + save_queue_defs(paths, Queue()) + print(f"已创建队列: {paths.name} → {paths.config}") + else: + print(f"队列已存在,保持不变: {paths.config}") + + ppath = root / ".overnight-runner" / "project.yaml" + if not ppath.exists(): + pcfg = ProjectConfig(name=root.name) + pcfg.agent_command = args.agent or DEFAULT_AGENT_COMMAND + pcfg.agent_args = list(args.agent_args) if args.agent_args else list(DEFAULT_AGENT_ARGS) + pcfg.default_prompt = DEFAULT_PROJECT_PROMPT + save_project_config(root, pcfg) + print(f"已创建项目配置: {ppath}") + else: + print(f"项目配置已存在,保持不变: {ppath}") + + print() + print("下一步:") + print(f" 1) 编辑 {paths.config} 填入 queue(plan 用相对项目根的路径)") + print(f" 2) 编辑 {ppath} 配默认提示词与默认决策") + print(f" 3) 运行: overnight-runner --queue {paths.name} run") + return 0 + + +# ── add ───────────────────────────────────────────────────────────── +def cmd_add(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + cfg = load_runner_config(root) + queue = load_queue(paths, load_queue_defs(paths)) + + try: + task = build_task( + root, + args.plan, + prompt=args.prompt or "", + role=args.role or "", + priority=args.priority, + existing_ids={t.id for t in queue.tasks}, + ) + queue.add(task) + except ValueError as exc: + print(f"错误: {exc}", file=sys.stderr) + return 1 + + save_queue_defs(paths, queue) + print(f"已加入队列 [{paths.name}]: {task.id} → {task.plan}") + return 0 + + +# ── list ──────────────────────────────────────────────────────────── +def cmd_list(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + queue = load_queue(paths, load_queue_defs(paths)) + + print(f"队列: {paths.name}") + if not len(queue): + print("队列为空。用 `overnight-runner add ` 追加。") + return 0 + + print(f"{'ID':<32} {'状态':<8} {'次':<3} {'耗时':<8} PLAN") + print("-" * 100) + for t in queue.tasks: + print( + f"{t.id:<32} {t.status:<8} {t.attempts:<3} " + f"{fmt_duration(t.duration_sec):<8} {t.plan}" + ) + return 0 + + +# ── status ────────────────────────────────────────────────────────── +def cmd_status(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + cfg = load_runner_config(root) + queue = load_queue(paths, load_queue_defs(paths)) + stats = queue.stats() + + print(f"项目: {root}") + print(f"队列: {paths.name}") + print(f"agent: {cfg.agent_command} {' '.join(cfg.agent_args)}") + print(f"决策: {cfg.decision.mode}({DECISION_MODE_ATTENDED}=有人值守 / " + f"{DECISION_MODE_UNATTENDED}=无人值守)· 等待 {cfg.decision.timeout_sec}s") + print(f"看门狗: 重试 {cfg.watchdog.max_retries} 次 · 退避 {cfg.watchdog.backoff_sec}s · " + f"空闲超时 {cfg.watchdog.idle_timeout_sec}s · 总超时 {cfg.watchdog.total_timeout_sec}s") + print() + for k in ("pending", "running", "retrying", "success", "failed", "blocked", "stopped"): + if stats.get(k): + print(f" {k:<10} {stats[k]}") + print() + for t in queue.tasks: + if t.status in ("failed", "blocked"): + print(f" ✘ {t.id}: {t.last_error}") + return 0 + + +# ── decisions ─────────────────────────────────────────────────────── +def cmd_decisions(args) -> int: + paths = _queue_paths(args) + log = DecisionLog(paths.decisions) + records = log.load() + + if not records: + print(f"队列 [{paths.name}] 还没有决策记录。") + return 0 + + if args.json: + print(json.dumps(records, ensure_ascii=False, indent=2)) + return 0 + + print(f"队列: {paths.name}") + print(f"{'时间':<20} {'任务':<28} {'来源':<9} 问题 → 答案") + print("-" * 110) + for r in records: + print( + f"{str(r.get('at',''))[:19]:<20} {str(r.get('task_id',''))[:27]:<28} " + f"{str(r.get('source','')):<9} {r.get('question','')} → {r.get('answer','')}" + ) + return 0 + + +# ── queues ────────────────────────────────────────────────────────── +def cmd_queues(args) -> int: + root = _project_root(args) + note = migrate_legacy_queue(root) + if note: + print(f"已迁移旧队列布局 → .overnight-runner/queue/{DEFAULT_QUEUE_NAME}/({note})") + names = queue_names(root) + if not names: + print("还没有任何队列。用 `overnight-runner init` 建一条。") + return 0 + + print(f"{'队列':<16} {'任务':<6} {'待跑':<6} {'运行':<6} {'成功':<6} {'失败':<6} 最后活动") + print("-" * 78) + for name in names: + paths = queue_paths(root, name) + queue = load_queue(paths, load_queue_defs(paths)) + stats = queue.stats() + last = _last_activity(queue) + print( + f"{name:<16} {len(queue):<6} {stats.get(PENDING, 0):<6} " + f"{stats.get('running', 0):<6} {stats.get('success', 0):<6} " + f"{stats.get('failed', 0):<6} {last}" + ) + return 0 + + +def _last_activity(queue: Queue) -> str: + times = [t.finished_at or t.started_at for t in queue.tasks] + times = [t for t in times if t is not None] + if not times: + return "-" + return fmt_ts(max(times)) + + +# ── run ───────────────────────────────────────────────────────────── +def cmd_run(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + cfg = load_runner_config(root) + project_cfg = load_project_config(root) + queue = load_queue(paths, load_queue_defs(paths)) + + # 决策模式:命令行优先;headless 强制无人值守(没人看面板,不能卡在等决策上) + cfg.decision.mode = resolve_decision_mode( + cfg, getattr(args, "mode", None), args.headless + ) + + if getattr(args, "retry_failed", False): + reset = 0 + for t in queue.tasks: + if t.status in ("failed", "blocked", "stopped"): + t.status = PENDING + t.attempts = 0 + t.last_error = "" + t.exit_code = None + t.finished_at = None + t.summary = "" + reset += 1 + if reset: + save_state(paths, queue) + print(f"已重置 {reset} 个失败/阻塞任务。") + + lock = QueueLock(paths.lock) + ok, err = lock.acquire() + if not ok: + print(f"错误: {err}(同一条队列不能同时跑两个 runner)", file=sys.stderr) + return 2 + + stop = StopFlag() + controller = RunnerController(root, cfg, project_cfg, queue, paths, stop=stop) + + try: + if args.headless: + return _run_headless(controller, queue, paths, stop, args) + + try: + from .ui import RunnerUI + except ImportError as exc: # pragma: no cover - 只在环境被破坏时触发 + print(f"无法启动面板: {exc}", file=sys.stderr) + print("也可以用 --headless 无界面运行。", file=sys.stderr) + return 2 + + ui = RunnerUI(controller, queue, cfg, root, paths) + + worker = threading.Thread(target=controller.run_forever, name="runner", daemon=True) + worker.start() + heartbeat = threading.Thread(target=_heartbeat, args=(lock, stop), daemon=True) + heartbeat.start() + + try: + ui.run() + finally: + stop.set() + worker.join(timeout=10) + finally: + lock.release() + + save_state(paths, queue) + return 0 + + +def _heartbeat(lock: QueueLock, stop: StopFlag) -> None: + """定期更新锁的心跳(长跑时用来识别 stale 锁)。""" + while not stop.is_set(): + lock.touch() + stop.wait(timeout=15) + + +def _run_headless(controller, queue, paths, stop, args) -> int: + """无界面模式:直接跑,输出到 stdout。适合 CI / 脚本。""" + def on_event(kind: str, task) -> None: + if task is not None: + print(f"[{fmt_ts(now())}] {kind:<16} {task.id} {task.plan}") + else: + print(f"[{fmt_ts(now())}] {kind}") + + def on_log(line: str) -> None: + if args.verbose: + print(f" {line}") + + controller.on_event = on_event + controller.on_log = on_log + + controller.run_forever() + save_state(paths, queue) + + stats = queue.stats() + failed = [t for t in queue.tasks if t.status in ("failed", "blocked")] + print() + print(controller.snapshot()) + if failed: + print() + print("失败任务:") + for t in failed: + print(f" ✘ {t.id}: {t.last_error}") + return 1 if failed else 0 + + +# ── 参数解析 ──────────────────────────────────────────────────────── +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + prog="overnight-runner", + description="把一串 plan 交给 coding agent 无人值守地跑", + ) + p.add_argument("--version", action="version", version=f"overnight-runner {__version__}") + p.add_argument("--project", default=".", help="项目根目录(默认当前目录)") + p.add_argument( + "--queue", + default=DEFAULT_QUEUE_NAME, + help=f"队列名(默认 {DEFAULT_QUEUE_NAME})", + ) + sub = p.add_subparsers(dest="command") + + s = sub.add_parser("init", help="初始化配置文件") + s.add_argument("--agent", help="coding agent 命令,如 opencode / claude / codex") + s.add_argument("--agent-args", nargs="*", help="agent 参数,默认 run") + s.set_defaults(func=cmd_init) + + s = sub.add_parser("add", help="往队列追加 plan") + s.add_argument("plan", help="plan 文件路径(相对项目根或绝对路径)") + s.add_argument("--prompt", default="", help="补充要求") + s.add_argument("--role", default="", help="角色标签 BA / DEV / QA") + s.add_argument("--priority", type=int, default=100, help="优先级,数字小的先跑") + s.set_defaults(func=cmd_add) + + s = sub.add_parser("list", help="列出队列") + s.set_defaults(func=cmd_list) + + s = sub.add_parser("status", help="查看运行状态") + s.set_defaults(func=cmd_status) + + s = sub.add_parser("decisions", help="查看决策记录") + s.add_argument("--json", action="store_true", help="输出 JSON") + s.set_defaults(func=cmd_decisions) + + s = sub.add_parser("queues", help="列出所有队列") + s.set_defaults(func=cmd_queues) + + s = sub.add_parser("run", help="启动(默认分屏面板;--headless 无界面)") + s.add_argument("--headless", action="store_true", help="无界面模式") + s.add_argument("--verbose", action="store_true", help="headless 模式下打印 agent 输出") + s.add_argument( + "--retry-failed", + action="store_true", + help="把失败/阻塞的任务重置为待跑", + ) + s.add_argument( + "--mode", + choices=list(DECISION_MODES), + default=None, + help=( + f"决策模式:{DECISION_MODE_ATTENDED}=有人值守(弹窗问人," + f"超时自动决策)/ {DECISION_MODE_UNATTENDED}=无人值守(直接决策)" + ), + ) + s.set_defaults(func=cmd_run) + + return p + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + if not getattr(args, "func", None): + parser.print_help() + return 2 + return args.func(args) + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/example-project/tools/overnight-runner/overnight_runner/config.py b/example-project/tools/overnight-runner/overnight_runner/config.py new file mode 100644 index 0000000..ff4d6fc --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/config.py @@ -0,0 +1,534 @@ +"""配置加载:队列配置(overnight-runner.yaml)与项目配置(.overnight-runner/project.yaml)。 + +配置分三层: + +- **runner 级**:`overnight-runner.yaml` —— agent 命令、看门狗、UI、决策策略(项目共享) +- **project 级**:`.overnight-runner/project.yaml` —— 默认提示词与默认决策规则(全队列共享) +- **queue 级**:`.overnight-runner/queue//queue.yaml` —— 队列里的任务列表(每条队列一份) +""" + +from __future__ import annotations + +import re +import shutil +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from . import yaml_lite as yaml + +from .util import atomic_write + +QUEUE_CONFIG_NAME = "overnight-runner.yaml" +PROJECT_DIR_NAME = ".overnight-runner" +PROJECT_CONFIG_NAME = "project.yaml" + +# 多队列:每条队列在 .overnight-runner/queue// 下有一份独立目录 +QUEUE_DIR_NAME = "queue" +DEFAULT_QUEUE_NAME = "default" +QUEUE_FILE_NAME = "queue.yaml" +STATE_FILE_NAME = "state.json" +LOGS_DIR_NAME = "logs" +DECISIONS_FILE_NAME = "decisions.jsonl" +LOCK_FILE_NAME = ".lock" + +DEFAULT_AGENT_COMMAND = "opencode" +DEFAULT_AGENT_ARGS: list[str] = ["run"] + +# 决策模式:attended = 有人值守(弹窗问人);unattended = 无人值守(直接决策) +DECISION_MODE_ATTENDED = "attended" +DECISION_MODE_UNATTENDED = "unattended" +DECISION_MODES = (DECISION_MODE_ATTENDED, DECISION_MODE_UNATTENDED) + +# 队列名白名单:不允许路径穿越 +QUEUE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + + + +# ── 项目配置 ──────────────────────────────────────────────────────── +@dataclass +class DecisionRule: + """一条默认决策:命中问题类别就用预设答案,并且记一笔。""" + + id: str + question: str = "" + match: str = "" + answer: str = "" + enabled: bool = True + + def describe(self) -> str: + return f"{self.id}: {self.question or self.match} → {self.answer}" + + +@dataclass +class ProjectConfig: + name: str = "" + agent_command: str = DEFAULT_AGENT_COMMAND + agent_args: list[str] = field(default_factory=lambda: list(DEFAULT_AGENT_ARGS)) + agent_env: dict[str, str] = field(default_factory=dict) + default_prompt: str = "" + decisions: list[DecisionRule] = field(default_factory=list) + on_unknown_decision: str = "跳过并记录到决策日志" + source_path: Path | None = None + + def decision_text(self) -> str: + if not self.decisions: + return "" + lines = [f"- [{d.id}] {d.question or d.match} → {d.answer}" for d in self.decisions] + return "\n".join(lines) + + def to_yaml(self) -> str: + data = { + "project": { + "name": self.name, + "agent": { + "command": self.agent_command, + "args": self.agent_args, + "env": self.agent_env, + }, + }, + "default": { + "prompt": self.default_prompt, + "onUnknownDecision": self.on_unknown_decision, + }, + "decisions": [ + { + "id": d.id, + "question": d.question, + "match": d.match, + "answer": d.answer, + "enabled": d.enabled, + } + for d in self.decisions + ], + } + return yaml.dumps(data) + + +DEFAULT_PROJECT_PROMPT = """\ +你在无人值守模式下工作,不要停下来等待人工确认。 + +按下面的方案执行,遇到需要决策的问题,按"默认决策"处理: +{{DECISIONS}} + +{{PLAN}} + +执行要求: +1. 每做出一个决策,输出一行:DECISION: <问题> → <决策> +2. 全部完成后输出一行:DONE: <一句话总结> +3. 如果无法继续,输出一行:BLOCKED: <原因> +""" + + +def load_project_config(project_root: Path) -> ProjectConfig: + path = project_root / PROJECT_DIR_NAME / PROJECT_CONFIG_NAME + cfg = ProjectConfig(source_path=path) + if not path.exists(): + cfg.default_prompt = DEFAULT_PROJECT_PROMPT + return cfg + + data = yaml.loads(path.read_text(encoding="utf-8")) or {} + proj = data.get("project") or {} + cfg.name = proj.get("name") or project_root.name + + agent = proj.get("agent") or {} + cfg.agent_command = agent.get("command") or DEFAULT_AGENT_COMMAND + cfg.agent_args = list(agent.get("args") or DEFAULT_AGENT_ARGS) + cfg.agent_env = dict(agent.get("env") or {}) + + default = data.get("default") or {} + cfg.default_prompt = default.get("prompt") or DEFAULT_PROJECT_PROMPT + cfg.on_unknown_decision = default.get("onUnknownDecision") or cfg.on_unknown_decision + + for item in data.get("decisions") or []: + cfg.decisions.append( + DecisionRule( + id=str(item.get("id") or f"rule-{len(cfg.decisions) + 1}"), + question=item.get("question") or "", + match=item.get("match") or "", + answer=item.get("answer") or "", + enabled=bool(item.get("enabled", True)), + ) + ) + return cfg + + +def save_project_config(project_root: Path, cfg: ProjectConfig) -> Path: + path = project_root / PROJECT_DIR_NAME / PROJECT_CONFIG_NAME + atomic_write(path, cfg.to_yaml()) + return path + + +# ── 多队列:路径解析与老布局迁移 ──────────────────────────────────── +@dataclass(frozen=True) +class QueuePaths: + """一条队列在磁盘上的全部路径。""" + + root: Path + name: str + + @property + def dir(self) -> Path: + return self.root / PROJECT_DIR_NAME / QUEUE_DIR_NAME / self.name + + @property + def config(self) -> Path: + """队列定义(进版本库)。""" + return self.dir / QUEUE_FILE_NAME + + @property + def state(self) -> Path: + """运行时状态(不进版本库)。""" + return self.dir / STATE_FILE_NAME + + @property + def logs(self) -> Path: + """agent 日志与 prompt 文件(不进版本库)。""" + return self.dir / LOGS_DIR_NAME + + @property + def decisions(self) -> Path: + """决策记录(进版本库)。""" + return self.dir / DECISIONS_FILE_NAME + + @property + def lock(self) -> Path: + """单实例锁(不进版本库)。""" + return self.dir / LOCK_FILE_NAME + + +def queue_paths(project_root: Path, name: str = DEFAULT_QUEUE_NAME) -> QueuePaths: + """解析一条队列的路径。队列名非法直接报错(防路径穿越)。""" + if not name or not QUEUE_NAME_RE.match(name): + raise ValueError( + f"队列名不合法: {name!r}(只允许字母、数字、. _ -,且必须以字母或数字开头)" + ) + return QueuePaths(root=project_root, name=name) + + +def queue_names(project_root: Path) -> list[str]: + """列出磁盘上已有的队列名(按字典序)。""" + base = project_root / PROJECT_DIR_NAME / QUEUE_DIR_NAME + if not base.is_dir(): + return [] + out = [ + p.name + for p in sorted(base.iterdir(), key=lambda x: x.name) + if p.is_dir() and QUEUE_NAME_RE.match(p.name) + ] + return out + + +def strip_queue_section(text: str) -> str: + """从 YAML 文本里删掉顶层的 `queue:` 段,**其余内容原样保留**。 + + 为什么不用"解析 → 改 → 重新序列化":那样会把用户写的注释全弄丢。 + 这里按行做手术,只动 `queue:` 那一段。 + + - `queue:` 后面跟缩进内容(块序列)→ 整段删掉 + - `queue: []` 这种内联写法 → 改成 `queue: []`(保持只有一个空段) + """ + lines = text.split("\n") + out: list[str] = [] + i = 0 + n = len(lines) + while i < n: + line = lines[i] + m = re.match(r"^queue\s*:(.*)$", line) + if not m: + out.append(line) + i += 1 + continue + + tail = m.group(1).strip() + if tail and not tail.startswith("#"): + # 内联写法(queue: [] / queue: [...])—— 归一成空列表 + out.append("queue: []") + i += 1 + continue + + # 块序列:吃掉这一行 + 后面所有缩进行 + i += 1 + while i < n: + nxt = lines[i] + if nxt.strip() == "": + # 空行:后面若还有缩进内容就一并吃掉 + j = i + while j < n and lines[j].strip() == "": + j += 1 + if j < n and lines[j][:1] in (" ", "\t"): + i = j + continue + break + if nxt[:1] in (" ", "\t"): + i += 1 + continue + break + return "\n".join(out) + + +def migrate_legacy_queue(project_root: Path) -> str: + """把老布局迁移到 `.overnight-runner/queue/default/`。 + + 老布局: + /overnight-runner.yaml 的 queue: 段 + /.overnight-runner/state.json + /.overnight-runner/logs/ + /.overnight-runner/decisions.jsonl + + 迁移是 **幂等** 的:源清空后第二次调用直接返回空串。 + 用的是 move(rename)不是 copy,源文件不会留下两份。 + + 返回一句人类可读的迁移说明(没迁移则返回空串)。 + """ + notes: list[str] = [] + default = queue_paths(project_root, DEFAULT_QUEUE_NAME) + + # 1) 队列定义:根配置文件的 queue: 段 → queue/default/queue.yaml + legacy_cfg_path = queue_config_path(project_root) + if legacy_cfg_path.exists(): + raw = legacy_cfg_path.read_text(encoding="utf-8") + data = yaml.loads(raw) or {} + legacy_queue = list(data.get("queue") or []) + if legacy_queue and not default.config.exists(): + default.dir.mkdir(parents=True, exist_ok=True) + atomic_write( + default.config, + yaml.dumps({"queue": legacy_queue}), + ) + notes.append(f"队列定义 → {default.config}") + # 把根配置里的 queue: 段清空,保证只迁移一次。 + # 按行做手术,保留用户写的注释与排版。 + atomic_write(legacy_cfg_path, strip_queue_section(raw)) + + # 2) 运行时状态 / 日志 / 决策记录:整体搬进 default 队列目录 + legacy_dir = project_root / PROJECT_DIR_NAME + for name, dest in ( + (STATE_FILE_NAME, default.state), + (LOGS_DIR_NAME, default.logs), + (DECISIONS_FILE_NAME, default.decisions), + ): + src = legacy_dir / name + if not src.exists(): + continue + if dest.exists(): + continue + default.dir.mkdir(parents=True, exist_ok=True) + shutil.move(str(src), str(dest)) + notes.append(f"{src} → {dest}") + + return ";".join(notes) + + +# ── 队列配置 ──────────────────────────────────────────────────────── +@dataclass +class WatchdogConfig: + max_retries: int = 2 + backoff_sec: int = 60 + idle_timeout_sec: int = 1800 + total_timeout_sec: int = 7200 + kill_grace_sec: int = 15 + + @classmethod + def from_dict(cls, data: dict | None) -> "WatchdogConfig": + data = data or {} + return cls( + max_retries=int(data.get("maxRetries", 2)), + backoff_sec=int(data.get("backoffSec", 60)), + idle_timeout_sec=int(data.get("idleTimeoutSec", 1800)), + total_timeout_sec=int(data.get("totalTimeoutSec", 7200)), + kill_grace_sec=int(data.get("killGraceSec", 15)), + ) + + def to_dict(self) -> dict: + return { + "maxRetries": self.max_retries, + "backoffSec": self.backoff_sec, + "idleTimeoutSec": self.idle_timeout_sec, + "totalTimeoutSec": self.total_timeout_sec, + "killGraceSec": self.kill_grace_sec, + } + + +@dataclass +class DecisionConfig: + """决策策略。 + + - `mode=attended`(有人值守):agent 抛问题时打断它,TUI 弹决策窗口问人; + 超时没人答就按规则/兜底策略自动决策。 + - `mode=unattended`(无人值守):不打断 agent,按规则/兜底策略直接决策。 + """ + + mode: str = DECISION_MODE_ATTENDED + timeout_sec: int = 600 + resume: str = "session" # session | restart + output_format: str = "json" # json | text + json_args: list[str] = field(default_factory=lambda: ["--format", "json"]) + session_args: list[str] = field(default_factory=lambda: ["--session", "{session}"]) + session_pattern: str = r'"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"' + + @classmethod + def from_dict(cls, data: dict | None) -> "DecisionConfig": + data = data or {} + mode = str(data.get("mode") or DECISION_MODE_ATTENDED) + if mode not in DECISION_MODES: + mode = DECISION_MODE_ATTENDED + resume = str(data.get("resume") or "session") + if resume not in ("session", "restart"): + resume = "session" + output_format = str(data.get("outputFormat") or "json") + if output_format not in ("json", "text"): + output_format = "json" + args = data.get("sessionArgs") + if not isinstance(args, list) or not args: + args = ["--session", "{session}"] + json_args = data.get("jsonArgs") + if not isinstance(json_args, list) or not json_args: + json_args = ["--format", "json"] + return cls( + mode=mode, + timeout_sec=int(data.get("timeoutSec", 600)), + resume=resume, + output_format=output_format, + json_args=[str(a) for a in json_args], + session_args=[str(a) for a in args], + session_pattern=str( + data.get("sessionPattern") + or r'"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"' + ), + ) + + def to_dict(self) -> dict: + return { + "mode": self.mode, + "timeoutSec": self.timeout_sec, + "resume": self.resume, + "outputFormat": self.output_format, + "jsonArgs": list(self.json_args), + "sessionArgs": list(self.session_args), + "sessionPattern": self.session_pattern, + } + + def session_command(self, session_id: str) -> list[str]: + """把 session_args 里的 {session} 占位符替换成真实 session id。""" + return [a.replace("{session}", session_id) for a in self.session_args] + + +@dataclass +class RunnerConfig: + """启动时用的队列配置(overnight-runner.yaml)。""" + + agent_command: str = DEFAULT_AGENT_COMMAND + agent_args: list[str] = field(default_factory=lambda: list(DEFAULT_AGENT_ARGS)) + agent_env: dict[str, str] = field(default_factory=dict) + watchdog: WatchdogConfig = field(default_factory=WatchdogConfig) + decision: DecisionConfig = field(default_factory=DecisionConfig) + state_dir: str = PROJECT_DIR_NAME + workdir: str = "." + refresh_hz: int = 8 + log_tail: int = 400 + queue: list[dict] = field(default_factory=list) + source_path: Path | None = None + + @classmethod + def from_dict(cls, data: dict, source_path: Path | None = None) -> "RunnerConfig": + runner = data.get("runner") or {} + agent = runner.get("agent") or {} + cfg = cls( + agent_command=agent.get("command") or DEFAULT_AGENT_COMMAND, + agent_args=list(agent["args"]) if agent.get("args") is not None else list(DEFAULT_AGENT_ARGS), + agent_env=dict(agent.get("env") or {}), + watchdog=WatchdogConfig.from_dict(runner.get("watchdog")), + decision=DecisionConfig.from_dict(runner.get("decision")), + state_dir=runner.get("state", {}).get("dir") or PROJECT_DIR_NAME, + workdir=runner.get("workdir") or ".", + refresh_hz=int((runner.get("ui") or {}).get("refreshHz", 8)), + log_tail=int((runner.get("ui") or {}).get("logTail", 400)), + queue=list(data.get("queue") or []), + source_path=source_path, + ) + return cfg + + def to_dict(self) -> dict: + data: dict[str, Any] = { + "runner": { + "agent": { + "command": self.agent_command, + "args": self.agent_args, + "env": self.agent_env, + }, + "watchdog": self.watchdog.to_dict(), + "decision": self.decision.to_dict(), + "state": {"dir": self.state_dir}, + "workdir": self.workdir, + "ui": {"refreshHz": self.refresh_hz, "logTail": self.log_tail}, + } + } + # 队列定义已经搬到 .overnight-runner/queue//queue.yaml,这里只在 + # 还没迁移时保留(迁移后为空 → 不写出去) + if self.queue: + data["queue"] = self.queue + return data + + def to_yaml(self) -> str: + header = ( + "# overnight-runner 运行配置\n" + "# agent / 看门狗 / UI / 决策策略 —— 项目级,全队列共享\n" + "# 队列里的任务在 .overnight-runner/queue//queue.yaml\n" + ) + return header + yaml.dumps(self.to_dict()) + + +def queue_config_path(project_root: Path) -> Path: + return project_root / QUEUE_CONFIG_NAME + + +def load_runner_config(project_root: Path) -> RunnerConfig: + path = queue_config_path(project_root) + if not path.exists(): + return RunnerConfig(source_path=path) + data = yaml.loads(path.read_text(encoding="utf-8")) or {} + return RunnerConfig.from_dict(data, source_path=path) + + +def save_runner_config(project_root: Path, cfg: RunnerConfig) -> Path: + path = queue_config_path(project_root) + atomic_write(path, cfg.to_yaml()) + return path + + +def default_queue_config(project_root: Path) -> RunnerConfig: + cfg = RunnerConfig(source_path=queue_config_path(project_root)) + cfg.queue = [] + return cfg + + +__all__ = [ + "DECISION_MODES", + "DECISION_MODE_ATTENDED", + "DECISION_MODE_UNATTENDED", + "DEFAULT_QUEUE_NAME", + "DecisionConfig", + "DecisionRule", + "ProjectConfig", + "QueuePaths", + "RunnerConfig", + "WatchdogConfig", + "default_queue_config", + "load_project_config", + "load_runner_config", + "migrate_legacy_queue", + "queue_config_path", + "queue_names", + "queue_paths", + "save_project_config", + "save_runner_config", + "DEFAULT_AGENT_ARGS", + "DEFAULT_AGENT_COMMAND", + "DEFAULT_PROJECT_PROMPT", + "PROJECT_CONFIG_NAME", + "PROJECT_DIR_NAME", + "QUEUE_CONFIG_NAME", + "QUEUE_DIR_NAME", + "QUEUE_FILE_NAME", +] diff --git a/example-project/tools/overnight-runner/overnight_runner/controller.py b/example-project/tools/overnight-runner/overnight_runner/controller.py new file mode 100644 index 0000000..9225f57 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/controller.py @@ -0,0 +1,605 @@ +"""调度器:取任务 → 跑 agent → 看门狗 → 决策 → 失败重试 → 落状态。 + +决策有两条路: + +- **unattended(无人值守)**:agent 抛 `QUESTION:` 时当场按规则/兜底策略决策, + **不打断** agent;决策会在下一次拉起 agent 时注入 prompt。 +- **attended(有人值守)**:打断 agent,TUI 弹决策窗口问人;人答了就用 + `opencode run --session ` 续跑;超时没人答就按规则/兜底策略兜底。 +""" + +from __future__ import annotations + +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +from .agent import AgentProcess, check_agent_available +from .config import ProjectConfig, QueuePaths, RunnerConfig +from .decisions import ( + SOURCE_AGENT, + SOURCE_FALLBACK, + SOURCE_HUMAN, + SOURCE_RULE, + SOURCE_TIMEOUT, + DecisionEvent, + DecisionLog, + parse_agent_line, + resolve_answer, + should_ask, +) +from .prompts import build_prompt, build_resume_prompt +from .queue import ( + BLOCKED, + FAILED, + PENDING, + RETRYING, + RUNNING, + STOPPED, + SUCCESS, + Queue, + Task, + save_state, +) +from .util import StopFlag, fmt_ts, now, sleep_interruptible + +EventCallback = Callable[[str, Task], None] + +# 单个任务最多被打断几次(防止 agent 无限提问拖死队列) +MAX_DECISIONS_PER_TASK = 10 + + +@dataclass +class TaskOutcome: + task_id: str + status: str + exit_code: int | None + attempts: int + duration_sec: float + error: str = "" + summary: str = "" + decisions: int = 0 + + +@dataclass +class WatchResult: + """一次 agent 运行的观察结果。""" + + kind: str = "exited" # exited | timeout | question | stopped + timeout_kind: str = "" + question: str = "" + session_id: str = "" + + +class RunnerController: + """把队列里的 plan 一个一个交给 coding agent 跑。""" + + def __init__( + self, + project_root: Path, + runner_cfg: RunnerConfig, + project_cfg: ProjectConfig, + queue: Queue, + paths: QueuePaths, + stop: StopFlag | None = None, + on_event: EventCallback | None = None, + on_log: Callable[[str], None] | None = None, + ) -> None: + self.project_root = project_root + self.runner_cfg = runner_cfg + self.project_cfg = project_cfg + self.queue = queue + self.paths = paths + self.stop = stop or StopFlag() + self.on_event = on_event + self.on_log = on_log + + self.log_dir = paths.logs + self.decision_log = DecisionLog(paths.decisions) + self.decision_log.load() + + self._current: Task | None = None + self._current_proc: AgentProcess | None = None + self._current_lines: list[str] = [] + self._lock = threading.Lock() + + # 决策:agent 抛出的问题、等待人回答、已作出的决策 + self._ask_question: tuple[str, str] | None = None + self._decisions_made: list[tuple[str, str]] = [] + self._decision_lock = threading.Lock() + self._decision_event = threading.Event() + self._pending: dict | None = None + self._answer: str | None = None + + # ── 事件 ──────────────────────────────────────────────────────── + def _emit(self, kind: str, task: Task | None = None) -> None: + if self.on_event is not None: + try: + self.on_event(kind, task or self._current) # type: ignore[arg-type] + except Exception: # noqa: BLE001 + pass + + def _log(self, line: str) -> None: + with self._lock: + self._current_lines.append(line) + if len(self._current_lines) > 2000: + self._current_lines = self._current_lines[-1000:] + if self.on_log is not None: + try: + self.on_log(line) + except Exception: # noqa: BLE001 + pass + + @property + def current_lines(self) -> list[str]: + with self._lock: + return list(self._current_lines) + + def clear_log(self) -> None: + with self._lock: + self._current_lines = [] + + # ── 决策:等待人回答 ──────────────────────────────────────────── + def pending_question(self) -> dict | None: + """当前正在等人回答的问题(没有则 None)。UI 渲染决策窗口用。""" + with self._decision_lock: + if self._pending is None: + return None + pending = dict(self._pending) + deadline = pending.get("deadline") + pending["remaining"] = ( + max(0.0, deadline - time.monotonic()) if deadline else None + ) + return pending + + def submit_decision(self, answer: str) -> None: + """人在 TUI 里回答了问题。""" + with self._decision_lock: + self._answer = answer + self._decision_event.set() + + def cancel_decision(self) -> None: + """人按 Esc:不等了,直接用默认决策兜底。""" + with self._decision_lock: + self._answer = None + self._decision_event.set() + + def _wait_for_human( + self, task: Task, question: str, session_id: str + ) -> tuple[str | None, float]: + """等人回答。返回 (答案 or None, 等了多久秒)。""" + timeout = self.runner_cfg.decision.timeout_sec + started = time.monotonic() + deadline = (started + timeout) if timeout else None + + with self._decision_lock: + self._pending = { + "task_id": task.id, + "question": question, + "session_id": session_id, + "deadline": deadline, + "timeout_sec": timeout, + } + self._answer = None + self._decision_event.clear() + + self._emit("question_pending", task) + answer: str | None = None + try: + while True: + if self._decision_event.wait(timeout=0.2): + with self._decision_lock: + answer = self._answer + break + if deadline is not None and time.monotonic() >= deadline: + answer = None + break + if self.stop.is_set(): + return None, time.monotonic() - started + finally: + with self._decision_lock: + self._pending = None + self._decision_event.clear() + return answer, time.monotonic() - started + + def _resolve_question( + self, task: Task, question: str, session_id: str + ) -> tuple[str, str, float, str]: + """有人值守模式下的决策:问人 → 答 / 超时兜底。""" + answer, waited = self._wait_for_human(task, question, session_id) + + if answer is None: + fallback, rule_id = resolve_answer(self.project_cfg, question) + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=question, + answer=fallback, + source=SOURCE_TIMEOUT, + rule_id=rule_id, + waited_sec=waited, + session_id=session_id, + ) + ) + return fallback, SOURCE_TIMEOUT, waited, session_id + + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=question, + answer=answer, + source=SOURCE_HUMAN, + waited_sec=waited, + session_id=session_id, + ) + ) + return answer, SOURCE_HUMAN, waited, session_id + + def _append_decision(self, question: str, answer: str) -> None: + with self._lock: + self._decisions_made.append((question, answer)) + + @property + def decisions_made(self) -> list[tuple[str, str]]: + with self._lock: + return list(self._decisions_made) + + # ── 主循环 ────────────────────────────────────────────────────── + def run_forever(self) -> None: + """一直取任务跑,直到队列跑完或收到停止信号。""" + self._emit("runner_started") + while not self.stop.is_set(): + task = self.queue.next_ready() + if task is None: + if not self.queue.has_unfinished(): + break + # 有任务卡在依赖或重试等待里 + if not self._wait_for_retry(): + break + continue + self.run_task(task) + self._emit("runner_stopped") + self._save() + + def _wait_for_retry(self) -> bool: + """等一个正在重试等待中的任务到期。返回 False 表示应该退出。""" + for t in self.queue.tasks: + if t.status == RETRYING: + wait = max(0.0, t.duration_sec or 0.0) + if wait <= 0: + return True + self._emit("retry_wait", t) + sleep_interruptible(min(wait, 5), self.stop) + return True + # 没有在重试的任务,但还有未完成 —— 说明被依赖卡住了 + blocked = [t for t in self.queue.tasks if t.status == PENDING and not t.enabled] + if blocked: + self._emit("queue_blocked", blocked[0]) + return False + return False + + # ── 单任务 ────────────────────────────────────────────────────── + def run_task(self, task: Task) -> TaskOutcome: + """跑一个任务(含看门狗、决策打断与重试)。""" + self.clear_log() + self._current = task + with self._lock: + self._decisions_made = [] + task.status = RUNNING + task.started_at = now() + task.finished_at = None + task.exit_code = None + task.last_error = "" + task.summary = "" + self._emit("task_started", task) + + max_attempts = self.runner_cfg.watchdog.max_retries + 1 + outcome = TaskOutcome(task.id, FAILED, None, 0, 0.0) + + for attempt in range(1, max_attempts + 1): + if self.stop.is_set(): + task.status = STOPPED + task.finished_at = now() + break + + task.attempts = attempt + self._save() + + kind, info = self._run_leg(task) + + if kind == "success": + task.status = SUCCESS + task.last_error = "" + task.finished_at = now() + self._emit("task_succeeded", task) + break + + if kind == "timeout": + task.last_error = ( + f"{'总时长' if info == 'total' else '空闲'}超时 " + f"({info}),已终止 agent" + ) + self._emit("task_timeout", task) + elif kind == "stopped": + task.status = STOPPED + task.finished_at = now() + elif kind == "blocked": + task.status = BLOCKED + task.finished_at = now() + else: + task.last_error = task.last_error or info + self._emit("task_error", task) + + # 失败:决定是否重试 + task.finished_at = task.finished_at or now() + if attempt < max_attempts and not self.stop.is_set(): + task.status = RETRYING + self._emit("task_retrying", task) + self._save() + sleep_interruptible(self.runner_cfg.watchdog.backoff_sec, self.stop) + if self.stop.is_set(): + break + task.status = RUNNING + task.started_at = now() + continue + else: + task.status = FAILED if task.status != BLOCKED else BLOCKED + self._emit("task_failed", task) + + if task.status != SUCCESS: + task.status = task.status if task.status != RUNNING else FAILED + task.finished_at = task.finished_at or now() + + outcome = TaskOutcome( + task.id, + task.status, + task.exit_code, + task.attempts, + task.duration_sec or 0.0, + error=task.last_error, + summary=task.summary, + decisions=len(self.decisions_made), + ) + self._save() + self._emit("task_done", task) + self._current = None + self._current_proc = None + return outcome + + # ── 一次 agent 运行(含决策打断与续跑)──────────────────────── + def _run_leg(self, task: Task) -> tuple[str, str]: + """跑一次 agent。返回 (kind, info)。 + + kind ∈ success / failed / timeout / stopped / blocked + """ + session_id = "" + resume_prompt = "" + decision_count = 0 + + while True: + prompt, err = build_prompt( + self.project_root, + self.project_cfg, + task.plan, + task.prompt, + ) + if err: + task.last_error = err + return "failed", err + + made = self.decisions_made + if made: + prompt += "\n已经做出的决策(不要重复询问):\n" + "\n".join( + f"- {q} → {a}" for q, a in made + ) + "\n" + + if resume_prompt: + prompt = resume_prompt + + prompt_file = self.log_dir / f"{task.id}.prompt.md" + prompt_file.parent.mkdir(parents=True, exist_ok=True) + prompt_file.write_text(prompt, encoding="utf-8") + + ok, avail_err = check_agent_available(self.runner_cfg.agent_command) + if not ok: + task.last_error = avail_err + return "failed", avail_err + + command = self._build_command(prompt, session_id) + log_path = self.log_dir / f"{task.id}.log" + task.log_path = str(log_path.relative_to(self.project_root)) + + proc = AgentProcess( + command=command, + cwd=self.project_root / self.runner_cfg.workdir, + env={**self.runner_cfg.agent_env, **self.project_cfg.agent_env}, + on_line=lambda line: self._on_agent_line(task, line), + idle_timeout_sec=self.runner_cfg.watchdog.idle_timeout_sec, + total_timeout_sec=self.runner_cfg.watchdog.total_timeout_sec, + kill_grace_sec=self.runner_cfg.watchdog.kill_grace_sec, + output_format=self.runner_cfg.decision.output_format, + session_pattern=self.runner_cfg.decision.session_pattern, + ) + self._current_proc = proc + + try: + proc.start() + except (OSError, ValueError) as exc: + task.last_error = f"无法启动 agent: {exc}" + return "failed", task.last_error + + result = self._watch(proc, task) + exit_code = proc.wait(timeout=30) + if exit_code is None: + proc.terminate() + exit_code = proc.wait(timeout=10) + + task.exit_code = exit_code + self._write_log(task, log_path) + + # ── agent 抛了问题 ──────────────────────────────────── + if result.kind == "question": + decision_count += 1 + if decision_count > MAX_DECISIONS_PER_TASK: + task.last_error = ( + f"决策次数超过上限({MAX_DECISIONS_PER_TASK} 次),任务中止" + ) + return "failed", task.last_error + + answer, source, waited, sid = self._resolve_question( + task, result.question, result.session_id + ) + self._append_decision(result.question, answer) + self._log(f" ↳ 决策[{source}]: {answer}") + self._emit("decision", task) + + if ( + self.runner_cfg.decision.resume == "session" + and sid + and self.runner_cfg.decision.session_args + ): + # 用同一个 session 续跑,agent 的上下文不丢 + session_id = sid + resume_prompt = build_resume_prompt( + result.question, answer, task.plan + ) + continue + # 拿不到 session(或配置成 restart)→ 重跑整个任务, + # 决策历史会注入新一轮的 prompt + session_id = "" + resume_prompt = "" + continue + + if result.kind == "timeout": + return "timeout", result.timeout_kind + if result.kind == "stopped": + return "stopped", "" + if task.status == BLOCKED: + return "blocked", task.last_error + if exit_code == 0: + return "success", "" + return "failed", f"agent 退出码 {exit_code}" + + def _build_command(self, prompt: str, session_id: str) -> list[str]: + """组装 agent 命令行(含 json 输出格式与 session 续跑参数)。""" + cfg = self.runner_cfg.decision + command = [self.runner_cfg.agent_command, *self.runner_cfg.agent_args] + if cfg.output_format == "json": + command.extend(cfg.json_args) + if session_id: + command.extend(cfg.session_command(session_id)) + command.append(prompt) + return command + + def _write_log(self, task: Task, log_path: Path) -> None: + with self._lock: + log_text = "\n".join(self._current_lines) + try: + log_path.parent.mkdir(parents=True, exist_ok=True) + log_path.write_text(log_text + "\n", encoding="utf-8") + except OSError: + pass + + # ── 看门狗 ────────────────────────────────────────────────────── + def _watch(self, proc: AgentProcess, task: Task) -> WatchResult: + """盯住 agent:空闲超时 / 总时长超时 / agent 抛问题 → 终止。""" + while True: + if self.stop.is_set(): + proc.terminate() + return WatchResult(kind="stopped") + + asked = self._take_question() + if asked is not None: + proc.terminate() + return WatchResult( + kind="question", question=asked[0], session_id=asked[1] + ) + + timed_out, kind = proc.check_timeout() + if timed_out: + proc.terminate() + return WatchResult(kind="timeout", timeout_kind=kind) + + if not proc.alive: + # agent 可能问完就退出了 —— 再查一次标志,别漏掉 + asked = self._take_question() + if asked is not None: + return WatchResult( + kind="question", question=asked[0], session_id=asked[1] + ) + return WatchResult(kind="exited") + + time.sleep(0.1) + + # ── agent 输出处理 ────────────────────────────────────────────── + def _take_question(self) -> tuple[str, str] | None: + with self._lock: + asked = self._ask_question + self._ask_question = None + return asked + + def _on_agent_line(self, task: Task, line: str) -> None: + self._log(line) + kind, value = parse_agent_line(line) + if kind == "decision": + question, answer = value # type: ignore[misc] + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=question, + answer=answer, + source=SOURCE_AGENT, + session_id=self._session_id(), + ) + ) + self._append_decision(question, answer) + self._emit("decision", task) + elif kind == "question": + if should_ask(self.runner_cfg.decision.mode): + # 有人值守:打断 agent,等人来答 + with self._lock: + self._ask_question = (value, self._session_id()) # type: ignore[assignment] + return + # 无人值守:当场按规则/兜底策略决策,agent 继续跑 + answer, rule_id = resolve_answer(self.project_cfg, value) # type: ignore[arg-type] + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=value, # type: ignore[arg-type] + answer=answer, + source=SOURCE_RULE if rule_id else SOURCE_FALLBACK, + rule_id=rule_id, + session_id=self._session_id(), + ) + ) + self._append_decision(value, answer) # type: ignore[arg-type] + self._log(f" ↳ 默认决策[{rule_id or 'fallback'}]: {answer}") + self._emit("decision", task) + elif kind == "done": + task.summary = value # type: ignore[assignment] + self._emit("task_summary", task) + elif kind == "blocked": + task.last_error = value # type: ignore[assignment] + task.status = BLOCKED + self._emit("task_blocked", task) + + def _session_id(self) -> str: + proc = self._current_proc + return proc.session_id if proc is not None else "" + + # ── 状态持久化 ────────────────────────────────────────────────── + def _save(self) -> None: + try: + save_state(self.paths, self.queue) + except OSError: + pass + + def snapshot(self) -> str: + stats = self.queue.stats() + return ( + f"{fmt_ts(now())} 总 {len(self.queue)} · " + f"待跑 {stats.get(PENDING, 0)} · 运行 {stats.get(RUNNING, 0)} · " + f"成功 {stats.get(SUCCESS, 0)} · 失败 {stats.get(FAILED, 0)}" + ) diff --git a/example-project/tools/overnight-runner/overnight_runner/decisions.py b/example-project/tools/overnight-runner/overnight_runner/decisions.py new file mode 100644 index 0000000..72b156e --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/decisions.py @@ -0,0 +1,174 @@ +"""默认决策:规则匹配 + 决策记录。 + +三种来源: +1. agent 自己按默认决策执行后输出 `DECISION: <问题> → <决策>`,我们解析并记录; +2. agent 抛出一个待决问题(输出 `QUESTION: <问题>`)—— 无人值守时用规则匹配给答案, + 有人值守时先问人(见 controller),答案最终都会回灌给 agent 并记录。 + +记录写在 `/decisions.jsonl`,一行一条,便于后续回溯。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +from .config import DECISION_MODE_ATTENDED, DecisionRule, ProjectConfig +from .util import append_jsonl, now_iso + +DECISION_RE = re.compile(r"^\s*DECISION\s*[::]\s*(.+?)\s*(?:→|->)\s*(.+?)\s*$") +QUESTION_RE = re.compile(r"^\s*QUESTION\s*[::]\s*(.+?)\s*$") +BLOCKED_RE = re.compile(r"^\s*BLOCKED\s*[::]\s*(.+?)\s*$") +DONE_RE = re.compile(r"^\s*DONE\s*[::]\s*(.+?)\s*$") + +# 决策来源 +SOURCE_AGENT = "agent" # agent 自己输出的 DECISION +SOURCE_RULE = "rule" # 命中预设规则 +SOURCE_FALLBACK = "fallback" # 兜底策略(onUnknownDecision) +SOURCE_HUMAN = "human" # 人在 TUI 里回答的 +SOURCE_TIMEOUT = "timeout" # 等待超时后自动兜底的 + + +@dataclass +class DecisionEvent: + task_id: str + question: str + answer: str + source: str = SOURCE_AGENT + rule_id: str = "" + at: str = "" + waited_sec: float | None = None + session_id: str = "" + + def to_record(self) -> dict: + return { + "at": self.at or now_iso(), + "task_id": self.task_id, + "question": self.question, + "answer": self.answer, + "source": self.source, + "rule_id": self.rule_id, + "waited_sec": round(self.waited_sec, 1) if self.waited_sec is not None else 0.0, + "session_id": self.session_id, + } + + +class DecisionLog: + """决策记录:JSONL 追加写 + 内存缓存。""" + + def __init__(self, path: Path) -> None: + self.path = path + self._records: list[dict] = [] + + def load(self) -> list[dict]: + import json + + if not self.path.exists(): + self._records = [] + return self._records + out = [] + for line in self.path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + try: + out.append(json.loads(line)) + except json.JSONDecodeError: + continue + self._records = out + return out + + def record(self, event: DecisionEvent) -> dict: + rec = event.to_record() + append_jsonl(self.path, rec) + self._records.append(rec) + return rec + + @property + def records(self) -> list[dict]: + return list(self._records) + + def for_task(self, task_id: str) -> list[dict]: + return [r for r in self._records if r.get("task_id") == task_id] + + +def match_rule(rules: list[DecisionRule], question: str) -> DecisionRule | None: + """用关键词/正则匹配一条默认决策。""" + q = question.strip() + for rule in rules: + if not rule.enabled: + continue + if rule.question and (rule.question.strip() == q or rule.question.strip() in q): + return rule + if rule.match: + try: + if re.search(rule.match, q): + return rule + except re.error: + if rule.match.lower() in q.lower(): + return rule + return None + + +def parse_agent_line(line: str) -> tuple[str, str]: + """解析 agent 的一行输出。 + + 返回 (kind, value),kind ∈ decision / question / blocked / done / ''。 + """ + m = DECISION_RE.match(line) + if m: + return "decision", (m.group(1).strip(), m.group(2).strip()) # type: ignore[return-value] + m = QUESTION_RE.match(line) + if m: + return "question", m.group(1).strip() # type: ignore[return-value] + m = BLOCKED_RE.match(line) + if m: + return "blocked", m.group(1).strip() # type: ignore[return-value] + m = DONE_RE.match(line) + if m: + return "done", m.group(1).strip() # type: ignore[return-value] + return "", "" + + +def resolve_answer(project_cfg: ProjectConfig, question: str) -> tuple[str, str]: + """算出(答案, rule_id)—— **纯函数,不写日志**。 + + 命中规则就用规则答案,否则用项目的兜底策略。 + """ + rule = match_rule(project_cfg.decisions, question) + if rule is not None: + return (rule.answer or project_cfg.on_unknown_decision), rule.id + return project_cfg.on_unknown_decision, "" + + +def should_ask(mode: str) -> bool: + """该模式下要不要问人。 + + - `attended`(有人值守):要问 + - `unattended`(无人值守):不问 + """ + return mode == DECISION_MODE_ATTENDED + + +def decide( + project_cfg: ProjectConfig, + log: DecisionLog, + task_id: str, + question: str, +) -> tuple[str, str]: + """给 agent 抛出的问题一个默认答案(无人值守路径)。 + + 返回 (answer, rule_id)。命中规则就用规则答案,否则用项目的兜底策略。 + """ + answer, rule_id = resolve_answer(project_cfg, question) + log.record( + DecisionEvent( + task_id=task_id, + question=question, + answer=answer, + source=SOURCE_RULE if rule_id else SOURCE_FALLBACK, + rule_id=rule_id, + ) + ) + return answer, rule_id diff --git a/example-project/tools/overnight-runner/overnight_runner/keys.py b/example-project/tools/overnight-runner/overnight_runner/keys.py new file mode 100644 index 0000000..7442877 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/keys.py @@ -0,0 +1,329 @@ +"""跨平台按键读取:POSIX 用 termios,Windows 用 msvcrt。 + +只依赖标准库,不需要 prompt_toolkit 之类的重依赖。 +""" + +from __future__ import annotations + +import os +import sys +import threading +from typing import Callable + +from .util import is_windows + +# 规范化按键名 +UP = "up" +DOWN = "down" +LEFT = "left" +RIGHT = "right" +ENTER = "enter" +ESC = "esc" +BACKSPACE = "backspace" +TAB = "tab" +CTRL_C = "ctrl-c" +NONE = "" + +KEYBOARD_HELP = ( + "↑↓ 选择 a 追加 plan r 重试 p 暂停/恢复 d 移除 " + "Enter 查看日志 Esc 返回 c 清屏 q 退出" +) + +DECISION_HELP = ( + "待决策时: Enter 提交答案 · Esc 用默认决策 · Ctrl-C 退出" +) + +_WIN_SPECIAL = { + "H": UP, + "P": DOWN, + "K": LEFT, + "M": RIGHT, + "G": ENTER, + "S": LEFT, + "R": RIGHT, + "\x0d": ENTER, + "\x1b": ESC, + "\x08": BACKSPACE, + "\x09": TAB, +} + +# 按下 ESC 后等这么久还等不到后续字节,就认为用户是单独按了 ESC +ESC_TIMEOUT = 0.05 +# 轮询间隔(秒):让读线程能及时响应 stop() +POLL_INTERVAL = 0.2 + + +class RawMode: + """进入原始模式(按键立即返回,不回显),退出时恢复。""" + + def __init__(self) -> None: + self._fd = None + self._old = None + self._active = False + + def __enter__(self) -> "RawMode": + if is_windows(): + self._active = True + return self + try: + import termios + import tty + + self._fd = sys.stdin.fileno() + self._old = termios.tcgetattr(self._fd) + tty.setraw(self._fd) + self._active = True + except Exception: # noqa: BLE001 - 没有 tty 时降级为行模式 + self._active = False + return self + + def __exit__(self, *exc) -> None: + if not self._active or self._fd is None or self._old is None: + return + try: + import termios + + termios.tcsetattr(self._fd, termios.TCSADRAIN, self._old) + except Exception: # noqa: BLE001 + pass + + +def _utf8_seq_len(lead: int) -> int: + """按 UTF-8 首字节判断这个字符总共占几个字节。 + + 汉字 3 字节、emoji 4 字节。读键盘必须 **按字节凑齐再解**, + 否则一个汉字会被拆成 3 次读、每次都解码失败 → 中文全变问号。 + """ + if lead < 0x80: + return 1 + if lead >= 0xF0: + return 4 + if lead >= 0xE0: + return 3 + if lead >= 0xC0: + return 2 + return 1 # 非法首字节(续字节开头)—— 当 1 字节处理,别死循环 + + +def _normalize_key(ch: str) -> str: + """把一个字符归一成按键名(控制键给名字,其余原样返回)。""" + if ch in ("\r", "\n"): + return ENTER + if ch in ("\x7f", "\x08"): + return BACKSPACE + if ch == "\x03": + return CTRL_C + if ch == "\t": + return TAB + return ch + + +_CSI_KEYS = { + "[A": UP, + "[B": DOWN, + "[C": RIGHT, + "[D": LEFT, + "[H": UP, + "[F": DOWN, +} + + +class PosixKeyReader: + """POSIX 下的按键读取:懂 UTF-8 多字节字符,也懂 ESC 序列。 + + 为什么不用"一次 os.read(fd, 1)":那样会把一个汉字的 3 个字节 + 拆成 3 次读,每次 `decode(errors="replace")` 都失败 → 中文全变问号 + (实测:决策窗口里输入"先修 Bug",落盘变成"??? Bug")。 + + 做法:字节先进缓冲区,按 UTF-8 首字节凑齐长度再整体解码。 + """ + + def __init__(self) -> None: + self._buf = bytearray() + self._eof = False + + # ── 字节层 ────────────────────────────────────────────────────── + def _pump(self, fd: int, timeout: float | None) -> bool: + """把 fd 里的可用字节读进缓冲区。返回是否读到东西。""" + import select + + try: + ready, _, _ = select.select([fd], [], [], timeout) + except (OSError, ValueError): + return False + if not ready: + return False + try: + data = os.read(fd, 1024) + except OSError: + return False + if not data: + self._eof = True + return False + self._buf.extend(data) + return True + + def _take_char(self) -> str | None: + """从缓冲区头部取一个完整字符;字节还不够返回 None。""" + if not self._buf: + return None + need = _utf8_seq_len(self._buf[0]) + if len(self._buf) < need: + return None + raw = bytes(self._buf[:need]) + del self._buf[:need] + return raw.decode("utf-8", errors="replace") + + def _find_csi_final(self) -> int | None: + """在缓冲区里找 CSI 序列的结束字节下标。 + + 缓冲区形如 b"[A" / b"[1;5C"(下标 0 是 '[')。 + 返回 None 表示"还没收全";返回 -1 表示"非法序列"。 + """ + for i in range(1, len(self._buf)): + b = self._buf[i] + if 0x40 <= b <= 0x7E: + return i + if not (0x20 <= b <= 0x3F): + return -1 + return None + + # ── ESC 序列 ──────────────────────────────────────────────────── + def _read_escape(self, fd: int) -> str: + """已经读到 ESC,判断它是单独按键还是某个序列的开头。""" + if not self._buf: + self._pump(fd, ESC_TIMEOUT) + if not self._buf or self._buf[0] != 0x5B: # '[' + return ESC # 后面的字节留给下一次读 + while True: + idx = self._find_csi_final() + if idx is not None and idx >= 0: + seq = bytes(self._buf[: idx + 1]) + del self._buf[: idx + 1] + return _CSI_KEYS.get(seq.decode("ascii", errors="replace"), NONE) + if idx == -1: # 非法序列,丢掉 ESC[ 别把后面的正文吃掉 + del self._buf[:1] + return NONE + if not self._pump(fd, ESC_TIMEOUT): + del self._buf[:1] + return NONE + + # ── 对外 ──────────────────────────────────────────────────────── + def read_key(self, fd: int) -> str: + """读一个按键(控制键给名字,其余返回原字符)。 + + 返回 NONE 表示"暂时没读到"(超时或输入流结束)。 + """ + while True: + ch = self._take_char() + if ch is None: + if self._eof: + return NONE + self._pump(fd, POLL_INTERVAL) + continue + if ch == "\x1b": + return self._read_escape(fd) + return _normalize_key(ch) + + +_POSIX_READER = PosixKeyReader() + + +def _read_posix_key(fd: int) -> str: + """读一个按键(POSIX)。保留函数形式,内部共用一个带缓冲的读取器。""" + return _POSIX_READER.read_key(fd) + + +def _read_win_key() -> str: + import msvcrt + + ch = msvcrt.getwch() + if ch in ("\x00", "\xe0"): + ch2 = msvcrt.getwch() + return _WIN_SPECIAL.get(ch2, NONE) + if ch in ("\r", "\n"): + return ENTER + if ch in ("\x7f", "\x08"): + return BACKSPACE + if ch == "\x03": + return CTRL_C + if ch == "\t": + return TAB + return ch + + +class KeyReader: + """后台线程读按键,交给回调。""" + + def __init__(self, on_key: Callable[[str], None]) -> None: + self.on_key = on_key + self._thread: threading.Thread | None = None + self._stop = threading.Event() + self._raw = RawMode() + self._posix = PosixKeyReader() + + def start(self) -> None: + self._raw.__enter__() + self._thread = threading.Thread(target=self._loop, name="key-reader", daemon=True) + self._thread.start() + + def stop(self) -> None: + self._stop.set() + self._raw.__exit__() + + def _loop(self) -> None: + while not self._stop.is_set(): + try: + if is_windows(): + key = _read_win_key() + else: + fd = sys.stdin.fileno() + key = self._posix.read_key(fd) + except Exception: # noqa: BLE001 + break + if key == NONE: + continue + try: + self.on_key(key) + except Exception: # noqa: BLE001 + pass + if key == CTRL_C: + break + + +def read_line(prompt: str = "") -> str: + """行模式读一行(用于非 TUI 场景)。""" + if prompt: + print(prompt, end="", flush=True) + try: + return sys.stdin.readline().strip() + except (EOFError, KeyboardInterrupt): + return "" + + +def confirm(prompt: str, default: bool = False) -> bool: + suffix = "[Y/n]" if default else "[y/N]" + ans = read_line(f"{prompt} {suffix} ").lower() + if not ans: + return default + return ans in ("y", "yes") + + +__all__ = [ + "BACKSPACE", + "CTRL_C", + "DOWN", + "ENTER", + "ESC", + "KEYBOARD_HELP", + "KeyReader", + "LEFT", + "NONE", + "PosixKeyReader", + "RawMode", + "RIGHT", + "TAB", + "UP", + "confirm", + "read_line", +] diff --git a/example-project/tools/overnight-runner/overnight_runner/prompts.py b/example-project/tools/overnight-runner/overnight_runner/prompts.py new file mode 100644 index 0000000..45fd918 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/prompts.py @@ -0,0 +1,66 @@ +"""提示词组装:把项目默认提示词 + 默认决策 + plan 内容拼成给 agent 的一次性提示。""" + +from __future__ import annotations + +from pathlib import Path + +from .config import ProjectConfig + +PLAN_PLACEHOLDER = "{{PLAN}}" +DECISIONS_PLACEHOLDER = "{{DECISIONS}}" + + +def read_plan(project_root: Path, plan_rel: str) -> tuple[str, str]: + """读 plan 文件,返回 (内容, 错误信息)。""" + path = project_root / plan_rel + if not path.exists(): + return "", f"plan 文件不存在: {plan_rel}" + try: + text = path.read_text(encoding="utf-8") + except OSError as exc: + return "", f"plan 文件读取失败: {plan_rel} ({exc})" + if not text.strip(): + return "", f"plan 文件为空: {plan_rel}" + return text, "" + + +def build_prompt( + project_root: Path, + project_cfg: ProjectConfig, + plan_rel: str, + task_prompt: str = "", +) -> tuple[str, str]: + """返回 (最终提示词, 错误信息)。""" + plan_text, err = read_plan(project_root, plan_rel) + if err: + return "", err + + decisions = project_cfg.decision_text() or "(无预设决策,遇到需决策的问题请选择最安全、可回滚的方案)" + + template = project_cfg.default_prompt or "" + if PLAN_PLACEHOLDER in template: + prompt = template.replace(PLAN_PLACEHOLDER, plan_text) + else: + prompt = f"{template}\n\n{plan_text}" + + if DECISIONS_PLACEHOLDER in prompt: + prompt = prompt.replace(DECISIONS_PLACEHOLDER, decisions) + elif decisions: + prompt = f"{prompt}\n\n默认决策:\n{decisions}" + + prompt += f"\n\n---\n本次任务:{plan_rel}\n" + + if task_prompt: + prompt += f"补充要求:\n{task_prompt}\n" + + return prompt, "" + + +def build_resume_prompt(question: str, answer: str, plan_rel: str) -> str: + """续跑时的提示词:把人的决策送回给同一个 session 的 agent。""" + return ( + f"针对你刚才提出的问题:{question}\n\n" + f"决策如下:{answer}\n\n" + f"请基于这个决策继续完成原任务(计划:{plan_rel})。" + "不要重复已经完成的步骤,只做剩下的部分。" + ) diff --git a/example-project/tools/overnight-runner/overnight_runner/queue.py b/example-project/tools/overnight-runner/overnight_runner/queue.py new file mode 100644 index 0000000..3357ac6 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/queue.py @@ -0,0 +1,320 @@ +"""任务队列:加载 / 追加 / 状态跟踪。 + +队列定义在 `.overnight-runner/queue//queue.yaml`(可提交进仓库), +运行时状态放在同目录的 `state.json`(不提交)。 + +每条队列一个独立目录 —— 多人可以在同一个项目里各跑各的队列,互不干扰。 +""" + +from __future__ import annotations + +import json +import re +import threading +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +from typing import Any + +from . import yaml_lite as yaml +from .config import QueuePaths +from .util import atomic_write, now, now_iso, slugify, today_stamp + +# 任务状态 +PENDING = "pending" +RUNNING = "running" +RETRYING = "retrying" +SUCCESS = "success" +FAILED = "failed" +STOPPED = "stopped" +BLOCKED = "blocked" + +STATUSES = (PENDING, RUNNING, RETRYING, SUCCESS, FAILED, STOPPED, BLOCKED) + +# plan 文件名常带日期前缀(YYYYMMDD-xxx / YYYY-MM-DD-xxx),别再拼一遍 +DATE_PREFIX_RE = re.compile(r"^\d{4}-?\d{2}-?\d{2}[-_]") + + + +@dataclass +class Task: + id: str + plan: str + prompt: str = "" + priority: int = 100 + enabled: bool = True + role: str = "" # BA / DEV / QA —— 只是标签,用于分组显示 + depends_on: list[str] = field(default_factory=list) + + # 运行时状态 + status: str = PENDING + attempts: int = 0 + started_at: datetime | None = None + finished_at: datetime | None = None + exit_code: int | None = None + last_error: str = "" + summary: str = "" + log_path: str = "" + + @property + def plan_path(self) -> Path: + return Path(self.plan) + + @property + def duration_sec(self) -> float | None: + if self.started_at is None: + return None + end = self.finished_at or now() + # 状态文件是手改过的,可能写了不带时区的时间 —— 别让渲染循环炸掉 + if end.tzinfo is None and self.started_at.tzinfo is not None: + end = end.replace(tzinfo=self.started_at.tzinfo) + elif end.tzinfo is not None and self.started_at.tzinfo is None: + self.started_at = self.started_at.replace(tzinfo=end.tzinfo) + return (end - self.started_at).total_seconds() + + def to_def(self) -> dict: + """写回 YAML 的定义部分。""" + data: dict[str, Any] = {"id": self.id, "plan": self.plan} + if self.prompt: + data["prompt"] = self.prompt + if self.priority != 100: + data["priority"] = self.priority + if self.role: + data["role"] = self.role + if self.depends_on: + data["depends_on"] = self.depends_on + if not self.enabled: + data["enabled"] = False + return data + + def to_state(self) -> dict: + return { + "id": self.id, + "plan": self.plan, + "status": self.status, + "attempts": self.attempts, + "started_at": self.started_at.isoformat(timespec="seconds") if self.started_at else None, + "finished_at": self.finished_at.isoformat(timespec="seconds") if self.finished_at else None, + "exit_code": self.exit_code, + "last_error": self.last_error, + "summary": self.summary, + "log_path": self.log_path, + } + + +class Queue: + """线程安全的任务队列。""" + + def __init__(self, tasks: list[Task] | None = None) -> None: + self._tasks: list[Task] = tasks or [] + self._lock = threading.RLock() + + # ── 基本访问 ──────────────────────────────────────────────────── + @property + def tasks(self) -> list[Task]: + with self._lock: + return list(self._tasks) + + def get(self, task_id: str) -> Task | None: + with self._lock: + for t in self._tasks: + if t.id == task_id: + return t + return None + + def __len__(self) -> int: + with self._lock: + return len(self._tasks) + + # ── 变更 ──────────────────────────────────────────────────────── + def add(self, task: Task) -> Task: + with self._lock: + if self.get(task.id) is not None: + raise ValueError(f"任务 id 已存在: {task.id}") + self._tasks.append(task) + self._tasks.sort(key=lambda t: (t.priority, t.id)) + return task + + def remove(self, task_id: str) -> bool: + with self._lock: + before = len(self._tasks) + self._tasks = [t for t in self._tasks if t.id != task_id] + return len(self._tasks) != before + + def update(self, task_id: str, **fields) -> Task | None: + with self._lock: + task = self.get(task_id) + if task is None: + return None + for key, value in fields.items(): + setattr(task, key, value) + return task + + # ── 调度 ──────────────────────────────────────────────────────── + def next_ready(self) -> Task | None: + """下一个可以跑的任务:enabled + pending + 依赖已完成 + 优先级最高。""" + with self._lock: + done = {t.id for t in self._tasks if t.status == SUCCESS} + candidates = [ + t + for t in self._tasks + if t.enabled and t.status == PENDING and all(d in done for d in t.depends_on) + ] + if not candidates: + return None + candidates.sort(key=lambda t: (t.priority, t.id)) + return candidates[0] + + def pending_count(self) -> int: + with self._lock: + return sum(1 for t in self._tasks if t.status in (PENDING, RUNNING, RETRYING)) + + def has_unfinished(self) -> bool: + with self._lock: + return any(t.status in (PENDING, RUNNING, RETRYING) for t in self._tasks) + + def stats(self) -> dict[str, int]: + with self._lock: + out = {s: 0 for s in STATUSES} + for t in self._tasks: + out[t.status] = out.get(t.status, 0) + 1 + return out + + +def build_task( + project_root: Path, + plan: str, + prompt: str = "", + role: str = "", + priority: int = 100, + task_id: str | None = None, + existing_ids: set[str] | None = None, +) -> Task: + """由 plan 路径构造任务;plan 相对项目根目录。 + + id 默认取 plan 文件名(去掉日期前缀)—— 同一个 plan 可以在同一天被排多次, + 冲突时自动加 `-2` / `-3` 序号。 + """ + plan_rel = _normalize_rel(project_root, plan) + if task_id is None: + # plan 文件名通常已经带日期前缀(20261106-xxx),别再拼一遍变成双日期 + stem = DATE_PREFIX_RE.sub("", Path(plan_rel).stem) + base = slugify(stem, fallback="task") + task_id = f"{today_stamp()}-{base}" + taken = existing_ids or set() + if task_id in taken: + n = 2 + while f"{task_id}-{n}" in taken: + n += 1 + task_id = f"{task_id}-{n}" + return Task( + id=task_id, + plan=plan_rel, + prompt=prompt, + role=role, + priority=priority, + ) + + +def _normalize_rel(project_root: Path, plan: str) -> str: + """把 plan 路径规范成相对项目根的 POSIX 风格路径。""" + p = Path(plan) + if p.is_absolute(): + try: + p = p.resolve().relative_to(project_root.resolve()) + except ValueError: + return p.as_posix() + return p.as_posix() + + +def task_from_def(defs: dict, index: int = 0) -> Task: + plan = defs.get("plan") or "" + task_id = defs.get("id") or f"task-{index + 1}" + return Task( + id=str(task_id), + plan=plan, + prompt=defs.get("prompt") or "", + priority=int(defs.get("priority", 100)), + enabled=bool(defs.get("enabled", True)), + role=defs.get("role") or "", + depends_on=list(defs.get("depends_on") or []), + ) + + +def load_queue(paths: QueuePaths, queue_defs: list[dict]) -> Queue: + """把 YAML 定义与运行时状态合并成队列。""" + tasks = [task_from_def(d, i) for i, d in enumerate(queue_defs)] + queue = Queue(tasks) + + for st in _read_states(paths): + task = queue.get(st.get("id", "")) + if task is None: + # 兼容老 id(如 20261106-20261106-xxx)—— 退化成按 plan 路径匹配 + task = next( + (t for t in queue.tasks if t.plan == st.get("plan", "")), None + ) + if task is None: + continue + task.status = st.get("status", PENDING) + task.attempts = int(st.get("attempts", 0)) + task.exit_code = st.get("exit_code") + task.last_error = st.get("last_error", "") + task.summary = st.get("summary", "") + task.log_path = st.get("log_path", "") + started = st.get("started_at") + finished = st.get("finished_at") + task.started_at = datetime.fromisoformat(started) if started else None + task.finished_at = datetime.fromisoformat(finished) if finished else None + return queue + + +def _read_states(paths: QueuePaths) -> list[dict]: + """读运行时状态。 + + `state.json` 缺失或损坏时回落到 `state.json.bak` —— 避免误删状态文件 + 就把已经跑完的任务全部重新排队。 + """ + for path in (paths.state, paths.state.with_name(paths.state.name + ".bak")): + if not path.exists(): + continue + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + continue + if isinstance(data, dict): + return list(data.get("tasks") or []) + return [] + + +def save_state(paths: QueuePaths, queue: Queue) -> Path: + """写运行时状态(同时留一份 .bak 兜底)。""" + payload = { + "updated_at": now_iso(), + "tasks": [t.to_state() for t in queue.tasks], + } + text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n" + atomic_write(paths.state, text) + try: + atomic_write(paths.state.with_name(paths.state.name + ".bak"), text) + except OSError: + pass + return paths.state + + +def load_queue_defs(paths: QueuePaths) -> list[dict]: + """读队列定义(`.overnight-runner/queue//queue.yaml`)。""" + if not paths.config.exists(): + return [] + try: + data = yaml.loads(paths.config.read_text(encoding="utf-8")) or {} + except (OSError, ValueError): + return [] + return list(data.get("queue") or []) + + +def save_queue_defs(paths: QueuePaths, queue: Queue) -> Path: + """把队列定义写回 `queue.yaml`(追加 plan 用)。""" + paths.dir.mkdir(parents=True, exist_ok=True) + payload = {"queue": [t.to_def() for t in queue.tasks]} + atomic_write(paths.config, yaml.dumps(payload)) + return paths.config diff --git a/example-project/tools/overnight-runner/overnight_runner/term.py b/example-project/tools/overnight-runner/overnight_runner/term.py new file mode 100644 index 0000000..50a766d --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/term.py @@ -0,0 +1,279 @@ +"""纯 ANSI 终端绘制 —— 零第三方依赖。 + +只依赖标准库。用 ANSI 转义序列直接画: + +- 备用屏幕(全屏面板) +- 光标定位 / 隐藏 +- 颜色(SGR) +- 边框(圆角 / 直角) +- 中日韩宽字符的显示宽度计算 + +没有 TTY 时(管道 / CI)会自动降级:不做任何转义,只输出纯文本。 +""" + +from __future__ import annotations + +import os +import shutil +import sys +import unicodedata +from typing import Iterable + +# ── 转义序列 ──────────────────────────────────────────────────────── +ESC = "\x1b" +CSI = ESC + "[" + +ALT_SCREEN_ON = CSI + "?1049h" +ALT_SCREEN_OFF = CSI + "?1049l" +CURSOR_HIDE = CSI + "?25l" +CURSOR_SHOW = CSI + "?25h" +CLEAR = CSI + "2J" +CURSOR_HOME = CSI + "H" +RESET = CSI + "0m" + + +def _sgr(*codes: int | str) -> str: + return CSI + ";".join(str(c) for c in codes) + "m" + + +class Style: + """语义色。""" + + RESET = _sgr(0) + BOLD = _sgr(1) + DIM = _sgr(2) + ITALIC = _sgr(3) + REVERSE = _sgr(7) + + BLACK = _sgr(30) + RED = _sgr(31) + GREEN = _sgr(32) + YELLOW = _sgr(33) + BLUE = _sgr(34) + MAGENTA = _sgr(35) + CYAN = _sgr(36) + WHITE = _sgr(37) + GREY = _sgr(90) + + BRIGHT_RED = _sgr(91) + BRIGHT_GREEN = _sgr(92) + BRIGHT_YELLOW = _sgr(93) + BRIGHT_BLUE = _sgr(94) + BRIGHT_MAGENTA = _sgr(95) + BRIGHT_CYAN = _sgr(96) + BRIGHT_WHITE = _sgr(97) + + +# ── 显示宽度 ──────────────────────────────────────────────────────── +import re + +_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]") + + +def char_width(ch: str) -> int: + """字符的显示宽度(0 / 1 / 2)。""" + if ch == "\t": + return 4 + if unicodedata.combining(ch): + return 0 + if unicodedata.east_asian_width(ch) in ("W", "F"): + return 2 + return 1 + + +def _tokens(text: str) -> list[tuple[str, int]]: + """把文本切成 (片段, 显示宽度) 序列。 + + ANSI 转义序列宽度算 0 —— 否则带颜色的文本会被算宽。 + """ + out: list[tuple[str, int]] = [] + i = 0 + while i < len(text): + if text[i] == "\x1b": + m = _ANSI_RE.match(text, i) + if m: + out.append((m.group(0), 0)) + i = m.end() + continue + out.append((text[i], char_width(text[i]))) + i += 1 + return out + + +def dwidth(text: str) -> int: + """字符串的显示宽度(忽略 ANSI 转义序列)。""" + return sum(w for _, w in _tokens(text)) + + +def truncate(text: str, width: int, ellipsis: str = "…") -> str: + """按显示宽度截断(不切断 ANSI 序列)。""" + if width <= 0: + return "" + if dwidth(text) <= width: + return text + limit = width - dwidth(ellipsis) + out: list[str] = [] + used = 0 + for tok, w in _tokens(text): + if used + w > limit: + break + out.append(tok) + used += w + return "".join(out) + ellipsis + Style.RESET + + +def pad(text: str, width: int, align: str = "left") -> str: + """按显示宽度补齐(忽略 ANSI 转义序列)。""" + w = dwidth(text) + if w >= width: + return text + space = " " * (width - w) + if align == "right": + return space + text + if align == "center": + left = (width - w) // 2 + return " " * left + text + " " * (width - w - left) + return text + space + + +def wrap(text: str, width: int) -> list[str]: + """按显示宽度折行(不打断宽字符,不切断 ANSI 序列)。""" + if width <= 0: + return [""] + lines: list[str] = [] + for raw in text.split("\n"): + if dwidth(raw) <= width: + lines.append(raw) + continue + cur: list[str] = [] + used = 0 + for tok, w in _tokens(raw): + if used + w > width and cur: + lines.append("".join(cur)) + cur = [] + used = 0 + cur.append(tok) + used += w + lines.append("".join(cur)) + return lines or [""] + + +# ── 边框字符 ──────────────────────────────────────────────────────── +class Box: + ROUND = "┌┐└┘─│├┤┬┴┼" + SQUARE = "┌┐└┘─│├┤┬┴┼" + ASCII = "+-++|+++++" + + +class Term: + """终端绘制器。""" + + def __init__(self, stream=None) -> None: + self.out = stream or sys.stdout + self.tty = bool(getattr(self.out, "isatty", lambda: False)()) + self._alt = False + + # ── 尺寸 ──────────────────────────────────────────────────────── + def size(self) -> tuple[int, int]: + try: + size = shutil.get_terminal_size(fallback=(120, 40)) + return max(40, size.columns), max(10, size.lines) + except OSError: + return 120, 40 + + # ── 基础输出 ──────────────────────────────────────────────────── + def write(self, text: str) -> None: + try: + self.out.write(text) + except (OSError, ValueError): + pass + + def flush(self) -> None: + try: + self.out.flush() + except (OSError, ValueError): + pass + + def enter(self) -> None: + """进备用屏幕 + 隐藏光标。""" + if not self.tty: + return + self.write(ALT_SCREEN_ON + CURSOR_HIDE + CLEAR + CURSOR_HOME) + self._alt = True + self.flush() + + def leave(self) -> None: + """退出备用屏幕 + 恢复光标。""" + if not self.tty: + self.flush() + return + self.write(CURSOR_SHOW + ALT_SCREEN_OFF) + self._alt = False + self.flush() + + def clear(self) -> None: + if self.tty: + self.write(CLEAR + CURSOR_HOME) + + def move(self, row: int, col: int) -> None: + """移动光标(1-based)。""" + if self.tty: + self.write(f"{CSI}{row};{col}H") + + def style(self, code: str, text: str) -> str: + if not self.tty or not code: + return text + return f"{code}{text}{Style.RESET}" + + # ── 画框 ──────────────────────────────────────────────────────── + def draw_box( + self, + x: int, + y: int, + w: int, + h: int, + title: str = "", + lines: Iterable[str] = (), + border: str = Style.CYAN, + title_style: str = Style.BOLD, + footer: str = "", + ) -> None: + """在 (x, y) 处画一个 w×h 的框,内容放 lines。""" + if w < 4 or h < 3: + return + b = Box.ROUND + tl, tr, bl, br, hz, vt = b[0], b[1], b[2], b[3], b[4], b[5] + + # 上边框(带标题) + self.move(y, x) + if title: + label = " " + truncate(title, max(0, w - 6)) + " " + self.write(self.style(border, tl)) + self.write(self.style(title_style, label)) + self.write(self.style(border, hz * max(0, w - 2 - dwidth(label)) + tr)) + else: + self.write(self.style(border, tl + hz * (w - 2) + tr)) + + # 内容 + body = list(lines) + for i in range(h - 2): + content = body[i] if i < len(body) else "" + self.move(y + 1 + i, x) + self.write(self.style(border, vt)) + self.write(pad(truncate(content, w - 2), w - 2)) + self.write(self.style(border, vt)) + + # 下边框(带 footer) + self.move(y + h - 1, x) + if footer: + label = " " + truncate(footer, max(0, w - 6)) + " " + self.write(self.style(border, bl)) + self.write(self.style(Style.DIM, label)) + self.write(self.style(border, hz * max(0, w - 2 - dwidth(label)) + br)) + else: + self.write(self.style(border, bl + hz * (w - 2) + br)) + + def draw_line(self, x: int, y: int, text: str, style: str = "") -> None: + """在 (x, y) 处写一行(1-based 坐标)。""" + self.move(y, x) + self.write(self.style(style, text)) diff --git a/example-project/tools/overnight-runner/overnight_runner/ui.py b/example-project/tools/overnight-runner/overnight_runner/ui.py new file mode 100644 index 0000000..c129aed --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/ui.py @@ -0,0 +1,460 @@ +"""分屏面板:左边任务队列,右边 coding agent 输出。 + +零第三方依赖 —— 用 ANSI 转义序列直接画(见 term.py)。 +""" + +from __future__ import annotations + +import threading +import time +from pathlib import Path +from typing import Callable + +from .config import QueuePaths, RunnerConfig +from .controller import RunnerController +from .keys import ( + BACKSPACE, + CTRL_C, + DECISION_HELP, + DOWN, + ENTER, + ESC, + KEYBOARD_HELP, + UP, +) +from .queue import BLOCKED, FAILED, PENDING, RETRYING, RUNNING, SUCCESS, STOPPED, Queue, Task +from .term import Style, Term, dwidth, pad, truncate, wrap + +STATUS_STYLE = { + PENDING: Style.DIM, + RUNNING: Style.BRIGHT_CYAN, + RETRYING: Style.BRIGHT_YELLOW, + SUCCESS: Style.BRIGHT_GREEN, + FAILED: Style.BRIGHT_RED, + BLOCKED: Style.BRIGHT_MAGENTA, + STOPPED: Style.GREY, +} + +STATUS_LABEL = { + PENDING: "待跑", + RUNNING: "运行中", + RETRYING: "待重试", + SUCCESS: "成功", + FAILED: "失败", + BLOCKED: "阻塞", + STOPPED: "已停", +} + +LEFT_WIDTH = 46 +FOOTER_HEIGHT = 3 + + +class RunnerUI: + """overnight-runner 的分屏界面。""" + + def __init__( + self, + controller: RunnerController, + queue: Queue, + runner_cfg: RunnerConfig, + project_root: Path, + paths: QueuePaths | None = None, + ) -> None: + self.controller = controller + self.queue = queue + self.cfg = runner_cfg + self.project_root = project_root + self.paths = paths + + self.term = Term() + self.selected = 0 + self.detail_task_id: str | None = None + self.message = "" + self.message_level = "info" + self._quit = threading.Event() + self._input: dict | None = None # {"prompt": str, "buffer": str} + self._log_lines: list[str] = [] + self._log_lock = threading.Lock() + + # 决策窗口:人正在回答 agent 的问题 + self._decision_buffer: str | None = None + self._decision_lock = threading.Lock() + + controller.on_log = self._on_log + controller.on_event = self._on_event + + # ── 回调 ──────────────────────────────────────────────────────── + def _on_log(self, line: str) -> None: + with self._log_lock: + self._log_lines.append(line) + if len(self._log_lines) > 4000: + self._log_lines = self._log_lines[-2000:] + + def _on_event(self, kind: str, task: Task | None) -> None: + labels = { + "task_started": f"▶ 开始 {task.id if task else ''}", + "task_succeeded": f"✔ 成功 {task.id if task else ''}", + "task_failed": f"✘ 失败 {task.id if task else ''}", + "task_timeout": f"⏱ 超时 {task.id if task else ''}", + "task_retrying": f"↻ 重试 {task.id if task else ''}", + "task_blocked": f"⛔ 阻塞 {task.id if task else ''}", + "task_done": f"— 结束 {task.id if task else ''}", + "decision": f"◆ 决策已记录 {task.id if task else ''}", + "retry_wait": f"⏳ 等待重试 {task.id if task else ''}", + "runner_started": "启动 overnight-runner", + "runner_stopped": "overnight-runner 已停止", + } + text = labels.get(kind) + if text: + self._set_message(text, "warn" if kind.endswith(("failed", "timeout", "blocked")) else "info") + + def _set_message(self, text: str, level: str = "info") -> None: + self.message = text + self.message_level = level + + # ── 交互 ──────────────────────────────────────────────────────── + def handle_key(self, key: str) -> None: + # 决策窗口优先级最高 —— 它在阻塞 agent,等不起 + if self.controller.pending_question() is not None: + self._handle_decision_key(key) + return + + if self._input is not None: + self._handle_input_key(key) + return + + if key == CTRL_C or key == "q": + self._quit.set() + self.controller.stop.set() + elif key == UP: + self.selected = max(0, self.selected - 1) + elif key == DOWN: + self.selected = min(max(0, len(self.queue) - 1), self.selected + 1) + elif key == "a": + self._input = {"prompt": "追加 plan 路径:", "buffer": ""} + elif key == "r": + self._retry_selected() + elif key == "p": + self._toggle_pause() + elif key == "d": + self._delete_selected() + elif key == ENTER: + task = self._selected_task() + if task is not None: + self.detail_task_id = task.id + elif key == ESC: + self.detail_task_id = None + elif key == "c": + self.controller.clear_log() + with self._log_lock: + self._log_lines = [] + + def _handle_decision_key(self, key: str) -> None: + """决策窗口的按键处理。""" + with self._decision_lock: + if self._decision_buffer is None: + self._decision_buffer = "" + buffer = self._decision_buffer + + if key == CTRL_C: + self._decision_buffer = None + self._quit.set() + self.controller.stop.set() + return + if key == ESC: + self._decision_buffer = None + self.controller.cancel_decision() + self._set_message("已放弃回答,按默认决策继续", "warn") + return + if key == ENTER: + answer = buffer.strip() + self._decision_buffer = None + if answer: + self.controller.submit_decision(answer) + else: + self.controller.cancel_decision() + return + if key == BACKSPACE: + self._decision_buffer = buffer[:-1] + return + if len(key) == 1 and key.isprintable(): + self._decision_buffer = buffer + key + + def _handle_input_key(self, key: str) -> None: + assert self._input is not None + if key == ESC: + self._input = None + return + if key == ENTER: + value = self._input["buffer"].strip() + self._input = None + if value: + self._append_plan(value) + return + if key == BACKSPACE: + self._input["buffer"] = self._input["buffer"][:-1] + return + if key == CTRL_C: + self._input = None + self._quit.set() + self.controller.stop.set() + return + if len(key) == 1 and key.isprintable(): + self._input["buffer"] += key + + def _append_plan(self, plan: str) -> None: + from .queue import build_task, save_queue_defs + + if self.paths is None: + self._set_message("队列路径未设置,无法追加", "error") + return + task = build_task( + self.project_root, + plan, + existing_ids={t.id for t in self.queue.tasks}, + ) + try: + self.queue.add(task) + save_queue_defs(self.paths, self.queue) + self._set_message(f"已加入队列: {task.id} → {task.plan}", "ok") + except ValueError as exc: + self._set_message(str(exc), "error") + + def _selected_task(self) -> Task | None: + tasks = self.queue.tasks + if not tasks: + return None + self.selected = min(self.selected, len(tasks) - 1) + return tasks[self.selected] + + def _running_task(self) -> Task | None: + """当前正在跑的任务(可能没有)。""" + for t in self.queue.tasks: + if t.status == RUNNING: + return t + return None + + def _retry_selected(self) -> None: + task = self._selected_task() + if task is None: + return + task.status = PENDING + task.attempts = 0 + task.last_error = "" + task.exit_code = None + task.finished_at = None + self._set_message(f"已重置 {task.id},将重新排队", "ok") + + def _toggle_pause(self) -> None: + task = self._selected_task() + if task is None: + return + task.enabled = not task.enabled + self._set_message(f"{task.id} 已{'恢复' if task.enabled else '暂停'}", "ok") + + def _delete_selected(self) -> None: + task = self._selected_task() + if task is None: + return + if task.status == RUNNING: + self._set_message("任务正在运行,不能删除", "error") + return + self.queue.remove(task.id) + self.selected = max(0, self.selected - 1) + self._set_message(f"已移除 {task.id}", "ok") + + # ── 渲染:左边 ────────────────────────────────────────────────── + def _left_lines(self, width: int) -> list[str]: + tasks = self.queue.tasks + stats = self.queue.stats() + + if not tasks: + body = ["", "队列为空", "", "按 a 追加 plan", ""] + else: + body = [] + id_w = max(8, min(18, width - 22)) + for idx, t in enumerate(tasks): + marker = "▶" if idx == self.selected else " " + name = truncate(t.id, id_w) + status = STATUS_LABEL.get(t.status, t.status) + line = f"{marker} {pad(name, id_w)} {pad(status, 6)} {t.attempts:>2}" + if idx == self.selected: + line = Style.BRIGHT_WHITE + line + Style.RESET + else: + line = f"{marker} {name}{' ' * max(0, id_w - dwidth(name))} " \ + f"{STATUS_STYLE.get(t.status, '')}{pad(status, 6)}{Style.RESET} {t.attempts:>2}" + body.append(line) + body.append("") + body.append( + Style.DIM + + f"待跑 {stats.get(PENDING, 0)} · 运行 {stats.get(RUNNING, 0)} · " + + f"成功 {stats.get(SUCCESS, 0)} · 失败 {stats.get(FAILED, 0)}" + + Style.RESET + ) + return body + + # ── 渲染:决策窗口 ────────────────────────────────────────────── + def _decision_lines(self, width: int) -> list[str]: + """正在等人回答时的决策框(没有则空)。""" + pending = self.controller.pending_question() + if pending is None: + self._decision_buffer = None + return [] + + with self._decision_lock: + if self._decision_buffer is None: + self._decision_buffer = "" + buffer = self._decision_buffer + + remaining = pending.get("remaining") + if remaining is None: + countdown = "不限时" + else: + secs = int(max(0, remaining)) + countdown = f"剩余 {secs // 60}:{secs % 60:02d}" + + box: list[str] = [ + Style.BOLD + Style.BRIGHT_YELLOW + "◆ 待决策" + Style.RESET, + Style.DIM + f" 任务: {pending.get('task_id', '')}" + Style.RESET, + ] + for ln in wrap(str(pending.get("question", "")), max(10, width - 4)): + box.append(" " + ln) + box.append("") + box.append(Style.BOLD + " 你的决策:" + Style.RESET) + box.append(" > " + Style.BRIGHT_WHITE + buffer + Style.RESET + "▏") + box.append("") + box.append( + Style.DIM + + f" {countdown} Enter 确认 · Esc 用默认决策 · Ctrl-C 退出" + + Style.RESET + ) + box.append("") + return box + + # ── 渲染:右边 ────────────────────────────────────────────────── + def _right_lines(self, width: int) -> list[str]: + if self._input is not None: + return [ + "", + self._input["prompt"] + Style.BRIGHT_WHITE + self._input["buffer"] + Style.RESET + "▏", + "", + Style.DIM + "Enter 确认 · Esc 取消" + Style.RESET, + ] + + detail = self.queue.get(self.detail_task_id) if self.detail_task_id else None + + lines: list[str] = self._decision_lines(width) + if detail is not None: + log_file = self.project_root / detail.log_path if detail.log_path else None + if log_file and log_file.exists(): + raw = log_file.read_text(encoding="utf-8", errors="replace").splitlines() + else: + raw = [f"({detail.id} 还没有日志)"] + else: + with self._log_lock: + raw = list(self._log_lines) + raw = raw[-self.cfg.log_tail:] + + if self.message: + style = {"error": Style.BRIGHT_RED, "warn": Style.BRIGHT_YELLOW, "ok": Style.BRIGHT_GREEN}.get( + self.message_level, "" + ) + lines.append(style + self.message + Style.RESET) + lines.append("") + + for ln in raw: + lines.extend(wrap(ln, width)) + + decisions = self.controller.decision_log.records[-6:] + if decisions: + lines.append("") + lines.append(Style.BOLD + Style.DIM + "最近决策" + Style.RESET) + # 问题占 40%,答案占剩下的 + q_w = max(8, (width - 3) * 2 // 5) + a_w = max(8, width - q_w - 3) + for d in decisions: + q = truncate(str(d.get("question", "")), q_w) + a = truncate(str(d.get("answer", "")), a_w) + lines.append(f"{Style.DIM}{q}{Style.RESET} → {a}") + + if not lines: + lines = [Style.DIM + "等待任务开始…" + Style.RESET] + return lines + + # ── 渲染:整体 ────────────────────────────────────────────────── + def render(self) -> None: + term = self.term + cols, rows = term.size() + left_w = min(LEFT_WIDTH, max(30, cols // 3)) + right_x = left_w + 1 + right_w = cols - left_w - 1 + body_h = max(3, rows - FOOTER_HEIGHT) + + term.clear() + + # 左:任务队列 + title = f"任务队列 ({len(self.queue)})" + term.draw_box( + x=1, + y=1, + w=left_w, + h=body_h, + title=title, + lines=self._left_lines(left_w - 4), + border=Style.CYAN, + title_style=Style.BOLD + Style.CYAN, + ) + + # 右:agent 输出 + # 标题用 **正在跑** 的任务,而不是选中行 —— 否则按 ↓ 切行后标题和内容对不上 + running = self._running_task() + if self._input is not None: + right_title = "追加任务" + elif self.detail_task_id: + right_title = f"任务日志 · {self.detail_task_id}" + elif running is not None: + right_title = f"Coding Agent · {running.id}" + else: + right_title = "Coding Agent" + + term.draw_box( + x=right_x, + y=1, + w=right_w, + h=body_h, + title=right_title, + lines=self._right_lines(right_w - 4), + border=Style.CYAN, + title_style=Style.BOLD + Style.CYAN, + ) + + # 底:快捷键 + if self.controller.pending_question() is not None: + hint = truncate(DECISION_HELP, cols - 4) + else: + hint = truncate(KEYBOARD_HELP, cols - 4) + term.draw_box( + x=1, + y=body_h + 1, + w=cols - 1, + h=FOOTER_HEIGHT, + lines=[Style.DIM + hint + Style.RESET], + border=Style.GREY, + ) + term.flush() + + # ── 主循环 ────────────────────────────────────────────────────── + def run(self) -> None: + from .keys import KeyReader + + reader = KeyReader(self.handle_key) + self.term.enter() + reader.start() + try: + while not self._quit.is_set(): + self.render() + time.sleep(1.0 / max(1, self.cfg.refresh_hz)) + finally: + reader.stop() + self.term.leave() + print(self.controller.snapshot()) diff --git a/example-project/tools/overnight-runner/overnight_runner/util.py b/example-project/tools/overnight-runner/overnight_runner/util.py new file mode 100644 index 0000000..deb1581 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/util.py @@ -0,0 +1,233 @@ +"""跨平台小工具:时间、时长、原子写、终端宽度。""" + +from __future__ import annotations + +import os +import shutil +import tempfile +import time +from datetime import datetime, timezone +from pathlib import Path + + +def now() -> datetime: + return datetime.now(timezone.utc).astimezone() + + +def now_iso() -> str: + return now().isoformat(timespec="seconds") + + +def fmt_ts(dt: datetime | None) -> str: + if dt is None: + return "-" + return dt.strftime("%m-%d %H:%M:%S") + + +def fmt_duration(seconds: float | None) -> str: + if seconds is None: + return "-" + seconds = int(max(0, seconds)) + h, rem = divmod(seconds, 3600) + m, s = divmod(rem, 60) + if h: + return f"{h}h{m:02d}m" + if m: + return f"{m}m{s:02d}s" + return f"{s}s" + + +def atomic_write(path: Path, text: str) -> None: + """同目录临时文件 + rename,避免读到写了一半的内容。""" + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh: + fh.write(text) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def append_jsonl(path: Path, record: dict) -> None: + import json + + path.parent.mkdir(parents=True, exist_ok=True) + line = json.dumps(record, ensure_ascii=False, sort_keys=False) + with path.open("a", encoding="utf-8", newline="\n") as fh: + fh.write(line + "\n") + fh.flush() + os.fsync(fh.fileno()) + + +def terminal_size() -> tuple[int, int]: + size = shutil.get_terminal_size(fallback=(100, 30)) + return size.columns, size.lines + + +def is_windows() -> bool: + return os.name == "nt" + + +def slugify(text: str, fallback: str = "task") -> str: + keep = [] + for ch in text.lower(): + if ch.isalnum() or ch in "-_": + keep.append(ch) + elif ch in " /\\": + keep.append("-") + slug = "".join(keep).strip("-") + while "--" in slug: + slug = slug.replace("--", "-") + return slug[:48] or fallback + + +def today_stamp() -> str: + return now().strftime("%Y%m%d") + + +def sleep_interruptible(seconds: float, stop: "StopFlag") -> None: + """可被 stop 打断的 sleep。""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if stop.is_set(): + return + time.sleep(min(0.25, max(0.0, deadline - time.monotonic()))) + + +class StopFlag: + """线程安全的停止标志。""" + + def __init__(self) -> None: + import threading + + self._event = threading.Event() + + def set(self) -> None: + self._event.set() + + def is_set(self) -> bool: + return self._event.is_set() + + def wait(self, timeout: float | None = None) -> bool: + return self._event.wait(timeout) + + +def pid_alive(pid: int) -> bool: + """进程还活着吗? + + Windows 上不能用 `os.kill(pid, 0)` —— 那会真的把进程杀掉, + 所以 Windows 走心跳判断(见 QueueLock)。 + """ + if pid <= 0: + return False + if is_windows(): + return True # Windows 上无法安全探测,交给心跳 + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + return True + + +class QueueLock: + """队列级单实例锁。 + + 同一个队列同时跑两个 runner 会把同一个 pending 任务跑两遍(白烧 agent), + 所以每条队列目录放一个锁文件。 + + 锁文件内容:{"pid": 12345, "started_at": "...", "heartbeat": 1793...} + 判定为 stale 的条件:pid 已死(POSIX)或心跳超过 STALE_SEC(Windows / 兜底)。 + """ + + STALE_SEC = 120.0 + + def __init__(self, path: Path) -> None: + self.path = path + self._held = False + + # ── 内部 ──────────────────────────────────────────────────────── + def _read(self) -> dict: + import json + + try: + data = json.loads(self.path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + def _write(self, data: dict) -> None: + import json + + atomic_write(self.path, json.dumps(data, ensure_ascii=False) + "\n") + + def _is_stale(self, data: dict) -> bool: + pid = int(data.get("pid") or 0) + if pid and not pid_alive(pid): + return True + if is_windows(): + heartbeat = float(data.get("heartbeat") or 0) + if heartbeat and (time.time() - heartbeat) > self.STALE_SEC: + return True + return False + + # ── 对外 ──────────────────────────────────────────────────────── + def acquire(self) -> tuple[bool, str]: + """拿锁。返回 (是否成功, 失败原因)。""" + self.path.parent.mkdir(parents=True, exist_ok=True) + if self.path.exists(): + data = self._read() + if not self._is_stale(data): + pid = int(data.get("pid") or 0) + return False, f"队列已被 pid {pid} 占用" + # 残留锁,清掉重建 + try: + self.path.unlink() + except OSError: + pass + self._write( + { + "pid": os.getpid(), + "started_at": now_iso(), + "heartbeat": time.time(), + } + ) + self._held = True + return True, "" + + def touch(self) -> None: + """更新心跳(长跑时定期调)。""" + if not self._held: + return + data = self._read() + data["heartbeat"] = time.time() + try: + self._write(data) + except OSError: + pass + + def release(self) -> None: + if not self._held: + return + self._held = False + try: + self.path.unlink() + except OSError: + pass + + def __enter__(self) -> "QueueLock": + ok, err = self.acquire() + if not ok: + raise RuntimeError(err) + return self + + def __exit__(self, *exc) -> None: + self.release() diff --git a/example-project/tools/overnight-runner/overnight_runner/yaml_lite.py b/example-project/tools/overnight-runner/overnight_runner/yaml_lite.py new file mode 100644 index 0000000..8374f82 --- /dev/null +++ b/example-project/tools/overnight-runner/overnight_runner/yaml_lite.py @@ -0,0 +1,566 @@ +"""极简 YAML 子集解析 / 序列化 —— 零第三方依赖。 + +支持(覆盖本仓库用到的全部语法): + +- 缩进映射、序列 +- 序列项为映射(``- key: value`` 及其续行) +- 标量:plain / ``'single'`` / ``"double"`` +- 流式序列 ``[a, b]`` 与流式映射 ``{a: 1}`` +- 块标量 ``|`` ``|-`` ``>`` ``>-`` +- 注释(引号外、行首或前置空白后) +- 类型推断:bool / null / int / float / str +- 文档分隔符 ``---`` + +不支持(遇到会明确报错,不静默出错): + +- 锚点 ``&`` / 别名 ``*`` / 标签 ``!`` +- 复杂键(``? key``) +- 多文档(只取第一个) + +之所以自己写而不是用 PyYAML:让 overnight-runner **零依赖**, +在任何装了 Python 3.9+ 的机器上直接跑,不用 pip install。 +""" + +from __future__ import annotations + +from typing import Any + +__all__ = ["loads", "dumps", "YamlError"] + + +class YamlError(ValueError): + """YAML 解析失败。消息里带行号,便于定位。""" + + +# 序列项标记(用不可能出现在正文里的字符,避免与缩进层级混淆) +_SEQ = "\x00seq" + + +# ── 行处理 ────────────────────────────────────────────────────────── +class _Line: + __slots__ = ("indent", "text", "lineno", "raw_idx") + + def __init__(self, indent: int, text: str, lineno: int, raw_idx: int) -> None: + self.indent = indent + self.text = text + self.lineno = lineno + self.raw_idx = raw_idx + + def __repr__(self) -> str: # pragma: no cover - 调试用 + return f"_Line({self.indent}, {self.text!r}, line={self.lineno})" + + +def _strip_comment(text: str) -> str: + """去掉引号外的注释。""" + out = [] + quote = "" + i = 0 + while i < len(text): + ch = text[i] + if quote: + out.append(ch) + if ch == "\\" and quote == '"' and i + 1 < len(text): + out.append(text[i + 1]) + i += 2 + continue + if ch == quote: + quote = "" + i += 1 + continue + if ch in ("'", '"'): + quote = ch + out.append(ch) + i += 1 + continue + if ch == "#" and (not out or out[-1] in " \t"): + break + out.append(ch) + i += 1 + return "".join(out).rstrip() + + +def _split_key(text: str) -> tuple[str, str, str]: + """拆 ``key: value``。 + + 返回 (key, sep, value)。sep 为空表示这一行不是映射项。 + 引号内的冒号不算分隔符。 + """ + quote = "" + i = 0 + while i < len(text): + ch = text[i] + if quote: + if ch == "\\" and quote == '"' and i + 1 < len(text): + i += 2 + continue + if ch == quote: + quote = "" + i += 1 + continue + if ch in ("'", '"'): + quote = ch + i += 1 + continue + if ch in "[{": + break + if ch == ":": + rest = text[i + 1:] + if rest == "" or rest[0] in " \t": + return text[:i].strip(), ":", rest.strip() + i += 1 + return text.strip(), "", "" + + +def _unterminated(text: str) -> bool: + """引号没闭合(只关心行尾的引号状态)。""" + t = text.rstrip() + if len(t) >= 1 and t[-1] in ("'", '"'): + # 可能闭合了,也可能是转义过的 + return t.count(t[-1]) % 2 == 1 + if t.startswith("'") or t.startswith('"'): + return True + return False + + +def _fold(parts: list[str]) -> str: + """多行引号标量的折行规则:单换行折成空格,空行保留为换行。""" + result = "" + prev_blank = False + for i, ln in enumerate(parts): + if i == 0: + result = ln + continue + if ln.strip() == "": + result += "\n" + prev_blank = True + continue + if not prev_blank: + result += " " + result += ln + prev_blank = False + return result + + +def _preprocess(raw_lines: list[str]) -> list[_Line]: + """把原始行变成逻辑行。 + + 做三件事: + 1. 跳过空行、整行注释、``---`` + 2. 把 ``- key: value`` 拆成序列标记 + 内容行 + 3. 把跨行的引号标量合并成一行 + """ + out: list[_Line] = [] + idx = 0 + total = len(raw_lines) + while idx < total: + raw = raw_lines[idx] + if "\t" in raw[: len(raw) - len(raw.lstrip())]: + raise YamlError(f"第 {idx + 1} 行:YAML 缩进不能用 Tab") + stripped = raw.strip() + if not stripped or stripped.startswith("#"): + idx += 1 + continue + if stripped == "---": + idx += 1 + continue + if stripped in ("...",): + break + indent = len(raw) - len(raw.lstrip(" ")) + text = _strip_comment(raw[indent:]) + + if text == "-" or text.startswith("- "): + rest = text[1:].strip() + key, sep, _ = _split_key(rest) + # 统一拆成:序列标记 + 内容行 + out.append(_Line(indent, _SEQ, idx + 1, idx)) + if rest: + content_indent = indent + 2 if (sep and key) else indent + out.append(_Line(content_indent, rest, idx + 1, idx)) + idx += 1 + continue + + # 跨行的引号标量(PyYAML 会把带换行的字符串写成这种形式) + key, sep, val = _split_key(text) + if sep and val and _unterminated(val): + prefix = text[: len(text) - len(val)] + parts = [val] + j = idx + 1 + while j < total and _unterminated(_fold(parts)): + parts.append(raw_lines[j].strip()) + j += 1 + out.append(_Line(indent, prefix + _fold(parts), idx + 1, idx)) + idx = j + continue + + out.append(_Line(indent, text, idx + 1, idx)) + idx += 1 + return out + + +# ── 标量 ──────────────────────────────────────────────────────────── +_TRUE = {"true", "True", "TRUE"} +_FALSE = {"false", "False", "FALSE"} +_NULL = {"", "~", "null", "Null", "NULL"} + + +def _parse_scalar(text: str, lineno: int) -> Any: + t = text.strip() + if len(t) >= 2 and t[0] == '"' and t[-1] == '"': + return _unescape_double(t[1:-1], lineno) + if len(t) >= 2 and t[0] == "'" and t[-1] == "'": + return t[1:-1].replace("''", "'") + if t.startswith("[") and t.endswith("]"): + return _parse_flow_seq(t[1:-1], lineno) + if t.startswith("{") and t.endswith("}"): + return _parse_flow_map(t[1:-1], lineno) + if t in _TRUE: + return True + if t in _FALSE: + return False + if t in _NULL: + return None + try: + if t.lstrip("+-").isdigit(): + return int(t) + except ValueError: + pass + try: + if any(c in t for c in ".eE") and t.lstrip("+-").replace(".", "", 1).isdigit(): + return float(t) + except ValueError: + pass + return t + + +def _unescape_double(s: str, lineno: int) -> str: + out = [] + i = 0 + while i < len(s): + ch = s[i] + if ch == "\\" and i + 1 < len(s): + nxt = s[i + 1] + mapping = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\", "/": "/", "0": "\0"} + if nxt in mapping: + out.append(mapping[nxt]) + i += 2 + continue + if nxt == "u" and i + 5 < len(s) + 1: + try: + out.append(chr(int(s[i + 2: i + 6], 16))) + i += 6 + continue + except ValueError: + raise YamlError(f"第 {lineno} 行:非法的 \\u 转义") + raise YamlError(f"第 {lineno} 行:未知的转义 \\{nxt}") + out.append(ch) + i += 1 + return "".join(out) + + +def _split_flow(body: str, lineno: int) -> list[str]: + """按顶层逗号切分流式集合的内容。""" + parts = [] + buf = [] + depth = 0 + quote = "" + for ch in body: + if quote: + buf.append(ch) + if ch == quote: + quote = "" + continue + if ch in ("'", '"'): + quote = ch + buf.append(ch) + continue + if ch in "[{": + depth += 1 + elif ch in "]}": + depth -= 1 + if ch == "," and depth == 0: + parts.append("".join(buf)) + buf = [] + continue + buf.append(ch) + tail = "".join(buf) + if tail.strip() or parts: + parts.append(tail) + return [p.strip() for p in parts] + + +def _parse_flow_seq(body: str, lineno: int) -> list: + body = body.strip() + if not body: + return [] + return [_parse_scalar(p, lineno) for p in _split_flow(body, lineno)] + + +def _parse_flow_map(body: str, lineno: int) -> dict: + body = body.strip() + if not body: + return {} + out = {} + for part in _split_flow(body, lineno): + key, sep, value = _split_key(part) + if not sep: + raise YamlError(f"第 {lineno} 行:流式映射项格式错误: {part!r}") + out[_parse_scalar(key, lineno)] = _parse_scalar(value, lineno) + return out + + +# ── 块标量 ────────────────────────────────────────────────────────── +def _read_block_scalar( + raw_lines: list[str], start_raw: int, key_indent: int, style: str, lineno: int +) -> tuple[str, int]: + """读块标量(| 或 >)。返回 (文本, 消耗到的 raw 索引)。""" + folded = style[0] == ">" + chomp = "clip" + if style.endswith("-"): + chomp = "strip" + elif style.endswith("+"): + chomp = "keep" + + body: list[str] = [] + i = start_raw + block_indent: int | None = None + while i < len(raw_lines): + raw = raw_lines[i] + if raw.strip() == "": + body.append("") + i += 1 + continue + indent = len(raw) - len(raw.lstrip(" ")) + if indent <= key_indent: + break + if block_indent is None: + block_indent = indent + body.append(raw[block_indent:] if len(raw) >= block_indent else "") + i += 1 + + # 去掉尾部空行(按 chomp 策略再决定加不加回来) + while body and body[-1] == "": + body.pop() + i -= 1 + + if folded: + text = "" + for idx, ln in enumerate(body): + if idx == 0: + text = ln + elif ln == "" or body[idx - 1] == "": + text += "\n" + ln + else: + text += " " + ln + else: + text = "\n".join(body) + + if chomp == "strip": + return text, i + if chomp == "keep": + return text + "\n", i + return (text + "\n") if text else "", i + + +# ── 主解析 ────────────────────────────────────────────────────────── +def loads(text: str) -> Any: + """解析 YAML 文本。""" + raw_lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") + lines = _preprocess(raw_lines) + if not lines: + return None + value, idx = _parse_node(lines, 0, lines[0].indent, raw_lines) + if idx < len(lines): + raise YamlError(f"第 {lines[idx].lineno} 行:缩进异常") + return value + + +def _parse_node(lines: list[_Line], i: int, indent: int, raw_lines: list[str]) -> tuple[Any, int]: + if lines[i].text == _SEQ: + return _parse_sequence(lines, i, indent, raw_lines) + return _parse_mapping(lines, i, indent, raw_lines) + + +def _parse_mapping( + lines: list[_Line], i: int, indent: int, raw_lines: list[str] +) -> tuple[dict, int]: + result: dict = {} + while i < len(lines) and lines[i].indent == indent: + line = lines[i] + if line.text == _SEQ: + break + key, sep, rest = _split_key(line.text) + if not sep: + raise YamlError(f"第 {line.lineno} 行:期望 `key: value`,得到 {line.text!r}") + if key.startswith("&") or key.startswith("*") or key.startswith("!"): + raise YamlError(f"第 {line.lineno} 行:不支持锚点/别名/标签") + key_value = _parse_scalar(key, line.lineno) + + if rest and rest[0] in "|>": + value, consumed = _read_block_scalar( + raw_lines, line.raw_idx + 1, indent, rest, line.lineno + ) + result[key_value] = value + # 跳到块标量之后的第一条逻辑行 + i += 1 + while i < len(lines) and lines[i].raw_idx < consumed: + i += 1 + continue + + if rest == "": + nxt = lines[i + 1] if i + 1 < len(lines) else None + # 块序列可以与它的 key 同缩进(PyYAML 的写法),也可以更深 + if nxt is not None and ( + nxt.indent > indent + or (nxt.indent == indent and nxt.text == _SEQ) + ): + value, i = _parse_node(lines, i + 1, nxt.indent, raw_lines) + else: + value = None + i += 1 + else: + value = _parse_scalar(rest, line.lineno) + i += 1 + result[key_value] = value + return result, i + + +def _parse_sequence( + lines: list[_Line], i: int, indent: int, raw_lines: list[str] +) -> tuple[list, int]: + result: list = [] + while i < len(lines) and lines[i].indent == indent and lines[i].text == _SEQ: + marker = lines[i] + i += 1 + + if i >= len(lines): + result.append(None) + break + + content = lines[i] + if content.indent == indent + 2: + # 序列项是映射 + value, i = _parse_mapping(lines, i, content.indent, raw_lines) + result.append(value) + continue + + if content.indent != indent: + # 空项 / 嵌套块 + value, i = _parse_node(lines, i, content.indent, raw_lines) + result.append(value) + continue + + rest = content.text + if rest and rest[0] in "|>": + value, consumed = _read_block_scalar( + raw_lines, marker.raw_idx + 1, indent, rest, marker.lineno + ) + result.append(value) + i += 1 + while i < len(lines) and lines[i].raw_idx < consumed: + i += 1 + continue + + result.append(_parse_scalar(rest, marker.lineno)) + i += 1 + return result, i + + +# ── 序列化 ────────────────────────────────────────────────────────── +_PLAIN_SAFE = set( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./+@" +) + + +def _needs_quote(s: str) -> bool: + if s == "": + return True + if s.strip() != s: + return True + if s[0] in "-?:,[]{}#&*!|>'\"%@`": + return True + if ": " in s or " #" in s or s.endswith(":"): + return True + if "\n" in s or "\t" in s: + return True + if any(c not in _PLAIN_SAFE for c in s): + # 含中文、空格等 —— 加引号更安全 + return True + if s in _TRUE or s in _FALSE or s in _NULL: + return True + try: + float(s) + return True + except ValueError: + return False + + +def _dump_scalar(value: Any) -> str: + if value is None: + return "null" + if value is True: + return "true" + if value is False: + return "false" + if isinstance(value, (int, float)): + return str(value) + s = str(value) + if "\n" in s: + return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"' + if _needs_quote(s): + return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"' + return s + + +def dumps(data: Any, indent: int = 0) -> str: + """把数据序列化成 YAML 子集文本。""" + lines: list[str] = [] + + def emit(node: Any, level: int) -> None: + pad = " " * (level * 2) + if isinstance(node, dict): + for key, value in node.items(): + if isinstance(value, dict) and value: + lines.append(f"{pad}{key}:") + emit(value, level + 1) + elif isinstance(value, list) and value: + lines.append(f"{pad}{key}:") + emit(value, level + 1) + elif isinstance(value, dict): + lines.append(f"{pad}{key}: {{}}") + elif isinstance(value, list): + lines.append(f"{pad}{key}: []") + elif isinstance(value, str) and "\n" in value: + lines.append(f"{pad}{key}: |") + for ln in value.rstrip("\n").split("\n"): + lines.append(f"{pad} {ln}") + else: + lines.append(f"{pad}{key}: {_dump_scalar(value)}") + elif isinstance(node, list): + for item in node: + if isinstance(item, dict) and item: + first = True + for key, value in item.items(): + prefix = f"{pad}- " if first else f"{pad} " + first = False + if isinstance(value, dict) and value: + lines.append(f"{prefix}{key}:") + emit(value, level + 2) + elif isinstance(value, list) and value: + lines.append(f"{prefix}{key}:") + emit(value, level + 2) + elif isinstance(value, str) and "\n" in value: + lines.append(f"{prefix}{key}: |") + for ln in value.rstrip("\n").split("\n"): + lines.append(f"{pad} {ln}") + else: + lines.append(f"{prefix}{key}: {_dump_scalar(value)}") + elif isinstance(item, (list, dict)): + lines.append(f"{pad}-") + emit(item, level + 1) + else: + lines.append(f"{pad}- {_dump_scalar(item)}") + else: + lines.append(f"{pad}{_dump_scalar(node)}") + + emit(data, indent) + return "\n".join(lines) + "\n" diff --git a/harness-installer/README.md b/harness-installer/README.md new file mode 100644 index 0000000..3d7974d --- /dev/null +++ b/harness-installer/README.md @@ -0,0 +1,53 @@ +# harness-installer + +为任意项目铺好 **工程底座**:`AGENTS.md` + `docs/` 文档骨架 + `opencode.jsonc`。 + +``` +harness-installer/ +├── SKILL.md +├── scripts/init-harness.sh +└── templates/ + ├── AGENTS.md.template # 架构与工程规范模板(含 TODO 占位) + ├── opencode.jsonc + └── docs/ + ├── README.md + ├── features/_template.md + ├── plans/_template.md + ├── designs/README.md + ├── designs/topic/README.md + ├── standards/README.md + ├── standards/templates/README.md + └── test-cases/ + ├── README.md + ├── e2e-cases/test-cases.md + ├── manual-cases/manual-test-cases.md + ├── smoking-cases/smoking-test-cases.md + └── dev-self-cases/README.md +``` + +## 用法 + +```bash +# 预览 +./harness-installer/scripts/init-harness.sh ../my-project --dry-run + +# 执行 +./harness-installer/scripts/init-harness.sh ../my-project + +# 强制覆盖 +./harness-installer/scripts/init-harness.sh ../my-project --force +``` + +## 脚本做了什么 + +1. 探测项目结构:`backend/`(`pom.xml`)、`frontend/`(`package.json`)、`e2e/`、`docs/` +2. 渲染 `templates/AGENTS.md.template` → `<项目>/AGENTS.md` +3. 复制 `templates/docs/**` → `<项目>/docs/**` +4. 缺失时创建 `<项目>/opencode.jsonc` + +已存在的文件默认跳过,重复执行安全。 + +## 生成的 AGENTS.md 是"半成品" + +模板里的 `TODO` 段落需要项目负责人补全。参考实现见 +[`../example-project/AGENTS.md`](../example-project/AGENTS.md)。 diff --git a/harness-installer/SKILL.md b/harness-installer/SKILL.md new file mode 100644 index 0000000..cefa9d8 --- /dev/null +++ b/harness-installer/SKILL.md @@ -0,0 +1,69 @@ +--- +name: harness-installer +description: 初始化项目的工程 harness —— 生成/补齐 AGENTS.md(架构与工程规范)与 docs/ 文档骨架(features/plans/designs/standards/test-cases 等)。当用户说"初始化项目"、"生成 AGENTS.md"、"建文档骨架"、"harness 安装"、"新项目接入规范"时使用。 +--- + +# Harness 初始化器 + +为一个项目铺好 **工程底座**:`AGENTS.md`(唯一权威工程约定)+ `docs/`(文档体系骨架)+ `opencode.jsonc`(工具配置)。 + +典型场景: + +- 新项目接入团队规范,需要一份 `AGENTS.md` 和文档骨架 +- `example-project` 这类参考项目的骨架被删了,需要重建 +- 给新团队成员一个可运行的最小 harness + +## 前置:先确认目标 + +安装前必须确认 **目标项目目录**(绝对路径)。用户没说清楚就用 `question` 工具问, +不要默认装到当前目录。 + +## 执行 + +```bash +# 从本 skill 所在目录执行 +./harness-installer/scripts/init-harness.sh <目标项目目录> --dry-run # 先预览 +./harness-installer/scripts/init-harness.sh <目标项目目录> +``` + +| 参数 | 说明 | +|---|---| +| `--dry-run` | 只打印将要发生的改动,不写文件 | +| `--force` | 覆盖已存在的 `AGENTS.md` 与文档文件 | +| `--no-agents` | 只生成 `docs/` 骨架,不动 `AGENTS.md` | + +脚本会: + +1. **探测项目结构**:找后端(有 `pom.xml`/`build.gradle`)、前端(有 `package.json`)、E2E 目录 +2. **渲染 `AGENTS.md`**:把模板里的 `{{...}}` 占位符替换成探测结果,写入 `<项目>/AGENTS.md` +3. **铺 `docs/` 骨架**:复制 `templates/docs/**` 到 `<项目>/docs/**` +4. **确保 `opencode.jsonc`**:不存在则创建(注册 `.agent/skills` 路径) + +## 生成后必须做的事 + +`AGENTS.md` 里的 `TODO` 段落 **不会** 被自动填好,必须补全,否则规范形同虚设: + +| TODO 段落 | 要写什么 | +|---|---| +| §1 仓库拓扑 | 真实技术栈、各模块职责、运行时形态 | +| §2 鉴权与用户上下文 | 认证方式、token 传递、当前用户获取方式、权限模型 | +| §3 标准分层 | 实际分层与包路径 | +| §5 持久化规则 | ORM / Mapper、主键策略、聚合装配方式 | +| §8 领域设计 | 核心聚合、业务规则引擎、数据字典注册方式 | +| §9 状态机 | 核心状态机图与守卫方法 | +| §10 测试规范 | 单元/集成/E2E 框架、数据库测试方案 | +| §11 前端规范 | 框架版本、状态管理、路由、HTTP 封装约定 | + +可以用 `example-project/AGENTS.md` 作为 **填写范例** —— 那是本仓库里已经填好的完整版本。 + +## 幂等性 + +- 已存在的 `AGENTS.md` / 文档文件默认 **跳过**(不覆盖),只有 `--force` 才覆盖 +- `opencode.jsonc` 已存在时 **不修改** +- 因此可以放心在已有项目上重复执行 + +## 相关 + +- `agile-team-sdd/` — 装 SDD skills(dev-plan / dev-build / dev-debug),应在 harness 初始化 **之后** 执行 +- `tool-chain-installer/` — 装 MCP 工具链 +- `team-workflow-guide/` — 团队角色与协作约定 diff --git a/harness-installer/scripts/init-harness.sh b/harness-installer/scripts/init-harness.sh new file mode 100755 index 0000000..07e74b7 --- /dev/null +++ b/harness-installer/scripts/init-harness.sh @@ -0,0 +1,189 @@ +#!/usr/bin/env bash +# 初始化项目的 harness:AGENTS.md + docs/ 文档骨架 + opencode 配置。 +# +# 用法: +# ./init-harness.sh <目标项目目录> [--dry-run] [--force] [--no-agents] +# +# --dry-run 只打印将要发生的改动,不写文件 +# --force 覆盖目标项目里已存在的 AGENTS.md / 文档文件 +# --no-agents 不生成 AGENTS.md,只生成 docs/ 骨架 + +set -euo pipefail + +INSTALLER_DIR="$(cd "$(dirname "$0")/.." && pwd)" +TEMPLATE_DIR="$INSTALLER_DIR/templates" + +DRY_RUN=0 +FORCE=0 +NO_AGENTS=0 + +usage() { + sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//' + exit "${1:-0}" +} + +while [ $# -gt 0 ]; do + case "$1" in + --dry-run) DRY_RUN=1 ;; + --force) FORCE=1 ;; + --no-agents) NO_AGENTS=1 ;; + -h|--help) usage 0 ;; + -*) echo "未知参数: $1" >&2; usage 1 ;; + *) TARGET="$1" ;; + esac + shift +done + +if [ -z "${TARGET:-}" ]; then + echo "错误:缺少目标项目目录。" >&2 + usage 1 +fi + +if [ ! -d "$TARGET" ]; then + echo "错误:目标目录不存在: $TARGET" >&2 + exit 1 +fi + +PROJECT_ROOT="$(cd "$TARGET" && pwd)" +PROJECT_NAME="${PROJECT_NAME:-$(basename "$PROJECT_ROOT")}" + +# ── 自动探测项目结构 ──────────────────────────────────────────────── +detect_dir() { + # detect_dir <候选1> <候选2> ... <探测文件> + local candidate found="" + local probe="${!#}" + for candidate in "${@:1:$#-1}"; do + if [ -e "$PROJECT_ROOT/$candidate/$probe" ]; then + found="$candidate" + break + fi + done + echo "$found" +} + +BACKEND_DIR="${BACKEND_DIR:-$(detect_dir backend service server api pom.xml)}" +[ -z "$BACKEND_DIR" ] && BACKEND_DIR="backend" +FRONTEND_DIR="${FRONTEND_DIR:-$(detect_dir frontend web client ui package.json)}" +[ -z "$FRONTEND_DIR" ] && FRONTEND_DIR="frontend" +E2E_DIR="${E2E_DIR:-$(detect_dir e2e tests test package.json)}" +[ -z "$E2E_DIR" ] && E2E_DIR="e2e" +DOCS_DIR="${DOCS_DIR:-docs}" +E2E_CASES_DIR="${E2E_CASES_DIR:-$DOCS_DIR/test-cases/e2e-cases}" +E2E_RUNNER="${E2E_RUNNER:-e2e-run.sh}" +FEATURES_DIR="${FEATURES_DIR:-$DOCS_DIR/features}" +PLANS_DIR="${PLANS_DIR:-$DOCS_DIR/plans}" +DESIGNS_DIR="${DESIGNS_DIR:-$DOCS_DIR/designs}" +STANDARDS_DIR="${STANDARDS_DIR:-$DOCS_DIR/standards}" + +BACKEND_DESC="${BACKEND_DESC:-后端服务}" +FRONTEND_DESC="${FRONTEND_DESC:-前端应用}" +BACKEND_NAME="${BACKEND_NAME:-后端服务}" +FRONTEND_NAME="${FRONTEND_NAME:-前端应用}" +DATABASE="${DATABASE:-数据库}" +TECH_STACK="${TECH_STACK:-见项目 README}" +ERROR_CODE_EXAMPLE="${ERROR_CODE_EXAMPLE:-BUSINESS_ERROR}" +ERROR_MESSAGE_EXAMPLE="${ERROR_MESSAGE_EXAMPLE:-业务规则不满足}" + +# ── 占位符表(从长到短)────────────────────────────────────────────── +PAIRS=( + "TECH_STACK=$TECH_STACK" + "BACKEND_DESC=$BACKEND_DESC" + "FRONTEND_DESC=$FRONTEND_DESC" + "BACKEND_NAME=$BACKEND_NAME" + "FRONTEND_NAME=$FRONTEND_NAME" + "DATABASE=$DATABASE" + "ERROR_CODE_EXAMPLE=$ERROR_CODE_EXAMPLE" + "ERROR_MESSAGE_EXAMPLE=$ERROR_MESSAGE_EXAMPLE" + "TEST_CMD_BACKEND=cd $PROJECT_ROOT/$BACKEND_DIR && mvn test" + "TEST_CMD_FRONTEND=cd $PROJECT_ROOT/$FRONTEND_DIR && npm run build" + "E2E_CASES_DIR=$PROJECT_ROOT/$E2E_CASES_DIR" + "E2E_RUNNER=$PROJECT_ROOT/$E2E_RUNNER" + "E2E_DIR=$PROJECT_ROOT/$E2E_DIR" + "STANDARDS_DIR=$PROJECT_ROOT/$STANDARDS_DIR" + "DESIGNS_DIR=$PROJECT_ROOT/$DESIGNS_DIR" + "PLANS_DIR=$PROJECT_ROOT/$PLANS_DIR" + "FEATURES_DIR=$PROJECT_ROOT/$FEATURES_DIR" + "DOCS_DIR=$PROJECT_ROOT/$DOCS_DIR" + "FRONTEND_DIR=$PROJECT_ROOT/$FRONTEND_DIR" + "BACKEND_DIR=$PROJECT_ROOT/$BACKEND_DIR" + "PROJECT_NAME=$PROJECT_NAME" + "PROJECT_ROOT=$PROJECT_ROOT" +) + +escape_replacement() { + printf '%s' "$1" | sed -e 's/[\\&|]/\\&/g' +} + +render() { + local file="$1" out="$2" + local args=() + local pair key value + for pair in "${PAIRS[@]}"; do + key="${pair%%=*}" + value="${pair#*=}" + args+=(-e "s|{{$key}}|$(escape_replacement "$value")|g") + done + sed "${args[@]}" "$file" > "$out" +} + +# ── 执行 ───────────────────────────────────────────────────────────── +created=0 +skipped=0 + +write_file() { + local src="$1" dest="$2" + if [ -f "$dest" ] && [ "$FORCE" -eq 0 ]; then + echo " [跳过] ${dest#$PROJECT_ROOT/}(已存在,用 --force 覆盖)" + skipped=$((skipped + 1)) + return + fi + if [ "$DRY_RUN" -eq 1 ]; then + echo " [计划] 生成 ${dest#$PROJECT_ROOT/}" + else + mkdir -p "$(dirname "$dest")" + render "$src" "$dest" + echo " [生成] ${dest#$PROJECT_ROOT/}" + fi + created=$((created + 1)) +} + +echo "Harness 初始化器" +echo " 模板目录 : $TEMPLATE_DIR" +echo " 目标项目 : $PROJECT_ROOT" +echo " 探测结果 : backend=$BACKEND_DIR frontend=$FRONTEND_DIR e2e=$E2E_DIR docs=$DOCS_DIR" +echo "" + +if [ "$NO_AGENTS" -eq 0 ]; then + write_file "$TEMPLATE_DIR/AGENTS.md.template" "$PROJECT_ROOT/AGENTS.md" +fi + +# docs/ 骨架:递归拷贝模板目录 +while IFS= read -r src; do + rel="${src#$TEMPLATE_DIR/docs/}" + write_file "$src" "$PROJECT_ROOT/$DOCS_DIR/$rel" +done < 本文件由 `harness-installer` 生成,是本代码库的 **唯一权威工程约定**。 +> 新成员与自动化工具在不了解上下文的情况下,也应按本文件一致地新增功能、扩展模块并避免破坏依赖关系。 +> +> **待补充**:标有 `TODO` 的段落需要由项目负责人填写后生效。 + +## 1. 仓库拓扑 + +这是一个全栈工程,技术栈:{{TECH_STACK}} + +主要模块: + +- `{{BACKEND_DIR}}/`:{{BACKEND_DESC}} +- `{{FRONTEND_DIR}}/`:{{FRONTEND_DESC}} + +运行时形态: + +``` +Client → {{FRONTEND_NAME}} → /api 代理 → {{BACKEND_NAME}} → {{DATABASE}} +``` + +## 2. 横切关注点:鉴权与用户上下文 + +- TODO:写明认证方式(JWT / Session / OAuth2) +- TODO:写明 token 存放位置与请求头约定 +- TODO:写明后端如何获取当前用户(ThreadLocal / 拦截器注入 / 方法参数) +- TODO:写明权限模型(RBAC / ABAC)与管理员路径约定 + +约束: + +- 后端自行校验认证信息(不在前端或网关层做) +- application / domain 层不得依赖 Web 框架对象(Request / Response) +- 对外接口必须做鉴权检查 + +## 3. 标准分层 + +TODO:写明分层结构与包路径。 + +依赖方向(强制): + +- adapter → application → domain +- infrastructure → domain(实现 domain 定义的接口) +- domain 不得依赖 infrastructure / adapter / Web 框架 + +## 4. DTO、Assembler 与 Converter 约定 + +- 写操作入参使用 `*Command` 或 Request DTO +- 对外返回使用 `*Response` +- domain 与 infrastructure 之间使用 `*Converter` 做 PO ⟷ domain 转换 +- application 层使用 `*Assembler` 做 domain ⟷ DTO 转换 +- 映射约定:adapter 不直接操作 domain 实体;使用手动转换,遵循现有命名 + +## 5. 持久化规则 + +- TODO:写明 ORM / Mapper 框架与版本 +- PO 放在 `{{BACKEND_DIR}}/**/persistence/po/` +- Mapper 放在 `{{BACKEND_DIR}}/**/persistence/mapper/` +- Repository:domain 只定义接口,infrastructure 提供实现(`*RepositoryImpl`) +- 主键策略:TODO +- 聚合与一致性:聚合内子实体由 repository 在同一事务内装配与持久化 + +## 6. 事务边界 + +事务边界统一放在 application 层: + +- 以一个用例为单位在 AppService 方法上标注 `@Transactional` +- domain 方法不直接开启 / 提交事务 +- `@Transactional` 不在 Controller 或 Repository 层使用 + +## 7. 错误模型与异常处理 + +- 业务错误:抛 `BusinessException`(携带 errorCode 与 message) +- 参数错误:抛 `IllegalArgumentException`,由 `GlobalExceptionHandler` 转为 HTTP 400 +- 权限错误:由框架返回 HTTP 401 / 403 +- 资源冲突:HTTP 409 + +对外响应由 `GlobalExceptionHandler` 统一包装: + +```json +{ + "errorCode": "{{ERROR_CODE_EXAMPLE}}", + "message": "{{ERROR_MESSAGE_EXAMPLE}}", + "timestamp": "..." +} +``` + +## 8. 领域设计:聚合与规则 + +TODO:列出核心聚合(名称 + 关键字段)、业务规则引擎位置、数据字典注册方式。 + +## 9. 状态机 + +TODO:贴出核心状态机图,并写明状态流转由哪个 domain 守卫方法控制。 + +## 10. 测试规范 + +### 两类用例的归属 + +测试用例分两层,**归属看"谁定义、谁判定",不是"谁敲的代码"**: + +| | 开发自测 | QA 测试 | +|---|---|---| +| 验证什么 | 代码按 Plan 的设计工作 | 系统符合需求规格 | +| 谁定义 / 谁判定 | 开发本人 | **QA** | +| 用例编号 | 无编号,命名表达意图 | `TC-xxx`,与文本用例一一对应 | +| 存放位置 | 源码旁(`*Test.java`、`*.test.ts`) | `{{DOCS_DIR}}/` 用例库 + `{{E2E_DIR}}/tests/qa/` | +| 合并闸门 | 否 | **是** | +| 失败意味着 | 代码写错了 | 需求没实现 / 理解有偏差 / 规格有歧义 | + +约定: + +- QA 用例的自动化实现可由开发代写,但定义权与判定权归 QA +- 开发自测全绿 ≠ 需求被实现,不能替代 QA 测试 +- QA 用例必须先有文本用例(`{{E2E_CASES_DIR}}/`),再写自动化 + +### 测试技术栈 + +- TODO:单元测试框架、集成测试框架、数据库测试方案 +- 测试使用 `schema.sql` + `data.sql` 初始化数据 +- 每个用例前重置数据库,保证可重复执行、不依赖执行顺序 + +### 开发自测覆盖要求 + +- 每个 API **必须** 有对应的集成测试 +- 至少覆盖:1 个 Happy Path + 关键失败分支(参数错误 / 权限不足 / 业务冲突) +- 前端组件 / Composable 单元测试使用 Vitest(与源码同目录,`*.test.ts`) +- 命名:类名 `{被测Controller}Test`,方法名 `should_{action}_{expectedResult}`(不写 `TC-` 编号) + +### QA 测试要求 + +- 需求规格的每条验收标准、每条业务规则 → 至少 1 条 QA 用例 +- 编号统一 `TC-xxx`,文本用例与自动化用例共用同一编号 +- 四类产物:文本用例 `{{E2E_CASES_DIR}}/`、E2E 自动化 `{{E2E_DIR}}/tests/qa/`、手动用例 `{{DOCS_DIR}}/manual-cases/`、冒烟用例 `{{DOCS_DIR}}/smoking-cases/` +- 用例可独立重复执行,不依赖执行顺序 + +### E2E 测试 + +- Playwright + Chromium,按归属分两层: + +| 目录 | 归属 | 说明 | +|---|---|---| +| `{{E2E_DIR}}/tests/qa/` | **QA 测试** | 验收用例的自动化实现,与 `{{E2E_CASES_DIR}}/test-cases.md` 一一对应,合并闸门 | +| `{{E2E_DIR}}/tests/dev/` | 开发自测 | 开发期快速反馈,不作为验收依据 | + +- 运行命令:`{{E2E_RUNNER}}` + +## 11. 前端规范 + +- TODO:写明框架版本与组合式 API / 类组件约定 +- 状态管理:TODO +- 路由:TODO +- HTTP 封装:TODO +- 视图文件按子系统分组:`{{FRONTEND_DIR}}/src/views//` +- Service 层封装 API 调用,Composable 封装可复用逻辑 +- 页面级组件组合 Composable + UI 组件,视图内不含直接 API 调用 + +## 12. PR / 变更检查清单 + +- [ ] 分层检查:adapter 不含业务逻辑;domain 不依赖 infrastructure;事务边界在 application +- [ ] 错误处理:业务校验使用 `BusinessException`,避免裸 `RuntimeException` +- [ ] API 设计:RESTful 风格,路径统一 `/api/v1/resource` +- [ ] 安全:不记录 token / 敏感信息;对外接口做鉴权检查 +- [ ] 数据字典:新增枚举需要同时更新注册类与 `{{DESIGNS_DIR}}/topic/data-dict.md` +- [ ] 业务规则:新增规则需要同时更新规则配置与 `{{DESIGNS_DIR}}/topic/businessrule.md` +- [ ] 数据库变更:新增 DDL 需同时更新迁移脚本、测试 `schema.sql` 与 `{{DESIGNS_DIR}}/db-schema.md` +- [ ] 验证:本地运行 `{{TEST_CMD_BACKEND}}` 与 `{{TEST_CMD_FRONTEND}}` 全部通过 +- [ ] 文档同步检查(已更新 / 不涉及) + +## 13. 文档结构 + +``` +{{DOCS_DIR}}/ +├── features/ # 需求规格(过程文档) +│ └── _template.md +├── plans/ # 技术方案(过程文档) +│ └── _template.md +├── designs/ # 设计文档(事实文档) +│ ├── api.yaml +│ ├── db-schema.md +│ ├── domain-model.md +│ └── topic/ +├── standards/ # 代码规范(事实文档) +│ ├── architecture.md +│ ├── naming.md +│ ├── security.md +│ ├── api-design.md +│ ├── layers.md +│ ├── db.md +│ ├── error.md +│ ├── test.md +│ └── templates/ +├── e2e-cases/ # QA 用例:E2E 验收用例文本基线 +├── manual-cases/ # QA 用例:手动执行用例 +└── smoking-cases/ # QA 用例:快速回归(冒烟)用例 +``` + +> `{{DOCS_DIR}}/` 下的 `e2e-cases/`、`manual-cases/`、`smoking-cases/` 均为 **QA 测试** 产物(定义权与判定权归 QA); +> 开发自测用例放在源码旁(`*Test.java`、`*.test.ts`)与 `{{E2E_DIR}}/tests/dev/`。归属详见 §10 与 `{{STANDARDS_DIR}}/test.md`。 + +### 同步要求 + +- 每轮任务完成后,必须检查 `{{DESIGNS_DIR}}/` 中的内容是否因本次变更而需要更新 +- 新增 / 修改 API → 更新 `{{DESIGNS_DIR}}/api.yaml` +- 新增 / 修改数据表 → 更新 `{{DESIGNS_DIR}}/db-schema.md` +- 新增 / 修改业务规则 → 更新 `{{DESIGNS_DIR}}/topic/businessrule.md` +- 新增 / 修改数据字典 → 更新 `{{DESIGNS_DIR}}/topic/data-dict.md` + +### 执行检查点 + +每轮任务提交描述中必须包含: + +- [ ] `{{DOCS_DIR}}/` 同步检查(已更新 / 不涉及) + +## 14. 开发流程(每轮需求的标准执行步骤) + +每轮需求开发必须按以下顺序执行,严禁跳过或调换步骤: + +1. **Plan 等待确认**:在 `{{PLANS_DIR}}/` 下根据模板创建 Plan,包含技术方案与任务拆分,等待人工确认后再继续。 +2. **编写 QA 测试用例**:在 `{{E2E_CASES_DIR}}/` 下编写本轮需求的 E2E 测试用例(文本格式,编号 `TC-xxx`),由 QA 主导判定。**先写文本用例,再写自动化**。 +3. **编写开发自测(API 测试)**:根据 Plan 在 `{{BACKEND_DIR}}/src/test/` 中编写集成测试(TDD 红牌阶段)。 +4. **编写实现**:编写单元测试 + 实现代码,通过后端编译。 +5. **运行开发自测**:运行后端测试,修复失败用例直至全部通过;同时补齐 `{{E2E_DIR}}/tests/qa/` 中本轮需求的自动化实现。 +6. **浏览器调试**:使用 Playwright 启动前后端并调试,确认前端视觉效果和交互功能正常。 +7. **运行 QA 验收**:`{{E2E_DIR}}` 下跑 QA 用例集全部通过,并交由 QA 对照 `{{E2E_CASES_DIR}}/` 逐条验收。 + +> 第 3~6 步是 **开发自测**(对开发负责);第 2、7 步是 **QA 测试**(对需求负责,是合并闸门)。开发自测全绿不等于需求已实现。 diff --git a/harness-installer/templates/docs/README.md b/harness-installer/templates/docs/README.md new file mode 100644 index 0000000..8732c53 --- /dev/null +++ b/harness-installer/templates/docs/README.md @@ -0,0 +1,47 @@ +# 文档体系 + +本目录是项目的 **单一信息源**。文档分两类: + +| 类别 | 目录 | 性质 | 生命周期 | +|---|---|---|---| +| 过程文档 | `features/`、`plans/` | 会随需求演进 | 随需求创建,**定稿后不再修改** | +| 事实文档 | `designs/`、`standards/` | 描述系统当前真实状态 | 随代码同步更新 | + +## 目录 + +| 目录 | 内容 | 谁来写 | +|---|---|---| +| `features/` | 需求规格说明书:背景、字段表、业务规则、权限、验收标准 | 产品 / BA | +| `plans/` | 技术方案:领域模型、DDL、API、时序图、任务拆分、风险 | 架构师 / 负责人 | +| `designs/` | 设计文档(事实):API 定义、库表、领域模型、业务流程、专题 | 全员,随代码同步 | +| `designs/topic/` | 单点技术专题的深度说明 | 需要时新建 | +| `standards/` | 代码规范(事实):架构、命名、分层、安全、API、错误、测试 | 架构师 | +| `standards/templates/` | 代码模版 / snippet,供参考复制 | 架构师 | +| `test-cases/` | 测试用例文本基线(见下) | QA / 开发 | + +### `test-cases/` 子目录 + +| 子目录 | 归属 | 内容 | +|---|---|---| +| `test-cases/e2e-cases/` | **QA 测试** | E2E 验收用例文本基线(`TC-xxx`),合并闸门 | +| `test-cases/manual-cases/` | **QA 测试** | 需人工执行的用例(`TC-Mxx`) | +| `test-cases/smoking-cases/` | **QA 测试** | 上线前快速回归用例(`TC-Sxx`) | +| `test-cases/dev-self-cases/` | **开发自测** | 可选自测场景索引(实现仍在源码旁 / `e2e/tests/dev/`) | + +> QA 三目录:定义权与判定权归 QA,是合并闸门。 +> `dev-self-cases/` 对开发负责,不是合并闸门。归属细则见 `standards/test.md`。 + +## 写作约定 + +- 需求规格与 Plan **定稿后不改**;同一资源的二次改造新建文件(`YYYYMMDD-{slug}.md`)。 +- 事实文档必须与代码一致;改了代码就要改文档。 +- 新建需求先复制 `_template.md` 再改,不要从零写。 + +## 同步检查点 + +每轮任务结束时必须回答: + +- [ ] 本次变更是否影响 `designs/api.yaml`? +- [ ] 本次变更是否影响 `designs/db-schema.md`? +- [ ] 本次变更是否影响 `designs/topic/businessrule.md`? +- [ ] 本次变更是否影响 `designs/topic/data-dict.md`? diff --git a/harness-installer/templates/docs/designs/README.md b/harness-installer/templates/docs/designs/README.md new file mode 100644 index 0000000..548ff19 --- /dev/null +++ b/harness-installer/templates/docs/designs/README.md @@ -0,0 +1,42 @@ +# 设计文档(事实) + +本目录描述系统 **当前的真实状态**,必须与代码保持一致。 + +## 子目录 + +| 路径 | 内容 | +|---|---| +| `api.yaml` | OpenAPI 格式的接口定义 | +| `db-schema.md` | 数据库表结构与索引说明 | +| `domain-model.md` | 领域模型:聚合、实体、值对象、关系 | +| `topic/` | 单点技术专题(鉴权、状态机、业务规则、数据字典……) | + +## 维护规则 + +- 改了接口 → 更新 `api.yaml` +- 改了表结构 → 更新 `db-schema.md` +- 改了业务规则 → 更新 `topic/businessrule.md` +- 改了数据字典 → 更新 `topic/data-dict.md` +- 新增专题 → 在 `topic/` 下新建文件,并在本表登记 + +## 模板 + +```markdown +# {{专题名称}} + +## 背景 + +{{为什么需要这个专题}} + +## 方案 + +{{具体做法}} + +## 取舍 + +{{考虑过但放弃的方案及原因}} + +## 影响 + +{{对其他模块的影响}} +``` diff --git a/harness-installer/templates/docs/designs/topic/README.md b/harness-installer/templates/docs/designs/topic/README.md new file mode 100644 index 0000000..958f826 --- /dev/null +++ b/harness-installer/templates/docs/designs/topic/README.md @@ -0,0 +1,31 @@ +# 技术专题(Topic) + +每个文件解决 **一个** 技术问题:为什么这么做、怎么做、放弃了什么。 + +## 已有专题 + +| 文件 | 专题 | +|---|---| +| `businessrule.md` | 业务规则引擎:规则定义、配置、注册、查询 | +| `data-dict.md` | 数据字典:枚举定义、注册方式、对外查询接口 | +| `error-code.md` | 错误码规范:分段、命名、映射到 HTTP 状态码 | +| `security.md` | 安全设计:认证、鉴权、密码、越权防护 | +| `state-machine.md` | 状态机:状态、流转、守卫方法、非法流转处理 | + +## 新增专题 + +1. 新建 `{topic}.md` +2. 用下面的模板 +3. 在上面的表格中登记 + +```markdown +# {{专题名称}} + +## 背景 + +## 方案 + +## 取舍 + +## 影响 +``` diff --git a/harness-installer/templates/docs/features/_template.md b/harness-installer/templates/docs/features/_template.md new file mode 100644 index 0000000..2e0e988 --- /dev/null +++ b/harness-installer/templates/docs/features/_template.md @@ -0,0 +1,475 @@ +# 需求规格说明书:<需求名称> + +> 文档类型:需求规格 / Feature Specification +> 适用目录:`docs/features/` +> 需求类型:NEW / UPDATE +> 版本:v0.1 +> 作者: +> 日期:YYYY-MM-DD + +--- + +## 1. 需求说明 + +### 1.1 需求名称 + +<需求名称> + +### 1.2 需求类型 + +NEW / UPDATE + +### 1.3 版本信息 + +> 当需求类型为 NEW 时,可填写"无"。 +> 当需求类型为 UPDATE 时,必须填写基线版本和目标版本。 + +| 项目 | 内容 | +|---|---| +| 基线版本 | <例如:v1.2;NEW 可填"无"> | +| 目标版本 | <例如:v1.3> | + +### 1.4 背景 + +<说明为什么要做该需求。> + +### 1.5 目标 + +<说明该需求要解决什么问题,以及完成后的业务效果。> + +### 1.6 范围 + +本次需求包含: + +- <范围 1> +- <范围 2> +- <范围 3> + +--- + +## 2. 功能说明 + +### 2.1 功能概述 + +<用简洁语言说明本模块要实现或变更的核心功能。> + +### 2.2 适用用户 + +| 用户角色 | 角色说明 | 使用场景 | +|---|---|---| +| <角色 A> | <说明> | <使用场景> | +| <角色 B> | <说明> | <使用场景> | + +### 2.3 主要业务对象 + +| 业务对象 | 说明 | +|---|---| +| <业务对象 A> | <说明> | +| <业务对象 B> | <说明> | + +--- + +## 3. 用户角色与权限 + +| 角色 | 可查看 | 可新增 | 可编辑 | 可删除 | 可审批 | 说明 | +|---|---:|---:|---:|---:|---:|---| +| <角色 A> | 是 | 是 | 是 | 否 | 否 | <说明> | +| <角色 B> | 是 | 否 | 否 | 否 | 是 | <说明> | + +### 3.1 权限规则 + +- PR-001:<角色 A> 可以 <操作> <资源>。 +- PR-002:<角色 B> 不允许 <操作> <资源>。 +- PR-003:当用户无权限访问数据时,系统应拒绝操作并返回明确错误原因。 + +--- + +## 4. 业务流程 + +### 4.1 主流程 + +1. 用户进入 <模块名称>。 +2. 用户执行 <关键动作>。 +3. 系统校验 <关键业务条件>。 +4. 系统创建 / 查询 / 更新 / 删除 <业务对象>。 +5. 系统返回处理结果。 + +### 4.2 异常流程 + +| 编号 | 触发条件 | 系统行为 | 结果 | +|---|---|---|---| +| EX-001 | <条件> | <系统如何处理> | <返回结果> | +| EX-002 | <条件> | <系统如何处理> | <返回结果> | + +--- + +## 5. 字段表 + +> 所有业务数据以本字段表为准。 +> 本节只描述业务字段、校验规则、数据来源和业务含义。 +> 前端样式、布局、动效和交互细节,以原型 HTML 为准,不在本文档中展开。 + +### 5.1 完整字段表 + +> NEW 需求:填写本模块完整字段。 +> UPDATE 需求:填写变更后的完整字段表。 + +| 字段名 | 中文名 | 类型 | 必填 | 描述 | 取值 / 枚举 / 来源 | 创建时必填 | 可修改 | +|---|---|---|---:|---|---|---:|---:| +| id | ID | string | 是 | 业务对象唯一标识 | 系统生成 | 否 | 否 | +| name | 名称 | string | 是 | <字段含义> | 用户输入 | 是 | 是 | +| status | 状态 | enum | 否 | 当前状态 | 枚举:enabled=启用,表示可正常使用;disabled=禁用,表示不可使用但数据保留 | 否 | 是 | +| createdAt | 创建时间 | date | 是 | 数据创建时间 | 系统生成 | 否 | 否 | +| updatedAt | 更新时间 | date | 是 | 数据最后更新时间 | 系统生成 | 否 | 否 | + +说明: + +- 类型建议使用:string / number / boolean / date / enum / object / array。 +- 取值 / 枚举 / 来源用于说明字段值从哪里来,或枚举字段有哪些可选值。 +- 枚举字段应在本列中直接写明枚举值、中文含义和业务说明。 + +--- + +## 6. 字段变更说明 + +> 仅当需求类型为 UPDATE 时填写。 +> 必须使用 ADD / MODIFY / REMOVE 标记。 +> 当需求类型为 NEW 时,本节可写"无"。 + +### 6.1 [ADD] + +| 字段名 | 中文名 | 类型 | 必填 | 描述 | 取值 / 枚举 / 来源 | 创建时必填 | 可修改 | +|---|---|---|---:|---|---|---:|---:| +| | <中文名> | <类型> | 是 / 否 | <描述> | <来源或枚举说明> | 是 / 否 | 是 / 否 | + +### 6.2 [MODIFY] + +字段:<字段名> + +- 原:<原字段定义、原校验或原业务含义> +- 新:<新字段定义、新校验或新业务含义> + +字段:<字段名> + +- 原:<原内容> +- 新:<新内容> + +### 6.3 [REMOVE] + +移除字段: + +- <字段名 1> +- <字段名 2> + +--- + +## 7. 业务规则 + +> 所有业务行为必须通过规则定义。 +> 每条规则必须具备规则 ID、适用场景、条件和动作。 +> 每条规则应保持独立、可测试、可追踪。 + +### 7.1 通用规则 + +R-COMMON-001:<规则名称> + +- 适用场景:COMMON +- 条件:<触发条件> +- 动作:<系统行为> + +R-COMMON-002:<规则名称> + +- 适用场景:COMMON +- 条件:<触发条件> +- 动作:<系统行为> + +### 7.2 创建规则 + +R-CREATE-001:必填字段校验 + +- 适用场景:CREATE +- 条件:用户提交创建请求,且存在必填字段为空 +- 动作:系统拒绝创建,并返回字段级校验错误 + +R-CREATE-002:唯一性校验 + +- 适用场景:CREATE +- 条件:用户提交创建请求,且 `<唯一字段>` 已存在 +- 动作:系统拒绝创建,并提示数据已存在 + +R-CREATE-003:创建审计信息记录 + +- 适用场景:CREATE +- 条件:数据创建成功 +- 动作:系统记录创建人和创建时间 + +### 7.3 查询规则 + +R-QUERY-001:权限范围查询 + +- 适用场景:QUERY +- 条件:用户查询数据 +- 动作:系统仅返回用户权限范围内的数据 + +R-QUERY-002:默认排序 + +- 适用场景:QUERY +- 条件:用户未指定排序条件 +- 动作:系统按 `<排序字段>` 倒序返回结果 + +R-QUERY-003:分页返回 + +- 适用场景:QUERY +- 条件:用户查询列表数据 +- 动作:系统返回总数、当前页、页大小和结果列表 + +### 7.4 修改规则 + +R-UPDATE-001:编辑权限校验 + +- 适用场景:UPDATE +- 条件:用户修改数据 +- 动作:系统校验用户是否具备编辑权限;无权限时拒绝修改 + +R-UPDATE-002:修改审计信息记录 + +- 适用场景:UPDATE +- 条件:数据修改成功 +- 动作:系统记录最后修改人和最后修改时间 + +R-UPDATE-003:终态不可修改 + +- 适用场景:UPDATE +- 条件:数据已处于 `<终态>` +- 动作:系统拒绝修改 + +### 7.5 删除规则 + +R-DELETE-001:删除权限校验 + +- 适用场景:DELETE +- 条件:用户删除数据 +- 动作:系统校验用户是否具备删除权限;无权限时拒绝删除 + +R-DELETE-002:逻辑删除 + +- 适用场景:DELETE +- 条件:用户删除数据且校验通过 +- 动作:系统执行逻辑删除,不进行物理删除 + +R-DELETE-003:引用数据不可删除 + +- 适用场景:DELETE +- 条件:数据已被其他业务引用 +- 动作:系统拒绝删除,并提示数据已被使用 + +--- + +## 8. 业务规则变更说明 + +> 仅当需求类型为 UPDATE 时填写。 +> 必须使用 ADD / MODIFY / REMOVE 标记。 +> 当需求类型为 NEW 时,本节可写"无"。 + +### 8.1 [ADD] + +R-ADD-001:<规则名称> + +- 适用场景:CREATE / UPDATE / QUERY / DELETE / COMMON +- 条件:<触发条件> +- 动作:<系统行为> + +### 8.2 [MODIFY] + +R-UPDATE-001:<规则名称> + +- 原:<原规则内容> +- 新:<新规则内容> + +### 8.3 [REMOVE] + +移除规则: + +- <规则 ID 1> +- <规则 ID 2> + +--- + +## 9. 状态流转规则 + +> 如本模块不存在状态流转,可写"无"。 + +| 当前状态 | 触发动作 | 目标状态 | 允许角色 | 规则编号 | +|---|---|---|---|---| +| draft | submit | pending | <角色> | R-STATE-001 | +| pending | approve | approved | <角色> | R-STATE-002 | +| pending | reject | rejected | <角色> | R-STATE-003 | + +R-STATE-001:提交 + +- 适用场景:UPDATE +- 条件:数据处于 draft 状态,且用户具备提交权限 +- 动作:系统将状态变更为 pending + +R-STATE-002:审批通过 + +- 适用场景:UPDATE +- 条件:数据处于 pending 状态,且用户具备审批权限 +- 动作:系统将状态变更为 approved + +R-STATE-003:审批拒绝 + +- 适用场景:UPDATE +- 条件:数据处于 pending 状态,且用户具备审批权限 +- 动作:系统将状态变更为 rejected,并记录拒绝原因 + +--- + +## 10. 数据约束 + +### 10.1 唯一性约束 + +| 字段 | 唯一范围 | 说明 | +|---|---|---| +| <字段名> | 全局唯一 / 租户内唯一 / 用户内唯一 | <说明> | + +### 10.2 引用约束 + +| 当前对象字段 | 引用对象 | 引用字段 | 约束说明 | +|---|---|---|---| +| | | | 引用对象必须存在且未删除 | + +### 10.3 数据保留策略 + +- DATA-001:逻辑删除的数据默认不出现在普通查询结果中。 +- DATA-002:删除后的数据保留 天。 +- DATA-003:涉及审计的数据不得物理删除。 + +--- + +## 11. 影响范围 + +> 仅当需求类型为 UPDATE 时填写。 +> 当需求类型为 NEW 时,本节可写"无"。 + +| 项目 | 内容 | +|---|---| +| 影响的业务流程 | <说明影响哪些流程> | +| 是否影响已有用户行为 | 是 / 否;<说明影响> | +| 是否需要兼容历史数据 | 是 / 否;<说明兼容方式> | +| 是否影响权限规则 | 是 / 否;<说明影响> | +| 是否影响状态流转 | 是 / 否;<说明影响> | +| 是否影响已有数据 | 是 / 否;<说明影响> | + +--- + +## 12. 验收标准 + +### 12.1 功能验收 + +AC-001:正常创建 + +- 给定:用户具备创建权限 +- 当:用户输入合法字段并提交 +- 则:系统创建成功,并返回创建后的数据 + +AC-002:必填缺失 + +- 给定:用户具备创建权限 +- 当:用户提交时缺失必填字段 +- 则:系统拒绝创建,并返回字段级错误 + +AC-003:唯一性冲突 + +- 给定:系统中已存在相同唯一字段的数据 +- 当:用户再次提交相同唯一字段 +- 则:系统拒绝创建,并提示数据已存在 + +AC-004:无权限访问 + +- 给定:用户不具备对应权限 +- 当:用户查询、修改或删除数据 +- 则:系统拒绝操作,并返回统一错误结果 + +AC-005:引用数据删除 + +- 给定:数据已被其他业务引用 +- 当:用户删除该数据 +- 则:系统拒绝删除,并提示数据已被使用 + +### 12.2 数据验收 + +AC-DATA-001:创建成功后,数据库中必须存在对应业务记录。 + +AC-DATA-002:修改成功后,业务字段和审计字段必须同步更新。 + +AC-DATA-003:逻辑删除后,普通查询不得返回该数据。 + +AC-DATA-004:分页查询必须返回总数、当前页、页大小和结果列表。 + +### 12.3 权限验收 + +AC-PERM-001:具备权限的用户可以执行对应操作。 + +AC-PERM-002:不具备权限的用户不能执行对应操作。 + +AC-PERM-003:越权访问必须被拒绝,并返回统一错误结果。 + +--- + +## 13. 测试场景建议 + +| 场景编号 | 场景名称 | 前置条件 | 操作 | 预期结果 | +|---|---|---|---|---| +| TC-001 | 正常创建 | 用户已登录且有权限 | 输入合法数据并提交 | 创建成功 | +| TC-002 | 必填缺失 | 用户已登录且有权限 | 缺失必填字段并提交 | 创建失败,返回校验错误 | +| TC-003 | 唯一性冲突 | 已存在相同唯一字段数据 | 再次创建 | 创建失败 | +| TC-004 | 无权限访问 | 用户无对应权限 | 查询 / 修改 / 删除 | 操作被拒绝 | +| TC-005 | 状态流转 | 数据处于 draft 状态 | 提交审批 | 状态变为 pending | +| TC-006 | 逻辑删除 | 数据存在且未被引用 | 执行删除 | 数据被逻辑删除,普通查询不返回 | + +--- + +## 14. 原型引用说明 + +本需求关联的前端原型为: + +- HTML 原型路径:`` +- 或原型链接:`` + +说明: + +- 前端样式、布局、动效和交互细节,以原型 HTML 为准。 +- 本需求规格只描述业务背景、目标、字段、规则、权限、状态、数据约束和验收标准。 +- 若原型与本文档存在冲突,以本文档中的业务规则和验收标准为准。 + +--- + +## 15. 合并说明 + +> 仅当需求类型为 UPDATE 时填写。 +> 当需求类型为 NEW 时,本节可写"无"。 + +要求: + +1. 基于基线版本进行修改。 +2. 仅应用本文档中明确声明的变更。 +3. 未提及部分保持不变。 +4. 字段变更必须按 ADD / MODIFY / REMOVE 执行。 +5. 规则变更必须按 ADD / MODIFY / REMOVE 执行。 +6. 合并后应输出完整最新版本规格。 +7. 若字段表、规则、权限或状态流转存在冲突,应停止实现,并在计划文档中记录冲突点。 + +--- + +## 16. AI 实现提示 + +AI 在基于本文档生成技术方案或代码时,应遵守以下原则: + +1. 先读取本需求规格,再读取相关系统事实文档和技术规范文档。 +2. 不要根据前端样式推断业务规则;业务规则以本文档为准。 +3. 不要在实现中新增本文档未定义的业务行为。 +4. 每条业务规则都应能映射到至少一个测试用例。 +5. NEW 需求应按完整字段表和完整业务规则实现。 +6. UPDATE 需求应先读取基线版本,再按 ADD / MODIFY / REMOVE 合并变更。 +7. 存量修改必须限制在影响范围内,避免重构无关模块。 diff --git a/harness-installer/templates/docs/plans/_template.md b/harness-installer/templates/docs/plans/_template.md new file mode 100644 index 0000000..a7e8ba0 --- /dev/null +++ b/harness-installer/templates/docs/plans/_template.md @@ -0,0 +1,438 @@ +# {方案标题} + +>日期: YYYY-MM-DD +> +>关联需求:docs/features/{file}.md +> +>设计 design:docs/design/topics/{资源}-{操作}.md(实施后会写到原design文件) +> +> +> +>**plan一旦定稿就不修改。** 同一资源的二次改造新建 `YYYY-MM-DD-{slug}.md`,不修改原计划文件 + + + +> TODO:生成计划文档内容较长,执行计划时可以配合步骤进度文件实时落地执行进度 + +## 1. 文档说明 + +### 1.1 背景 + +- 业务 / 技术动机 +- 关联的 features 或 issue +- 关联的 design +- 关键决策点(讨论后定义的方向、放弃的备选方案等) + +### 1.2 目标 + +- 实现目标: +- 技术边界: + +------ + +## 2. 领域模型(PlantUML) + +```plantuml +@startuml +' 在此定义实体、属性、关系 + +entity User { + +id: string + +name: string +} + +entity Order { + +id: string + +userId: string +} + +User ||--o{ Order : places +@enduml +``` + +--- + +## 3. 数据库设计(SQL DDL) + +```sql +-- 在此定义表结构(必须可执行) + +CREATE TABLE user ( + id VARCHAR(64) PRIMARY KEY, + name VARCHAR(255) NOT NULL +); + +CREATE TABLE `order` ( + id VARCHAR(64) PRIMARY KEY, + user_id VARCHAR(64) NOT NULL +); +``` + +--- + +## 4. API 设计(OpenAPI) + +```yaml +openapi: 3.0.0 +info: + title: XXX API + version: 1.0.0 + +paths: + /example: + post: + summary: 示例接口 + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + field: + type: string + responses: + '200': + description: 成功响应 +``` + +--- + +## 5. 时序图(PlantUML) + +```plantuml +@startuml +actor Client +participant API +participant Service +participant DB + +Client -> API : 请求 +API -> Service : 处理 +Service -> DB : 操作 +DB --> Service : 返回 +Service --> API : 返回 +API --> Client : 响应 +@enduml +``` + +--- + +## 6. 专题设计(Markdown) + +### 6.1 权限设计 + +* (鉴权方式,如 JWT / Session) +* (权限模型,如 RBAC / ABAC) + +### 6.2 并发控制 + +* (乐观锁 / 悲观锁) +* (幂等设计) + +### 6.3 事务设计 + +* (单体事务 / 分布式事务) +* (一致性策略) + +### 6.4 异常处理 + +* (错误码规范) +* (统一返回结构) + +### 6.5 性能设计 + +* (缓存策略) +* (索引设计原则) + +### 6.6 扩展性设计 + +* (服务拆分) +* (事件驱动 / 消息队列) + +--- + +## 7. 一致性约束(必须遵守) + +* 领域模型 ↔ 数据库字段必须一致 +* 数据库 ↔ API 字段必须一致 +* 枚举值必须统一定义 +* 命名规范统一(如:API camelCase,DB snake_case) + +------ + +## 8. 单元测试设计 + +### 8.1 测试范围 + +* 被测单元粒度:(单个类 / 单个方法) +* 依赖处理:(Mock / Stub / Fake / Spy 的使用边界) +* 测试隔离:(独立、无副作用、可并行) + +### 8.2 测试策略 + +* 用例组织:(AAA 模式 Arrange-Act-Assert / Given-When-Then) +* 设计原则:(FIRST:Fast / Independent / Repeatable / Self-Validating / Timely) +* 测试框架:(JUnit 5 / Mockito / AssertJ) + +### 8.3 用例覆盖场景 + +每个被测单元的用例需覆盖以下场景: + +- [ ] 正常场景:合法输入,验证正确输出 +- [ ] 边界场景:最大/最小值、临界值 +- [ ] 异常场景:非法输入、越界、抛出预期异常 +- [ ] 特殊值:null、0、空字符串、空集合 +- [ ] 分支覆盖:每个 if/else、switch 分支 +- [ ] 状态机:状态流转与非法跳转 +- [ ] 并发幂等:竞态、重复调用 +- [ ] 一致性约束:领域模型↔数据库字段、枚举值校验(关联第 7 节) + +### 8.4 测试质量 + +* 命名规范:(should_xxx_when_yyy / given_when_then) +* 断言规范:(单一断言焦点 / 精准断言 / AssertJ) +* 数据构造:(TestDataBuilder / Object Mother) +* 覆盖率目标:(行覆盖 / 分支覆盖 阈值,如 ≥ 80%) +* 覆盖率排除:(DTO / 配置类 / generated code) + +### 8.5 用例清单 + +| 被测单元 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :------: | :------: | :------: | :------: | :------: | +| | | | | | + +------ + +## 9. API 集成测试设计 + +### 9.1 测试范围 + +* 切片类型:(Controller 切片 / Repository 切片 / 全链路集成) +* 真实加载组件:(Controller / Service / Repository / ...) +* Mock 边界:(外部服务 / 第三方接口 / 消息队列 / 下游 RPC) + +### 9.2 测试环境 + +* 数据库:(H2 内存库 / Testcontainers MySQL) +* 中间件:(Redis / MQ 依赖方案) +* 下游服务:(WireMock / MockServer) +* 迁移脚本:是否执行真实 Flyway 脚本(是 / 否) + +### 9.3 用例覆盖场景 + +- [ ] 契约校验:状态码、请求/响应字段、错误返回结构 +- [ ] 鉴权场景:无 token / 失效 token / 越权角色 +- [ ] 业务闭环:完整业务流程串联 +- [ ] 数据一致性:写入后查询验证、跨表对齐 +- [ ] 并发幂等:重复请求、并发写入 +- [ ] 下游异常:超时 / 失败 / 降级 + +### 9.4 测试数据 + +* 数据准备:(@Sql / @BeforeEach / TestDataBuilder) +* 隔离策略:(事务回滚 / 清表) +* 断言规范:(JSONPath / AssertJ) + +### 9.5 用例清单 + +| 接口 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :--: | :------: | :------: | :------: | :------: | +| | | | | | + +--- + +## 10. E2E 测试设计 + +### 10.1 测试范围 + +* 核心业务闭环:(列出 P0 链路,如 下单→支付→发货) +* 覆盖边界:(端到端全链路,不 Mock 内部组件) +* 数量约束:(核心链路 N 条) + +### 10.2 测试环境 + +* 部署方式:(Docker Compose / Testcontainers 全套) +* 依赖服务:(DB / Redis / MQ / 下游) +* 测试账号 / 种子数据:(可重入 / 可自清理) +* 外部第三方:(沙箱 / Mock,注明) + +### 10.3 用例覆盖场景 + +- [ ] 核心业务 user journey:完整业务闭环 +- [ ] 状态流转:状态机端到端跳转 +- [ ] 数据落库验证:接口成功后查 DB 校验 +- [ ] 异步链路:消息发送→消费→副作用(显式等待) +- [ ] 跨服务联动:服务间调用、最终一致性 +- [ ] 前端交互(可选):浏览器驱动 E2E + +### 10.4 稳定性与诊断 + +* 等待策略:(显式等待 / 禁止硬等待) +* Flaky 处理:(重试策略 + 记录) +* 失败诊断产物:(截图 / 录屏 / HAR / 日志) + +### 10.5 执行策略 + +* 运行时机:(夜跑 / 发版前 / 手动触发) +* 并行化:(是 / 否) +* 环境治理:(专用 E2E 环境 / 数据重置) + +### 10.6 用例清单 + +| 链路名称 | 覆盖步骤 | 验证点 | 关联章节 | +| :------: | :------: | :----: | :------: | +| | | | | + +------ + +## 11. 修改清单 + +### 11.1 代码修改 + +#### 11.1.1 修改{模块/资源} + +**修改** `src/main/java/.../File.java` + +- 改动点1 +- 改动点2 +- ... + +源代码(原功能概述): + +``` +涉及修改的源代码内容 +``` + +变动后的代码(新功能概述) + +``` +新代码内容 +``` + + + +#### 11.1.2 新增{模块/资源} + +- 用途与职责 +- 关键方法签名 + + + +#### 11.1.3 删除{模块/资源} + +- 用途与职责 +- 删除原因 +- 删除影响 + +#### ... + + + +#### 11.1.x 关键文件速查 + +| 操作 | 文件 | 备注 | +| :--: | :----------------------------: | :--: | +| 新增 | `src/main/java/.../FIlEA.java` | | +| 新增 | `src/main/java/.../FIlEB.java` | | +| ... | `...` | | +| 修改 | `src/main/java/.../FIlEC.java` | | +| 修改 | `src/main/java/.../FIlED.java` | | +| ... | `...` | | +| 删除 | `src/main/java/.../FIlEE.java` | | +| 删除 | `src/main/java/.../FIlEF.java` | | +| ... | `...` | | + +### 11.2 接口变更 + +| 路径 | 方法 | 变更类型 | 说明 | | +| :---------: | :--: | :------: | :--: | :--: | +| `/api/xxx` | POST | 新增 | xxxx | | +| `/api/xxx1` | GET | 修改 | xxxx | | + + + +### 11.3 数据库变更 + +- FLyway 脚本:`V{N}__{desc}.sql` + +- + +- 影响表: + + - `table_b`(新建) + + - 原因:xxxx + + - 影响:xxxx + + - sql脚本: + + ```sql + 对应sql脚本 + ``` + + - `tabel_a`(加字段 `xxx`) + + - 原因:xxxx + + - 影响:xxxx + + - sql脚本: + + ```sql + 对应sql脚本 + ``` + + - `table_b`(删字段 `xxx`) + + - 原因:xxxx + + - 影响:xxxx + + - sql脚本: + + ```sql + 对应sql脚本 + ``` + + + +- 数据迁移: + + - 迁移原因:xxxx + - 迁移方案:对应``V{N}__{desc}.sql` + - 注意事项:xxx + - 回滚方案:xxx + +------ + +## 12. 验证步骤 + +1. 本地启动后调 `curl ...` 期望返回 ... + +2. 检查数据库 `select ... from ... where ...` + +3. 看日志 grep `xxx` + + ------ + +## 13. 风险与回滚 + +- 风险点:xxxx + +- 回滚方案:Flyway 脚本 `V{N+1}__rollback_xxx.sql`,或代码会退到上一个commit + + ------ + +## 14. 实施后需更新的 design 文档 + +- `docs/design/topics/{主题}.md`(新建/更新) + + ------ + +## 15. 变更记录(可选) + +| 版本 | 日期 | 变更内容 | +| ---- | ---------- | -------- | +| v1.0 | YYYY-MM-DD | 初始版本 | diff --git a/harness-installer/templates/docs/standards/README.md b/harness-installer/templates/docs/standards/README.md new file mode 100644 index 0000000..dd366d9 --- /dev/null +++ b/harness-installer/templates/docs/standards/README.md @@ -0,0 +1,24 @@ +# 代码规范(事实) + +本目录是 **代码层面的硬约束**,写明"必须怎么做"。改动规范时要同步改本目录,并通知全队。 + +## 规范清单 + +| 文件 | 规范内容 | +|---|---| +| `architecture.md` | 整体架构、模块边界、依赖方向 | +| `layers.md` | 分层职责:每层允许做什么、禁止做什么 | +| `naming.md` | 命名约定:包、类、方法、字段、REST 路径 | +| `api-design.md` | API 设计:路径、版本、请求响应、分页、状态码 | +| `db.md` | 数据库规范:建表、命名、索引、迁移脚本 | +| `error.md` | 错误处理:错误码、异常类型、统一响应体 | +| `security.md` | 安全规范:认证、密码、敏感信息、上传 | +| `test.md` | 测试规范:分层、命名、覆盖要求、数据准备 | +| `business-rule.md` | 业务规则规范:规则 ID、定义位置、配置方式 | +| `data-dictionary.md` | 数据字典规范:枚举定义、注册方式、取值含义 | +| `templates/` | 代码模版 / snippet,供新功能开发时复制 | + +## 使用方式 + +- 写新代码前先读对应规范文件。 +- 实现与规范冲突时:要么改代码,要么改规范并说明理由,不允许默默违反。 diff --git a/harness-installer/templates/docs/standards/templates/README.md b/harness-installer/templates/docs/standards/templates/README.md new file mode 100644 index 0000000..cf421a9 --- /dev/null +++ b/harness-installer/templates/docs/standards/templates/README.md @@ -0,0 +1,20 @@ +# 代码模版(Snippet) + +存放常见业务代码模版,供新功能开发时 **参考复制**。所有模版都应来自项目真实实现代码。 + +## 目录 + +| # | 文件 | 层 | 用途 | +|---|------|-----|------| +| 1 | `01-ddd-controller.md` | Adapter | REST Controller 模版 | +| 2 | `02-ddd-appservice.md` | Application | AppService 用例编排模版 | +| 3 | `03-ddd-assembler.md` | Application | Domain → DTO 转换器模版 | +| 4 | `04-ddd-aggregate.md` | Domain | 聚合根模版(含业务守卫方法) | +| 5 | `05-ddd-domain-service.md` | Domain | Domain Service 模版 | +| 6 | `06-ddd-repository-interface.md` | Domain | Repository 接口模版 | +| 7 | `07-ddd-repository-impl.md` | Infrastructure | Repository 实现模版 | +| 8 | `08-ddd-converter.md` | Infrastructure | PO ⟷ Domain 转换器模版 | +| 9 | `09-ddd-po-mapper.md` | Infrastructure | PO 与 Mapper 模版 | +| 10 | `10-global-exception-handler.md` | Infrastructure | 全局异常处理模版 | + +> 模版里的包名请统一替换成实际项目的包名后再复制使用。 diff --git a/harness-installer/templates/docs/test-cases/README.md b/harness-installer/templates/docs/test-cases/README.md new file mode 100644 index 0000000..6f40a00 --- /dev/null +++ b/harness-installer/templates/docs/test-cases/README.md @@ -0,0 +1,13 @@ +# 测试用例(`docs/test-cases/`) + +本目录集中存放 **文本用例基线**(与自动化目录 `e2e/tests/` 分离)。 + +| 子目录 | 归属 | 内容 | +|---|---|---| +| `e2e-cases/` | **QA 测试** | E2E 验收用例文本基线(`TC-xxx`),合并闸门 | +| `manual-cases/` | **QA 测试** | 需人工执行的用例(`TC-Mxx`) | +| `smoking-cases/` | **QA 测试** | 发版前冒烟用例(`TC-Sxx`,≤ 5 分钟) | +| `dev-self-cases/` | **开发自测** | 开发自测场景清单(可选文本索引;实现仍在源码旁 / `e2e/tests/dev/`) | + +> QA 三目录:定义权与判定权归 QA。 +> `dev-self-cases/`:对开发本人负责,**不是**合并闸门。 diff --git a/harness-installer/templates/docs/test-cases/dev-self-cases/README.md b/harness-installer/templates/docs/test-cases/dev-self-cases/README.md new file mode 100644 index 0000000..d6830c4 --- /dev/null +++ b/harness-installer/templates/docs/test-cases/dev-self-cases/README.md @@ -0,0 +1,13 @@ +# 开发自测用例索引(可选) + +> **归属:开发自测。** 本目录用于记录本迭开发自测场景清单(可选文本索引)。 +> +> - 真正的可执行用例放在源码旁(`*Test.java`、`*.test.ts`)与 `e2e/tests/dev/` +> - **不写 `TC-` 编号**(`TC-` 是 QA 用例编号空间) +> - 自测全绿 ≠ 需求已验收 + +## 本迭索引(示例) + +| 场景 | 位置 | 备注 | +|---|---|---| +| (按 Plan 补) | `backend/src/test/...` | Happy Path + 失败分支 | diff --git a/harness-installer/templates/docs/test-cases/e2e-cases/test-cases.md b/harness-installer/templates/docs/test-cases/e2e-cases/test-cases.md new file mode 100644 index 0000000..68c9f36 --- /dev/null +++ b/harness-installer/templates/docs/test-cases/e2e-cases/test-cases.md @@ -0,0 +1,50 @@ +# E2E 测试用例 + +> **归属:QA 测试。** 本文件是 QA 验收用例的 **文本基线**,由 QA 定义与判定。 +> +> - 自动化实现位于 `e2e/tests/qa/`,编号与本文件一一对应 +> - 自动化代码可由开发代写,但用例的 **定义权与判定权归 QA** +> - 需求规格的每条验收标准(`docs/features/*/§12`)与每条业务规则(`R-xxx`)都必须有对应用例 +> - **合并闸门**:本文件的用例未全部通过验收,不能合并 + +> **不属于本文件的**:开发自测用例放在源码旁与 `e2e/tests/dev/`,只对开发本人负责,不是验收依据。 + +## 1. 公共页面 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-001 | 首页加载 | 访问 `/` | 页面渲染成功,主要元素可见 | + +## 2. 认证 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-002 | 登录成功 | 输入正确账号密码 → 提交 | 跳转到首页并显示用户信息 | +| TC-003 | 密码错误 | 输入错误密码 → 提交 | 显示错误提示,不跳转 | + +## 3. 业务流程 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-004 | {{核心流程}} | {{步骤}} | {{预期}} | + +## 4. 边界情况 + +| # | 用例 | 步骤 | 预期 | +|---|---|---|---| +| TC-005 | 未登录访问受保护页 | 清除登录态 → 访问受保护路由 | 跳转登录页 | + +## 测试数据 + +| 角色 | 账号 | 密码 | 说明 | +|---|---|---|---| +| 管理员 | TODO | TODO | | +| 普通用户 | TODO | TODO | | + +## 用例 ↔ 自动化对照 + +| 文本用例 | 自动化用例(`e2e/tests/qa/`) | 状态 | +|---|---|---| +| TC-001 ~ TC-005 | 同名 `test('TC-xxx ...')` | TODO | + +新增文本用例时,同步在自动化里加同名 `TC-xxx` 用例,并把状态改为"待实现"。 diff --git a/harness-installer/templates/docs/test-cases/manual-cases/manual-test-cases.md b/harness-installer/templates/docs/test-cases/manual-cases/manual-test-cases.md new file mode 100644 index 0000000..93dda8e --- /dev/null +++ b/harness-installer/templates/docs/test-cases/manual-cases/manual-test-cases.md @@ -0,0 +1,10 @@ +# 手动执行用例 + +> **归属:QA 测试。** 自动化难以覆盖、或需要人工主观判断的场景写在这里。 +> 由 QA 定义与判定,是 **合并闸门** 的一部分。 + +## 用例清单 + +| # | 用例 | 前置条件 | 步骤 | 预期 | 执行人 | +|---|---|---|---|---|---| +| TC-M01 | TODO | | | | | diff --git a/harness-installer/templates/docs/test-cases/smoking-cases/smoking-test-cases.md b/harness-installer/templates/docs/test-cases/smoking-cases/smoking-test-cases.md new file mode 100644 index 0000000..5542375 --- /dev/null +++ b/harness-installer/templates/docs/test-cases/smoking-cases/smoking-test-cases.md @@ -0,0 +1,13 @@ +# 冒烟用例 + +> **归属:QA 测试。** 发版前必须全绿的一组最小用例集。 +> 目标:**5 分钟内跑完**,用于快速判断"能不能发"。 + +## 用例清单 + +| # | 用例 | 冒烟点 | 预期 | 自动化 | +|---|---|---|---|---| +| TC-S01 | 服务启动 | 后端可启动、前端可加载 | 无启动错误 | | +| TC-S02 | 登录 | 正确凭据可登录 | 跳转成功 | | +| TC-S03 | 核心链路 | TODO | TODO | | +| TC-S04 | 数据库连通 | 可读写 | 无连接错误 | | diff --git a/harness-installer/templates/opencode.jsonc b/harness-installer/templates/opencode.jsonc new file mode 100644 index 0000000..69e15c9 --- /dev/null +++ b/harness-installer/templates/opencode.jsonc @@ -0,0 +1,7 @@ +{ + "$schema": "https://opencode.ai/config.json", + + "skills": { + "paths": [".agent/skills"] + } +} diff --git a/opencode.jsonc b/opencode.jsonc new file mode 100644 index 0000000..b7155ea --- /dev/null +++ b/opencode.jsonc @@ -0,0 +1,13 @@ +{ + "$schema": "https://opencode.ai/config.json", + + "skills": { + "paths": [ + "agile-team-sdd", + "harness-installer", + "tool-chain-installer", + "overnight-runner", + "example-project/.agent/skills" + ] + } +} diff --git a/overnight-runner/README.md b/overnight-runner/README.md new file mode 100644 index 0000000..398078b --- /dev/null +++ b/overnight-runner/README.md @@ -0,0 +1,354 @@ +# overnight-runner + +把一串 **plan** 交给 coding agent 无人值守地跑。左边是任务队列,右边是 agent 的实时输出。 + +``` +┌── 任务队列 ─────────────┬── Coding Agent ──────────────────────────┐ +│ ▶ 20261103-feature-a 运行中│ $ opencode run "…" │ +│ 20261103-bugfix 成功 │ DECISION: 是否执行数据库迁移? → 先写回滚 │ +│ 20261103-docs 待跑 │ … │ +│ │ │ +│ 待跑 1 · 运行 1 · 成功 1 │ 最近决策 │ +│ │ 是否执行数据库迁移 → 先写回滚脚本 │ +└─────────────────────────┴────────────────────────────────────────────┘ +``` + +## 为什么 + +一次要跑好几个 plan,人守着点 `opencode run` 没人愿意干。这个工具把它变成 **配置 + 启动**: + +| 原来 | 现在 | +|---|---| +| 守着终端一个个跑 | 队列里排好,启动就走 | +| 任务状态靠人记 | 左边面板实时看 | +| agent 卡死了没人知道 | 看门狗自动判定并重试 | +| 半夜替我做的决定没人知道 | 每条决策都记录,可回溯 | +| 换台机器跑不起来 | 装一次,配置进仓库 | +| 几个人抢同一个队列 | 一人一条队列,状态互不串 | +| 白天 agent 卡在提问上没人管 | 弹决策窗口问你,超时自动兜底 | + +## 安装 + +```bash +# 装到当前项目 +./scripts/install.sh . +``` + +**零依赖**:只用 Python 3.9+ 标准库,不需要 `pip install`。 + +装完项目里会有: + +``` +<项目>/ +├── overnight-runner.yaml # 运行配置(提交进仓库,全队列共享) +├── .overnight-runner/ +│ ├── project.yaml # 项目配置:默认提示词 + 默认决策(提交) +│ └── queue/ +│ └── default/ # 一条队列一个目录 +│ ├── queue.yaml # 队列定义:跑哪些 plan(提交) +│ ├── state.json # 运行时状态(不提交) +│ ├── decisions.jsonl # 决策记录(提交,便于回溯) +│ ├── logs/ # 每个任务的 agent 日志(不提交) +│ └── .lock # 单实例锁(不提交) +└── tools/overnight-runner/ + ├── overnight-runner # 启动脚本(POSIX) + ├── overnight-runner.cmd # 启动脚本(Windows) + └── overnight_runner/ # 实现 +``` + +**多队列**:`.overnight-runner/queue/<队列名>/` —— 同一个仓库里可以有多条队列, +多人各跑各的互不干扰(`--queue <名字>` 切换)。 + +**老项目自动迁移**:老布局(队列写在项目根 `overnight-runner.yaml`、 +状态在 `.overnight-runner/state.json`)第一次运行时 **自动搬到** +`.overnight-runner/queue/default/`,不丢任务、不丢状态,且迁移幂等(只发生一次)。 + +**依赖**:**没有**。 + +| 原本要什么 | 现在怎么做 | +|---|---| +| `rich` 画分屏 | `term.py` 自绘 ANSI(备用屏幕、光标定位、边框、语义色) | +| `PyYAML` 读配置 | `yaml_lite.py` 自实现 YAML 子集(缩进映射/序列、块标量、流式集合、注释) | + +按键读取 POSIX 用 `termios`、Windows 用 `msvcrt`,进程终止 POSIX 用 `killpg`、 +Windows 用 `CREATE_NEW_PROCESS_GROUP` —— 全是标准库。 +**Windows / macOS / Linux 都支持**,而且不用装任何东西。 + +## 用法 + +```bash +OR=tools/overnight-runner/overnight-runner + +$OR init # 初始化配置 +$OR add docs/plans/20261103-feature-a.md # 追加 plan(相对项目根) +$OR add docs/plans/xxx.md --role QA --priority 20 +$OR list # 看队列 +$OR status # 看状态 +$OR queues # 看所有队列 +$OR run # 启动分屏面板 +$OR run --headless # 无界面(CI / 脚本) +$OR run --headless --retry-failed # 把上次失败的重新排一遍 +$OR run --mode unattended # 临时切成无人值守(默认按配置) +$OR decisions # 看决策记录 +$OR decisions --json # 决策记录(JSON) +``` + +### 多队列(多人各跑各的) + +所有子命令都支持全局参数 `--queue <名字>`(默认 `default`): + +```bash +$OR --queue alice add docs/plans/alice-feature.md # 排到 alice 队列 +$OR --queue bob add docs/plans/bob-feature.md # 排到 bob 队列 +$OR queues # 一屏看清有几条队列、各自什么状态 +$OR --queue alice run # 跑 alice 队列 +``` + +每条队列的状态、日志、决策记录完全隔离(各自的目录),但 **默认决策规则是项目级共享** 的 +(都在 `.overnight-runner/project.yaml`)—— 规则是"这个项目怎么做决定", +决策 **记录** 才是"这条队列发生过什么"。 + +同一条队列 **不能同时跑两个 runner**(会白烧 agent),第二个会被挡住并退出(退出码 2)。 + +### 决策模式:白天有人值守 / 夜里无人值守 + +| | `attended`(白天有人值守) | `unattended`(夜里无人值守) | +|---|---|---| +| agent 提问时 | **打断 agent**,TUI 弹决策窗口 | 不打断,agent 继续跑 | +| 谁来决策 | 人(600 秒内)→ 超时自动兜底 | 规则 → `onUnknownDecision` 兜底 | +| 决策记录 source | `human` / `timeout` | `rule` / `fallback` | +| 决策能否被 agent 看到 | 能(续跑时直接带上) | 能(下次拉起时注入 prompt) | + +配置在 `overnight-runner.yaml` 的 `runner.decision`: + +```yaml +runner: + decision: + mode: attended # attended(有人值守) | unattended(无人值守) + timeoutSec: 600 # attended 模式下决策窗口等多久(秒);0 = 不限 + resume: session # session(续跑同一会话) | restart(重跑任务) +``` + +命令行可以临时覆盖(不改配置文件): + +```bash +$OR run --mode attended # 白天:有人盯着,弹窗问人 +$OR run --mode unattended # 夜里:直接决策,不打扰 +``` + +**`--headless` 强制 `unattended`** —— 没人看面板,不该卡在等 600 秒上。 + +### 决策窗口 + +agent 抛出 `QUESTION:` 时,右栏弹出带倒计时的决策框: + +``` +◆ 待决策 + 任务: 20261106-fix-public-endpoints + + 扩范围改还是先修 Bug? + + 你的决策: + > 先修 Bug,不要扩大改动范围▏ + + 剩余 9:58 Enter 确认 · Esc 用默认决策 · Ctrl-C 退出 +``` + +| 键 | 作用 | +|---|---| +| `Enter` | 提交你的答案,agent 用 `--session` 续跑(上下文不丢) | +| `Esc` | 立刻放弃回答,按默认决策兜底 | +| `Ctrl-C` | 退出 runner | + +超时(`timeoutSec` 到点)还没人回答 → 自动按规则/兜底策略决策,agent 续跑,**不会卡住队列**。 + +### 面板操作 + +| 键 | 作用 | +|---|---| +| `↑` `↓` | 选择任务 | +| `a` | 追加 plan(就地输入路径,回车确认) | +| `r` | 重置选中任务为待跑 | +| `p` | 暂停 / 恢复 | +| `d` | 移除 | +| `Enter` | 看选中任务的完整日志 | +| `Esc` | 返回实时输出 | +| `c` | 清屏 | +| `q` | 退出 | + +决策窗口出现时(`attended` 模式),按键被决策框独占:`Enter` 提交 · `Esc` 用默认决策 · `Ctrl-C` 退出。 + +## 三层配置 + +| 层 | 文件 | 作用域 | 管什么 | +|---|---|---|---| +| runner 级 | `overnight-runner.yaml` | 项目 | agent、看门狗、UI、决策策略 | +| project 级 | `.overnight-runner/project.yaml` | 项目(全队列共享) | 默认提示词、默认决策规则 | +| queue 级 | `.overnight-runner/queue//queue.yaml` | 单条队列 | 跑哪些 plan | + +### 1. 运行配置 `overnight-runner.yaml` + +管 **怎么跑**。 + +```yaml +runner: + agent: + command: opencode # 或 claude / codex / 任意 CLI + args: ["run"] + env: {} + watchdog: + maxRetries: 2 # 失败后额外重试几次 + backoffSec: 60 # 重试前等多久 + idleTimeoutSec: 1800 # 多久没输出判定卡死 + totalTimeoutSec: 7200 # 单任务最长跑多久 + killGraceSec: 15 # 终止后等多久再强杀 + decision: + mode: attended # attended | unattended + timeoutSec: 600 # 决策窗口等多久 + resume: session # session | restart + outputFormat: json # json(能拿 sessionID)| text + sessionArgs: ["--session", "{session}"] + state: + dir: .overnight-runner + workdir: . + ui: + refreshHz: 8 + logTail: 400 +``` + +### 2. 队列定义 `.overnight-runner/queue//queue.yaml` + +管 **跑什么**。plan 用 **相对项目根** 的路径。 + +```yaml +queue: + - id: 20261103-feature-a + plan: docs/plans/20261103-feature-a.md + prompt: "按 plan 实现,完成后跑一遍自测" + role: DEV + priority: 10 + depends_on: [] +``` + +队列可以直接改 YAML,也可以用 `add` 追加(会写回 YAML,**保留其它任务不动**)。 + +### 3. 项目配置 `.overnight-runner/project.yaml` + +管 **怎么决策**。 + +```yaml +project: + name: my-project + agent: + command: opencode + args: ["run"] + +default: + prompt: | + 你在无人值守模式下工作,不要停下来等待人工确认。 + {{DECISIONS}} + {{PLAN}} + 每做出一个决策,输出一行:DECISION: <问题> → <决策> + 全部完成后输出一行:DONE: <总结> + onUnknownDecision: 跳过并记录到决策日志 + +decisions: + - id: db-migration + question: 是否执行数据库迁移脚本? + match: "数据库迁移|migration" + answer: 先写好回滚脚本,再执行迁移 + enabled: true +``` + +占位符:`{{PLAN}}` = plan 全文,`{{DECISIONS}}` = 决策清单。 + +`match` 是正则,`question` 是精确 / 包含匹配。`enabled: false` 可以临时停用某条规则。 + +## 决策记录 + +每次用到决策都追加一条到 `.overnight-runner/queue//decisions.jsonl`: + +```json +{"at": "2026-11-03T02:14:22+08:00", "task_id": "20261103-feature-a", + "question": "是否执行数据库迁移脚本?", "answer": "先写好回滚脚本,再执行迁移", + "source": "rule", "rule_id": "db-migration", "waited_sec": 0, "session_id": ""} +``` + +| source | 含义 | +|---|---| +| `rule` | 命中预设规则(无人值守,或有人值守但超时兜底) | +| `fallback` | 没命中任何规则,用了 `onUnknownDecision` 兜底 | +| `agent` | agent 自己按默认决策做完了,输出了 `DECISION:` | +| `human` | **人在决策窗口里回答的** | +| `timeout` | **决策窗口等超时,自动兜底的** | + +**回溯时先看这个文件**,就知道"昨晚它替我做了什么决定"。 + +## agent 契约 + +agent 通过 stdout 跟 runner 通信: + +| 输出 | 含义 | +|---|---| +| `DECISION: <问题> → <决策>` | 做了一个决策(会被记录) | +| `QUESTION: <问题>` | 抛出待决问题(`attended` 打断问人 / `unattended` 按规则回答) | +| `DONE: <总结>` | 任务完成 | +| `BLOCKED: <原因>` | 任务阻塞 | +| 其它行 | 普通日志,原样显示在右侧 | + +`outputFormat: json` 时,agent 输出按 **json 事件** 解析(每行一个事件), +runner 从事件里取 `sessionID` —— 这是"把决策送回给 agent"的前提。 +换不支持 json 输出的 agent 时把 `outputFormat` 改成 `text`(此时靠 `sessionPattern` 正则抓 session id)。 + +## 看门狗 + +| 情况 | 判定 | 动作 | +|---|---|---| +| agent 退出码 ≠ 0 | 失败 | 退避后重试,超过次数标记失败 | +| 空闲超过 `idleTimeoutSec` | 卡死 | 终止进程组,退避后重试 | +| 超过 `totalTimeoutSec` | 超时 | 终止进程组,退避后重试 | + +终止时先 `SIGTERM`(Windows 是 `CTRL_BREAK`),宽限期后 `SIGKILL`, +**整组进程一起杀**(POSIX 用 `killpg`,Windows 用进程组),不留孤儿进程。 + +重试时会把之前做过的决策一起带上,避免 agent 重复问同一个问题。 + +## 架构 + +``` +┌──────────────────────────────────────────────┐ +│ ui.py(自绘 ANSI 分屏) │ +│ 左:任务队列 右:agent 输出 + 决策窗口 │ +│ term.py:备用屏幕 / 光标 / 边框 / 语义色 │ +└───────────────┬──────────────────────────────┘ + │ +┌───────────────▼──────────────────────────────┐ +│ controller.py │ +│ 取任务 → 组 prompt → 跑 agent → 看门狗 │ +│ → agent 提问?→ 打断 → 等人决策 → session 续跑 │ +└──┬────────────┬───────────────┬──────────────┘ + │ │ │ + ▼ ▼ ▼ +queue.py prompts.py agent.py +(队列目录) (默认提示词) (子进程+json解析) + │ │ + ▼ ▼ + decisions.py watchdog 判定 + (规则+记录+回灌) + +config.py ──→ yaml_lite.py(零依赖 YAML 子集) +util.py ──→ QueueLock(单实例锁) +``` + +## 注意 + +- **只跑已经确认过的 plan。** runner 不做人工确认这一关 —— plan 质量是人的责任。 +- 队列定义与项目配置 **提交进仓库**;`state.json` 与 `logs/` 不要提交。 +- 同一条队列 **不能同时跑两个 runner**(`.lock` 挡住,第二个退出码 2)。 +- agent 命令要支持"非交互跑一次"的用法(`opencode run ""` 这种)。 +- 面板需要真终端;`--headless` 可以在管道 / CI 里用(headless 强制无人值守模式)。 + +## 相关 + +- [`../agile-team-sdd/`](../agile-team-sdd/) — 产出 plan 的 skill(`dev-plan`),runner 消费的就是 plan +- [`../team-workflow-guide/`](../team-workflow-guide/) — 流程与角色约定 diff --git a/overnight-runner/SKILL.md b/overnight-runner/SKILL.md new file mode 100644 index 0000000..5c6faa4 --- /dev/null +++ b/overnight-runner/SKILL.md @@ -0,0 +1,230 @@ +--- +name: overnight-runner +description: 启动 overnight-runner 分屏面板,把队列里的 plan 交给 coding agent 跑(左边任务队列,右边 agent 输出,支持多队列、看门狗重试、有人值守时的决策窗口与无人值守时的默认决策记录)。当用户说"跑一晚上"、"夜间跑这些 plan"、"启动 overnight runner"、"无人值守跑任务"、"跑一条新队列"、"多个队列分别跑"时使用。 +--- + +# overnight-runner + +把一串 **plan** 交给 coding agent 无人值守地跑:左边是任务队列,右边是 agent 的实时输出。 + +## 它解决什么 + +一次要跑好几个 plan,人守着点 `opencode run` 没人愿意干。 +这个工具把这件事变成 **配置 + 启动**: + +- 队列用 YAML 管,plan 用相对路径引用;**一条队列一个目录**,多人各跑各的 +- 跑起来是分屏面板:左边看队列状态,右边看 agent 在干什么 +- agent 卡死或失败,看门狗自动重试 +- 决策按预设规则自动做,**每一条都记下来**,事后可回溯 +- 白天有人值守时,agent 提问会弹 **带倒计时的决策窗口**;超时没人答就自动兜底 + +## 安装 + +```bash +# 装到当前项目 +./overnight-runner/scripts/install.sh . + +# 预览 +./overnight-runner/scripts/install.sh . --dry-run + +``` + +**零依赖**:只用 Python 3.9+ 标准库,不用 pip install。 + +装完项目里会有: + +``` +<项目>/ +├── overnight-runner.yaml # 运行配置(提交进仓库,全队列共享) +├── .overnight-runner/ +│ ├── project.yaml # 项目配置:默认提示词 + 默认决策(提交) +│ └── queue/ +│ └── default/ # 一条队列一个目录 +│ ├── queue.yaml # 队列定义:跑哪些 plan(提交) +│ ├── state.json # 运行时状态(不提交) +│ ├── decisions.jsonl # 决策记录(提交,便于回溯) +│ ├── logs/ # 每个任务的 agent 日志(不提交) +│ └── .lock # 单实例锁(不提交) +└── tools/overnight-runner/ + ├── overnight-runner # 启动脚本(POSIX) + ├── overnight-runner.cmd # 启动脚本(Windows) + └── overnight_runner/ # 实现 +``` + +**老项目自动迁移**:老布局(队列写在项目根 `overnight-runner.yaml`)第一次运行时会 +自动搬到 `.overnight-runner/queue/default/`,不丢任务、不丢状态,迁移幂等。 + +**依赖**:**没有**。只用 Python 3.9+ 标准库 —— 界面是自绘的 ANSI 转义序列, +配置解析是自己实现的 YAML 子集。Windows / macOS / Linux 都支持。 + +## 用法 + +```bash +OR=tools/overnight-runner/overnight-runner + +$OR init # 初始化配置 +$OR add docs/plans/20261103-feature-a.md # 追加 plan(相对项目根) +$OR add docs/plans/xxx.md --role QA --priority 20 +$OR list # 看队列 +$OR status # 看状态 +$OR queues # 看所有队列 +$OR run # 启动分屏面板 +$OR run --headless # 无界面(CI / 脚本) +$OR run --headless --retry-failed # 把上次失败的重新排一遍 +$OR run --mode unattended # 临时切成无人值守 +$OR decisions # 看决策记录 +``` + +### 多队列(多人各跑各的) + +所有子命令都支持全局参数 `--queue <名字>`(默认 `default`): + +```bash +$OR --queue alice add docs/plans/alice-feature.md +$OR --queue bob add docs/plans/bob-feature.md +$OR queues # 一屏看清有几条队列、各自什么状态 +$OR --queue alice run # 跑 alice 队列 +``` + +每条队列的状态、日志、决策记录完全隔离;**默认决策规则是项目级共享**的 +(都在 `.overnight-runner/project.yaml`)—— 规则是"项目怎么做决定",决策 **记录** 才是 +"这条队列发生过什么"。 + +同一条队列 **不能同时跑两个 runner**(`.lock` 挡住,第二个退出码 2)。 + +### 决策模式:白天有人值守 / 夜里无人值守 + +| | `attended`(有人值守) | `unattended`(无人值守) | +|---|---|---| +| agent 提问时 | **打断 agent**,TUI 弹决策窗口 | 不打断,agent 继续跑 | +| 谁来决策 | 人(600 秒内)→ 超时自动兜底 | 规则 → `onUnknownDecision` 兜底 | +| 决策记录 source | `human` / `timeout` | `rule` / `fallback` | + +配置在 `overnight-runner.yaml` 的 `runner.decision.mode`; +命令行 `run --mode attended|unattended` 可临时覆盖。**`--headless` 强制无人值守。** + +决策窗口出现时按键被决策框独占:`Enter` 提交答案(agent 用 `--session` 续跑,上下文不丢)· +`Esc` 立刻用默认决策 · `Ctrl-C` 退出。 + +### 面板操作 + +| 键 | 作用 | +|---|---| +| `↑` `↓` | 选择任务 | +| `a` | 追加 plan(就地输入路径) | +| `r` | 重置选中任务为待跑 | +| `p` | 暂停 / 恢复 | +| `d` | 移除 | +| `Enter` | 看选中任务的完整日志 | +| `Esc` | 返回实时输出 | +| `c` | 清屏 | +| `q` | 退出 | + +## 队列定义(`.overnight-runner/queue/<名字>/queue.yaml`) + +```yaml +queue: + - id: 20261103-feature-a + plan: docs/plans/20261103-feature-a.md # 相对项目根 + role: DEV + priority: 10 +``` + +**plan 用相对项目根的路径。** 队列定义在 YAML 里,可以直接改,也可以用 `add` 追加(会写回 YAML)。 + +## 运行配置(`overnight-runner.yaml`) + +```yaml +runner: + agent: + command: opencode # 或 claude / codex / 任意 CLI + args: ["run"] + watchdog: + maxRetries: 2 # 失败后额外重试几次 + backoffSec: 60 # 重试前等多久 + idleTimeoutSec: 1800 # 多久没输出判定卡死 + totalTimeoutSec: 7200 # 单任务最长跑多久 + decision: + mode: attended # attended(有人值守)| unattended(无人值守) + timeoutSec: 600 # 决策窗口等多久(秒) + resume: session # session(续跑)| restart(重跑任务) + outputFormat: json # json(能拿 sessionID)| text +``` + +## 项目配置(`.overnight-runner/project.yaml`) + +回答"无人值守时怎么决策": + +```yaml +default: + prompt: | + 你在无人值守模式下工作,不要停下来等待人工确认。 + {{DECISIONS}} + {{PLAN}} + 每做出一个决策,输出一行:DECISION: <问题> → <决策> + 全部完成后输出一行:DONE: <总结> + onUnknownDecision: 跳过并记录到决策日志 + +decisions: + - id: db-migration + question: 是否执行数据库迁移脚本? + match: "数据库迁移|migration" + answer: 先写好回滚脚本,再执行迁移 +``` + +`{{PLAN}}` = plan 全文,`{{DECISIONS}}` = 下面的决策清单。 + +## 决策记录 + +每次用到决策,都会追加一条到 `.overnight-runner/queue/<名字>/decisions.jsonl`: + +```json +{"at": "2026-11-03T02:14:22+08:00", "task_id": "20261103-feature-a", + "question": "是否执行数据库迁移脚本?", "answer": "先写好回滚脚本,再执行迁移", + "source": "rule", "rule_id": "db-migration", "waited_sec": 0, "session_id": ""} +``` + +`source` 五种: + +| source | 含义 | +|---|---| +| `rule` | 命中预设规则 | +| `fallback` | 没命中任何规则,用了兜底策略 | +| `agent` | agent 自己按默认决策做完了,并输出了 `DECISION:` | +| `human` | 人在决策窗口里回答的 | +| `timeout` | 决策窗口等超时,自动兜底的 | + +**回溯时先看这个文件**,就知道"昨晚它替我做了什么决定"。 + +## agent 契约 + +agent 通过 stdout 跟 runner 通信: + +| 输出 | 含义 | +|---|---| +| `DECISION: <问题> → <决策>` | 做了一个决策(会被记录) | +| `QUESTION: <问题>` | 抛出待决问题(runner 用规则回答并记录) | +| `DONE: <总结>` | 任务完成 | +| `BLOCKED: <原因>` | 任务阻塞 | +| 其他行 | 普通日志,原样显示在右侧 | + +## 看门狗 + +| 情况 | 判定 | 动作 | +|---|---|---| +| agent 退出码 ≠ 0 | 失败 | 退避后重试,超过次数标记失败 | +| 空闲超过 `idleTimeoutSec` | 卡死 | 终止进程组,退避后重试 | +| 超过 `totalTimeoutSec` | 超时 | 终止进程组,退避后重试 | + +终止时会先 `SIGTERM`(Windows 是 `CTRL_BREAK`),宽限期后 `SIGKILL`, +**整组进程一起杀**,不会留孤儿进程。 + +重试时会把之前做过的决策一起带上,避免 agent 重复问同一个问题。 + +## 注意 + +- **只跑已经确认过的 plan。** runner 不做人工确认这一关 —— plan 质量是人的责任。 +- 队列定义与项目配置 **提交进仓库**;`state.json` 与 `logs/` 不要提交。 +- 同一条队列 **不能同时跑两个 runner**(`.lock` 挡住,第二个退出码 2)。 +- agent 命令要支持"非交互跑一次"的用法(`opencode run ""` 这种)。 +- 面板需要真终端;`--headless` 可以在管道 / CI 里用(headless 强制无人值守模式)。 diff --git a/overnight-runner/config/overnight-runner.example.yaml b/overnight-runner/config/overnight-runner.example.yaml new file mode 100644 index 0000000..bc0e242 --- /dev/null +++ b/overnight-runner/config/overnight-runner.example.yaml @@ -0,0 +1,60 @@ +# overnight-runner 运行配置(项目级,全队列共享) +# +# 这里回答的是"这个项目怎么跑": +# agent 是谁 / 看门狗多严 / 界面怎么刷 / 决策怎么处理 +# +# "跑哪些任务"不在这里 —— 队列定义在 +# .overnight-runner/queue/<队列名>/queue.yaml +# 用 `overnight-runner --queue <名字> add docs/plans/xxx.md` 追加。 +# +# 运行时状态(谁跑过、重试几次)写在同目录的 state.json,不进版本库。 + +runner: + # coding agent 命令与参数。默认 opencode run;也可以用 claude / codex 等。 + agent: + command: opencode + args: ["run"] + env: {} + + # 看门狗:失败自动重试 + watchdog: + maxRetries: 2 # 失败后额外重试几次 + backoffSec: 60 # 重试前等多久 + idleTimeoutSec: 1800 # agent 多久没输出就判定卡死(秒) + totalTimeoutSec: 7200 # 单个任务最长跑多久(秒) + killGraceSec: 15 # 终止后等多久再强杀 + + # 决策策略:agent 抛 "QUESTION: <问题>" 时怎么办 + decision: + # attended —— 有人值守(白天):打断 agent,TUI 弹决策窗口问你; + # 你在 timeoutSec 内没回答,就按规则/兜底策略自动决策 + # unattended —— 无人值守(夜里):不打断 agent,直接按规则/兜底策略决策 + mode: attended + + timeoutSec: 600 # attended 模式下决策窗口等多久(秒);0 = 不限 + + # 打断 agent 拿到答案后怎么让它继续: + # session —— 用 `agent --session ` 续跑同一会话(上下文不丢) + # restart —— 重跑整个任务(决策历史会注入新一轮 prompt) + resume: session + + # json 模式下 agent 每行输出都是 json 事件 —— 能拿到 sessionID, + # 决策才能送回给 agent。换不支持 json 输出的 agent 时改成 text。 + outputFormat: json + jsonArgs: ["--format", "json"] + + # 续跑时追加的参数,{session} 会被替换成真实的 session id + sessionArgs: ["--session", "{session}"] + + # text 模式下从 agent 输出里正则抓 session id 的兜底 + sessionPattern: '"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"' + + state: + dir: .overnight-runner + + # agent 在哪个目录下跑(相对项目根) + workdir: . + + ui: + refreshHz: 8 + logTail: 400 diff --git a/overnight-runner/config/project.example.yaml b/overnight-runner/config/project.example.yaml new file mode 100644 index 0000000..dafd750 --- /dev/null +++ b/overnight-runner/config/project.example.yaml @@ -0,0 +1,69 @@ +# overnight-runner 项目配置 +# +# 这个文件回答两个问题: +# 1. agent 是什么 —— command / args / env +# 2. 无人值守时,**默认怎么决策** —— default.prompt + decisions +# +# 每次用到默认决策,都会写一条记录到 +# .overnight-runner/queue/<队列名>/decisions.jsonl +# 方便事后回溯"昨晚它替我做了什么决定"。 +# +# 这里的规则是 **全队列共享** 的 —— 决策记录才是 per-queue 的。 + +project: + name: my-project + agent: + command: opencode + args: ["run"] + env: {} + +default: + # 每次任务都会用的默认提示词。 + # 占位符: + # {{PLAN}} —— plan 文件的全文 + # {{DECISIONS}} —— 下面的默认决策清单 + prompt: | + 你在无人值守模式下工作,不要停下来等待人工确认。 + + 按下面的方案执行,遇到需要决策的问题,按"默认决策"处理: + + {{DECISIONS}} + + {{PLAN}} + + 执行要求: + 1. 每做出一个决策,输出一行:DECISION: <问题> → <决策> + 2. 全部完成后输出一行:DONE: <一句话总结> + 3. 如果无法继续,输出一行:BLOCKED: <原因> + + # 命中不了任何规则时的兜底策略。 + # 可选:跳过并记录到决策日志 / 采用最安全可回滚的方案 / 停止任务并标记为阻塞 + onUnknownDecision: 跳过并记录到决策日志 + +# 默认决策规则:agent 遇到这类问题时,直接用这里的答案,不要等人。 +# +# match 是正则(大小写不敏感时用 (?i) 前缀),question 是精确/包含匹配。 +decisions: + - id: db-migration + question: 是否执行数据库迁移脚本? + match: "数据库迁移|flyway|migration" + answer: 先写好回滚脚本,再执行迁移;迁移后跑一遍冒烟用例 + enabled: true + + - id: missing-plan + question: plan 里没有写清楚的部分 + match: "plan.*(缺失|没有写|不明确)" + answer: 按项目现有实现的模式推断,并在最终总结里明确标注这个假设 + enabled: true + + - id: flaky-test + question: 测试偶发失败 + match: "flaky|偶发|时好时坏" + answer: 不要靠重试掩盖,定位根因后修复;在总结里写明根因 + enabled: true + + - id: scope-creep + question: 是否扩大改动范围 + match: "范围外|额外的改动|顺便" + answer: 不扩大范围,把发现的问题记录下来,不要顺手改 + enabled: true diff --git a/overnight-runner/config/runner.example.json b/overnight-runner/config/runner.example.json new file mode 100644 index 0000000..aea22c2 --- /dev/null +++ b/overnight-runner/config/runner.example.json @@ -0,0 +1,37 @@ +{ + "runner": { + "host": "127.0.0.1", + "port": 7801, + "stateDir": ".overnight-runner", + "logRetentionDays": 14 + }, + "defaults": { + "restart": { + "maxRetries": 0, + "backoffSec": 30 + }, + "timeoutSec": 1800, + "env": {} + }, + "tasks": [ + { + "id": "nightly-e2e", + "name": "夜跑 E2E", + "description": "每天凌晨跑一遍全量 Playwright 用例", + "command": "bash e2e-run.sh", + "cwd": "../example-project", + "schedule": "0 2 * * *", + "timeoutSec": 3600, + "restart": { + "maxRetries": 2, + "backoffSec": 60 + }, + "env": { + "NODE_ENV": "test" + }, + "notify": { + "onFailure": true + } + } + ] +} diff --git a/overnight-runner/docs/design.md b/overnight-runner/docs/design.md new file mode 100644 index 0000000..29c0a28 --- /dev/null +++ b/overnight-runner/docs/design.md @@ -0,0 +1,330 @@ +# overnight-runner 设计 + +## 目标 + +把"一串 plan 交给 coding agent 无人值守地跑"变成一个 **可配置、可观测、可回溯** 的工具。 + +四条硬需求: + +1. 作为一个 skill 启动,任何人都能装进自己的项目 +2. 分屏:左边任务管理,右边 coding agent +3. 启动用 YAML 管队列,plan 用相对路径引用 +4. 支持追加 plan +5. 失败有看门狗重试 +6. 支持 win / mac +7. 项目配置:默认提示词 + 默认决策,决策要写记录 + +## 模块 + +``` +overnight_runner/ +├── cli.py 命令行入口(init/add/list/status/decisions/queues/run) +├── config.py 三层 YAML 配置的加载与序列化 + 队列路径解析 + 老布局迁移 +├── yaml_lite.py 零依赖 YAML 子集解析/序列化 +├── queue.py 任务模型、队列、状态持久化(按队列目录隔离) +├── prompts.py 提示词组装(默认提示词 + 决策清单 + plan 全文 + 续跑提示) +├── decisions.py 默认决策规则匹配 + 决策记录 +├── agent.py 子进程启动、流式输出、json 事件解析、session id 抓取 +├── controller.py 调度:取任务 → 跑 → 看门狗 → 决策打断 → 续跑 → 重试 → 落状态 +├── keys.py 跨平台按键读取(termios / msvcrt) +├── ui.py 分屏界面 + 决策窗口 +├── term.py ANSI 绘制原语(备用屏幕 / 光标 / 边框 / 宽度计算) +└── util.py 时间、原子写、JSONL 追加、队列单实例锁 +``` + +**零第三方依赖**:只用 Python 3.9+ 标准库。 + +## 配置分层 + +| 文件 | 管什么 | 作用域 | 提交进仓库 | +|---|---|---|---| +| `overnight-runner.yaml` | agent 命令 + 看门狗 + UI + 决策策略 | 项目 | ✅ | +| `.overnight-runner/project.yaml` | 默认提示词 + 默认决策规则 | 项目(全队列共享) | ✅ | +| `.overnight-runner/queue//queue.yaml` | 队列定义(跑哪些 plan) | 单条队列 | ✅ | +| `.overnight-runner/queue//state.json` | 运行时状态(谁跑过、重试几次) | 单条队列 | ❌ | +| `.overnight-runner/queue//decisions.jsonl` | 决策记录 | 单条队列 | ✅(便于回溯) | +| `.overnight-runner/queue//logs/*.log` | 每个任务的 agent 原始输出 | 单条队列 | ❌ | +| `.overnight-runner/queue//.lock` | 单实例锁(pid + 心跳) | 单条队列 | ❌ | + +**三层分离的理由**: + +- **runner 级**(怎么跑):agent 是谁、看门狗多严、决策怎么处理 —— 项目级策略, + 跟"跑哪些任务"无关。 +- **project 级**(怎么决策):默认决策规则是"这个项目永远怎么做决定", + 很少变,应该沉淀下来复用,**所有队列共享一份**。 +- **queue 级**(跑什么):队列经常变(按迭代切分支、按人分工), + 多人各跑各的互不干扰,所以 **一条队列一个目录**。 + +**为什么决策记录分队列、决策规则不分**:规则是项目级策略("i 不在的时候你该怎么做"), +记录是 per-queue 的事实("alice 这条队列昨晚发生过什么")。混在一起会互相污染。 + +## 多队列 + +``` +/ +├── overnight-runner.yaml +└── .overnight-runner/ + ├── project.yaml + └── queue/ + ├── default/{queue.yaml, state.json, logs/, decisions.jsonl, .lock} + └── alice/{queue.yaml, state.json, logs/, decisions.jsonl, .lock} +``` + +- 队列名白名单 `[A-Za-z0-9][A-Za-z0-9._-]*` —— **拒绝 `..`**,防路径穿越。 +- 所有子命令都支持全局 `--queue `(默认 `default`)。 +- `queues` 子命令一屏看清有几条队列、各自什么状态。 + +### 老布局迁移(幂等) + +老布局:队列写在项目根 `overnight-runner.yaml` 的 `queue:` 段, +状态在 `.overnight-runner/state.json`,日志在 `.overnight-runner/logs/`。 + +任何读队列的子命令都会触发迁移: + +| 源 | 目标 | +|---|---| +| `/overnight-runner.yaml` 的 `queue:` 段 | `.overnight-runner/queue/default/queue.yaml` | +| `/.overnight-runner/state.json` | `.overnight-runner/queue/default/state.json` | +| `/.overnight-runner/logs/` | `.overnight-runner/queue/default/logs/` | +| `/.overnight-runner/decisions.jsonl` | `.overnight-runner/queue/default/decisions.jsonl` | + +**用 move(rename)不是 copy** —— 源文件不会留下两份。迁移后把根配置里的 `queue:` 段清空, +保证"只发生一次"。源文件不存在就跳过,重复调用无副作用。 + +### 单实例锁 + +同一个队列目录同时跑两个 runner → 两边都认领同一个 pending 任务 → **同一个 plan 跑两遍** +(白烧 agent)。所以每条队列目录放一个 `.lock`(`{"pid", "started_at", "heartbeat"}`): + +- 锁不存在 → 创建 +- 锁存在且 pid **活着** → 报错退出(退出码 `2`),提示"队列 X 已被 pid N 占用" +- 锁存在但 pid 已死(stale)→ 视为残留,清理后重建 +- 正常退出 / Ctrl-C → 删除自己持有的锁 + +pid 存活探测用 `os.kill(pid, 0)`(POSIX)。Windows 上 `os.kill(pid, 0)` 会真的杀进程, +所以 Windows 走心跳判断(超过 `STALE_SEC` 视为 stale)。 + +## 状态机 + +任务状态: + +``` +pending ──▶ running ──┬──▶ success + ▲ │ ├──▶ retrying ──▶ running (退避后重试) + │ │ ├──▶ failed + │ │ └──▶ blocked + └──────────┴── (r 键重置) +``` + +`next_ready()` 选下一个任务的条件:`enabled` 且 `status == pending` 且所有 `depends_on` 已 `success`, +按 `priority` 升序,同优先级按 id。 + +## 决策机制 + +五种来源,都写进 `decisions.jsonl`: + +| source | 触发方式 | 记录内容 | +|---|---|---| +| `agent` | agent 输出 `DECISION: <问题> → <决策>` | agent 自己做的决定 | +| `rule` | agent 输出 `QUESTION:`,命中预设规则 | 问题 + 规则答案 + rule_id | +| `fallback` | agent 输出 `QUESTION:` 但没命中规则 | 问题 + `onUnknownDecision` 兜底 | +| `human` | **人在 TUI 决策窗口里回答的** | 问题 + 人的答案 + 等了多久 + session id | +| `timeout` | **决策窗口等超时,自动兜底的** | 问题 + 兜底答案 + 等了多久 + session id | + +### 两种决策模式 + +| | `attended`(白天有人值守) | `unattended`(夜里无人值守) | +|---|---|---| +| agent 提问时 | **打断 agent**,TUI 弹决策窗口 | 不打断,agent 继续跑 | +| 谁来决策 | 人(`timeoutSec` 内)→ 超时自动兜底 | 规则 → `onUnknownDecision` 兜底 | +| 记录 source | `human` / `timeout` | `rule` / `fallback` | + +**为什么按"有没有人盯着"分,而不是按"问题命不命中规则"分**: +规则表在 attended 模式里只当 **超时兜底** 用 —— 它的语义是"我不在的时候你该怎么做"。 +白天有人就问人,问不到再用规则兜底。 + +`--headless` **强制** `unattended` —— 没人看面板,卡在等 600 秒纯属浪费。 + +### 决策状态机 + +``` +agent 输出 QUESTION: <问题> + │ + ▼ + ┌──────────────────────────┐ + │ mode = ? │ + │ unattended → 否 │──► 自动决策(规则答案 or onUnknownDecision) + │ attended → 是 │ └─► 记录 source=rule / fallback + └──────────────────────────┘ └─► 继续跑(决策在下次拉起时注入 prompt) + │ 是 + ▼ + 终止 agent(TERM → 宽限 → KILL) + │ + ▼ + 置 PendingQuestion{deadline = now + timeoutSec} + │ + ▼ + ┌──────────── 等待(TUI 弹决策窗口,倒计时)─────────────┐ + │ 人按 Enter 提交答案 ──────────► source=human │ + │ 人按 Esc 立刻兜底 ────────────► source=timeout │ + │ 倒计时到点没人管 ─────────────► source=timeout │ + └───────────────────────────────────────────────────────┘ + │ 超时兜底时:规则命中 → 规则答案;未命中 → onUnknownDecision + ▼ + 记录到 decisions.jsonl + │ + ▼ + ┌──────────── 恢复 ────────────┐ + │ resume=session 且拿到 sid │──► agent --session "<答案>,请继续>" + │ 否则 / 续跑失败 │──► 重跑任务,prompt 里带决策历史 + └─────────────────────────────┘ +``` + +**三条出路保证不会卡死**:人答(`Enter`)、人放弃(`Esc`)、超时自动兜底。 +Ctrl-C 退出整个 runner。 + +### 打断 agent 续跑:session 通道 + +`opencode run` **没有**"运行中接收输入"的选项,只有 `--session` / `--continue` 两种续跑方式 +(已实测)。所以"人回答问题"的实现路径只能是: + +``` +终止 agent → 拿到答案 → opencode run --session "<答案>,请继续>" +``` + +前提是能拿到 `sessionID`: + +- `outputFormat: json` 时,每条 json 事件顶层都带 `sessionID` —— **这是主路径** +- `outputFormat: text` 时,用 `sessionPattern` 正则从原始行里兜底抓 + +拿不到 session id → 降级为 **重跑整个任务**,决策历史注入新一轮 prompt。 +续跑进程立刻非零退出 → 再降级一次(避免无限重试)。 + +### 决策历史注入 + +每次决策后 `decisions_made` **必须 append**,且每次拉起 agent 前都拼进 prompt +(不只是重试时): + +``` +已经做出的决策(不要重复询问): +- 扩范围改还是先修 Bug? → 先修 Bug,不要扩大改动范围 +``` + +这样即使 `unattended`(完全不打断),agent 也能在下一轮看到之前的决策 —— +修掉了"决策是假的"(答案从不回灌给 agent)这个既有缺陷。 + +## 看门狗 + +两个超时,都以 **agent 最后一次输出** 为基准: + +- `idleTimeoutSec`:空闲超时 —— agent 卡死 / 死锁 / 在等输入 +- `totalTimeoutSec`:总时长超时 —— agent 在做无用功 + +判定在 controller 的轮询循环里做(0.5s 一次),超时后: + +1. `SIGTERM`(Windows `CTRL_BREAK_EVENT`) +2. 等 `killGraceSec` +3. 还没死就 `SIGKILL` + +**进程组终止**:POSIX 用 `start_new_session=True` + `os.killpg`, +Windows 用 `CREATE_NEW_PROCESS_GROUP` + `CTRL_BREAK_EVENT`。 +只杀父进程会留下孙子进程(agent 通常会再起子进程)。 + +重试次数 `maxRetries`,退避 `backoffSec`。 + +## 跨平台 + +| 关注点 | macOS / Linux | Windows | +|---|---|---| +| 按键读取 | `termios` + `tty.setraw` | `msvcrt.getwch()` | +| 进程组 | `start_new_session` + `killpg` | `CREATE_NEW_PROCESS_GROUP` + `CTRL_BREAK` | +| 强杀 | `SIGKILL` | `proc.kill()` | +| 启动脚本 | `overnight-runner`(bash) | `overnight-runner.cmd` | +| 换行 | `\n` | `\r\n`(Python 文本模式自动处理) | + +全部用标准库实现,不需要 `pip install`: +按键(`termios` / `msvcrt`)、进程组(`os.killpg` / `CREATE_NEW_PROCESS_GROUP`)、 +界面(ANSI 转义序列)、YAML 解析(`yaml_lite.py`)。 + +## 界面 + +自己用 ANSI 转义序列画(`term.py`),不用 rich: + +| 能力 | 实现 | +|---|---| +| 全屏 | `ESC[?1049h` 进备用屏幕,退出时 `ESC[?1049l` 恢复 | +| 光标 | `ESC[{row};{col}H` 绝对定位 + `ESC[?25l` 隐藏 | +| 边框 | `┌┐└┘─│` 圆角字符,逐格定位 | +| 颜色 | SGR 序列,状态用固定语义色 | +| 宽度 | 按 `east_asian_width` 算,中文算 2 列;**忽略 ANSI 序列本身占位** | + +布局: + +``` +┌ 任务队列 (N) ────────┐┌ Coding Agent · ──────────────────────────┐ +│▶ 20261103-feature-a 运行中│ $ opencode run "…" │ +│ 20261103-bugfix 成功 │ DECISION: 是否执行数据库迁移? → 先写回滚脚本 │ +│ │ … │ +│ 待跑 1 · 运行 1 · 成功 1│ 最近决策 │ +└────────────────────────┘└─────────────────────────────────────────────────────┘ +↑↓ 选择 a 追加 plan r 重试 p 暂停/恢复 d 移除 Enter 查看日志 Esc 返回 q 退出 +``` + +**宽度计算必须忽略 ANSI 序列**:带颜色的文本如果按字符数算宽, +边框就会错位。所以 `dwidth()` / `truncate()` / `pad()` / `wrap()` 都走同一个 +`_tokens()`,把转义序列当宽度 0。 + +按键在独立线程读(`KeyReader`),避免阻塞渲染循环。 +追加 plan 用 **行内输入模式**(不是弹窗):按 `a` 进入输入态, +后续按键进缓冲区,`Enter` 确认,`Esc` 取消。 + +**决策窗口**(`attended` 模式,agent 提问时抢占右栏): + +``` +◆ 待决策 + 任务: 20261106-fix-public-endpoints + + 扩范围改还是先修 Bug? + + 你的决策: + > 先修 Bug,不要扩大改动范围▏ + + 剩余 9:58 Enter 确认 · Esc 用默认决策 · Ctrl-C 退出 +``` + +- **按键路由优先级**:决策窗口 > 追加 plan 输入 > 常规。决策窗口在阻塞 agent,等不起。 +- 右栏标题用 **正在跑** 的任务(`_running_task()`)而不是 **选中行** —— + 否则按 `↓` 切行后标题和内容对不上。 + +### 按键读取必须懂 UTF-8 + +`keys.py` 不能"一次 `os.read(fd, 1)` 再解码" —— 汉字是 3 字节、emoji 是 4 字节, +一次读一个字节会把一个字符拆成 3 次读,每次 `decode(errors="replace")` 都失败, +**中文全变问号**(实测:决策窗口输入"先修 Bug",落盘变成"??? Bug")。 + +做法(`PosixKeyReader`): + +| 步骤 | 说明 | +|---|---| +| 缓冲 | 字节先进缓冲区,不假设一次 read 就是一个键 | +| 凑齐 | 按 UTF-8 首字节判断字符长度(1/2/3/4),字节够了才解 | +| ESC 判定 | ESC 后等 50ms;是 `ESC [` 就按 CSI 规则在 **缓冲区里** 找结束字节,不是再读 2 字节 | + +Windows 走 `msvcrt.getwch()`,它本身就返回完整字符,不受这个问题影响。 + +## 已知取舍 + +| 取舍 | 原因 | +|---|---| +| agent 非交互调用(`opencode run ""`) | runner 无法接管交互式 TUI 的终端输入;提示词走命令行参数 | +| 提示词不进 `--prompt-file` | 不同 agent 参数格式不一致;用命令行参数兼容性最好。超长提示词在 Windows 上有长度限制,这是已知限制 | +| 自己实现 YAML 子集 | 为了零依赖。覆盖了本项目用到的全部语法,遇到不支持的语法(锚点/别名/标签)会明确报错而不是静默出错 | +| 自己实现 ANSI 绘制 | 为了零依赖。代价是没有 rich 的自动换行与布局引擎,长文本要自己算宽 | +| 决策记录用 JSONL | 追加写、原子、无需数据库、方便 `jq` 处理 | +| 状态单独放 `state.json` | 队列 YAML 要提交,状态不要;分开才能既版本化又不脏仓库 | +| 状态文件旁存 `state.json.bak` | 误删状态文件不该把已跑完的任务全部重新排队;读取时主文件缺失/损坏就回落 `.bak` | +| 一条队列一个目录 | 多人可以在同一个仓库里各跑各的,状态与日志互不串;代价是路径多一层 | +| 老布局自动迁移而不是报错 | 用户不该为了升级改配置;迁移用 move 且幂等,只发生一次 | +| 面板不解析 agent 的 ANSI | agent 的原始输出原样透传,保留它的配色;代价是右侧可能有转义序列残留 | +| 打断 agent 而不是挂起等待 | agent 没有"挂起等输入"的接口(`opencode run` 只有 `--session` 续跑);打断后用 session 续跑保住上下文 | +| 按键读取用字节缓冲而不是一次读一个键 | 一次读一个字节会把汉字拆成乱码;缓冲 + 按 UTF-8 首字节凑齐才能正确还原中文 | diff --git a/overnight-runner/overnight_runner/__init__.py b/overnight-runner/overnight_runner/__init__.py new file mode 100644 index 0000000..e1203da --- /dev/null +++ b/overnight-runner/overnight_runner/__init__.py @@ -0,0 +1,5 @@ +"""overnight-runner:把一串 plan 交给 coding agent 无人值守地跑一晚上。""" + +__version__ = "0.1.0" + +APP_NAME = "overnight-runner" diff --git a/overnight-runner/overnight_runner/__main__.py b/overnight-runner/overnight_runner/__main__.py new file mode 100644 index 0000000..bfdcd0c --- /dev/null +++ b/overnight-runner/overnight_runner/__main__.py @@ -0,0 +1,4 @@ +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/overnight-runner/overnight_runner/agent.py b/overnight-runner/overnight_runner/agent.py new file mode 100644 index 0000000..29edfbe --- /dev/null +++ b/overnight-runner/overnight_runner/agent.py @@ -0,0 +1,301 @@ +"""调用 coding agent 子进程,实时收集输出。""" + +from __future__ import annotations + +import json +import os +import re +import signal +import subprocess +import sys +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable + +from .util import is_windows + +LineCallback = Callable[[str], None] + + +def extract_session_id(line: str, pattern: str) -> str: + """用正则从 agent 输出里抓 session id(text 模式的兜底)。""" + if not pattern: + return "" + try: + m = re.search(pattern, line) + except re.error: + return "" + return m.group(1) if m else "" + + +def _render_tool(part: dict) -> list[str]: + """把一次工具调用渲染成几行可读文本。""" + state = part.get("state") or {} + inp = state.get("input") or {} + tool = part.get("tool") or "tool" + title = state.get("title") or "" + cmd = inp.get("command") or inp.get("filePath") or inp.get("path") or "" + output = state.get("output") or "" + + lines: list[str] = [] + head = title or cmd or tool + lines.append(f"$ {head}") + if cmd and cmd != head: + lines.append(f" {cmd}") + for ln in str(output).splitlines(): + lines.append(ln) + return lines + + +def parse_agent_output(line: str, output_format: str) -> tuple[list[str], str]: + """把 agent 的一行原始输出解析成 (显示用的行列表, session_id)。 + + - `text` 模式:原样返回,session id 交给正则抓 + - `json` 模式:解析事件 —— `part.type=text` 取文本,`part.type=tool` 取工具摘要, + session id 从事件顶层的 `sessionID` 拿 + """ + if output_format != "json": + return [line], "" + + s = line.strip() + if not (s.startswith("{") and s.endswith("}")): + # 不是 json(agent 的 stderr 混进来了)—— 原样透传 + return [line], "" + + try: + obj = json.loads(s) + except json.JSONDecodeError: + return [line], "" + + if not isinstance(obj, dict): + return [], "" + + session_id = str(obj.get("sessionID") or "") + part = obj.get("part") or {} + ptype = part.get("type") + + if ptype == "text": + text = str(part.get("text") or "") + return (text.splitlines() or [""]), session_id + if ptype == "tool": + return _render_tool(part), session_id + return [], session_id + + + +@dataclass +class AgentResult: + exit_code: int | None = None + timed_out: bool = False + timeout_kind: str = "" # idle | total | "" + killed: bool = False + error: str = "" + duration_sec: float = 0.0 + + +@dataclass +class AgentProcess: + """一次 agent 调用。""" + + command: list[str] + cwd: Path + env: dict[str, str] = field(default_factory=dict) + on_line: LineCallback | None = None + idle_timeout_sec: int = 1800 + total_timeout_sec: int = 7200 + kill_grace_sec: int = 15 + output_format: str = "text" + session_pattern: str = "" + + _proc: subprocess.Popen | None = field(default=None, init=False, repr=False) + _thread: threading.Thread | None = field(default=None, init=False, repr=False) + _last_output_at: float = field(default_factory=time.monotonic, init=False) + _started_at: float = field(default_factory=time.monotonic, init=False) + _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) + _session_id: str = field(default="", init=False) + + # ── 生命周期 ──────────────────────────────────────────────────── + def start(self) -> None: + env = os.environ.copy() + env.update(self.env) + env.setdefault("PYTHONIOENCODING", "utf-8") + # 让 agent 认得非交互终端 + env.setdefault("CI", "1") + + kwargs: dict = dict( + cwd=str(self.cwd), + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, + text=True, + encoding="utf-8", + errors="replace", + bufsize=1, + ) + if is_windows(): + kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP + else: + kwargs["start_new_session"] = True + + self._started_at = time.monotonic() + self._last_output_at = self._started_at + self._proc = subprocess.Popen(self.command, **kwargs) + self._thread = threading.Thread(target=self._pump, name="agent-reader", daemon=True) + self._thread.start() + + def _pump(self) -> None: + proc = self._proc + if proc is None or proc.stdout is None: + return + try: + for raw in proc.stdout: + line = raw.rstrip("\n").rstrip("\r") + with self._lock: + self._last_output_at = time.monotonic() + for out in self._expand(line): + if self.on_line is not None: + try: + self.on_line(out) + except Exception: # noqa: BLE001 - UI 回调不该拖垮 agent + pass + except (ValueError, OSError): + pass + finally: + try: + proc.stdout.close() + except (OSError, AttributeError): + pass + + def _expand(self, line: str) -> list[str]: + """把一行原始输出展开成若干行可读文本,并顺手抓 session id。""" + lines, session_id = parse_agent_output(line, self.output_format) + if session_id: + self._remember_session(session_id) + elif self.output_format != "json" and self.session_pattern: + found = extract_session_id(line, self.session_pattern) + if found: + self._remember_session(found) + return lines + + def _remember_session(self, session_id: str) -> None: + with self._lock: + if not self._session_id: + self._session_id = session_id + + @property + def session_id(self) -> str: + """抓到的 agent session id(用于 `--session` 续跑)。""" + with self._lock: + return self._session_id + + @property + def alive(self) -> bool: + return self._proc is not None and self._proc.poll() is None + + @property + def idle_seconds(self) -> float: + with self._lock: + return time.monotonic() - self._last_output_at + + @property + def total_seconds(self) -> float: + return time.monotonic() - self._started_at + + def poll(self) -> int | None: + return self._proc.poll() if self._proc else None + + def wait(self, timeout: float | None = None) -> int | None: + if self._proc is None: + return None + try: + return self._proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + return None + + # ── 超时判定 ──────────────────────────────────────────────────── + def check_timeout(self) -> tuple[bool, str]: + """返回 (是否超时, 超时类型)。""" + if self.total_timeout_sec and self.total_seconds > self.total_timeout_sec: + return True, "total" + if self.idle_timeout_sec and self.idle_seconds > self.idle_timeout_sec: + return True, "idle" + return False, "" + + # ── 终止 ──────────────────────────────────────────────────────── + def terminate(self) -> bool: + """优雅终止:先 TERM,宽限期后 KILL。返回是否真的杀掉了。""" + proc = self._proc + if proc is None or proc.poll() is not None: + return False + + killed = False + try: + if is_windows(): + proc.send_signal(signal.CTRL_BREAK_EVENT) + else: + os.killpg(os.getpgid(proc.pid), signal.SIGTERM) + killed = True + except (ProcessLookupError, PermissionError, OSError): + try: + proc.terminate() + killed = True + except OSError: + pass + + try: + proc.wait(timeout=self.kill_grace_sec) + except subprocess.TimeoutExpired: + try: + if is_windows(): + proc.kill() + else: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except (ProcessLookupError, PermissionError, OSError): + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + return killed + + +def build_command( + agent_command: str, + agent_args: list[str], + prompt: str, + prompt_file: Path | None = None, +) -> list[str]: + """组装 agent 命令行。 + + 提示词优先通过文件传(避免超长命令行在 Windows 上炸掉); + 只有当 agent 明确支持时才用 stdin。 + """ + cmd = [agent_command, *agent_args] + if prompt_file is not None: + cmd += ["--prompt-file", str(prompt_file)] + else: + cmd.append(prompt) + return cmd + + +def check_agent_available(agent_command: str) -> tuple[bool, str]: + """检查 agent 命令是否可用。""" + import shutil + + if shutil.which(agent_command): + return True, "" + # 允许写成 "python -m foo" 这种形式,取第一段做 which + first = agent_command.split()[0] if agent_command.split() else agent_command + if shutil.which(first): + return True, "" + return False, f"找不到 agent 命令: {agent_command}" + + +def platform_hint() -> str: + return f"{sys.platform} / {'Windows' if is_windows() else 'POSIX'}" diff --git a/overnight-runner/overnight_runner/cli.py b/overnight-runner/overnight_runner/cli.py new file mode 100644 index 0000000..3b48e84 --- /dev/null +++ b/overnight-runner/overnight_runner/cli.py @@ -0,0 +1,439 @@ +"""命令行入口。 + +子命令: + init 初始化配置文件(队列 + 项目配置) + add 往队列里追加 plan + list 列出队列 + status 查看运行状态 + decisions 查看决策记录 + queues 列出所有队列 + run 启动(默认分屏面板;--headless 无界面) + +所有子命令都支持全局参数 `--queue `(默认 `default`)。 +""" + +from __future__ import annotations + +import argparse +import json +import sys +import threading +from pathlib import Path + +from . import __version__ +from .config import ( + DECISION_MODE_ATTENDED, + DECISION_MODE_UNATTENDED, + DECISION_MODES, + DEFAULT_AGENT_ARGS, + DEFAULT_AGENT_COMMAND, + DEFAULT_PROJECT_PROMPT, + DEFAULT_QUEUE_NAME, + ProjectConfig, + QueuePaths, + load_project_config, + load_runner_config, + migrate_legacy_queue, + queue_config_path, + queue_names, + queue_paths, + save_project_config, + save_runner_config, +) +from .controller import RunnerController +from .decisions import DecisionLog +from .queue import ( + PENDING, + Queue, + build_task, + load_queue, + load_queue_defs, + save_queue_defs, + save_state, +) +from .util import QueueLock, StopFlag, fmt_duration, fmt_ts, now + + +def _project_root(args) -> Path: + return Path(args.project).expanduser().resolve() + + +def _queue_paths(args) -> QueuePaths: + """解析本次命令要操作的队列(顺带做老布局迁移)。""" + root = _project_root(args) + note = migrate_legacy_queue(root) + if note: + print(f"已迁移旧队列布局 → .overnight-runner/queue/{DEFAULT_QUEUE_NAME}/({note})") + name = getattr(args, "queue", DEFAULT_QUEUE_NAME) or DEFAULT_QUEUE_NAME + try: + return queue_paths(root, name) + except ValueError as exc: + print(f"错误: {exc}", file=sys.stderr) + raise SystemExit(2) + + +def resolve_decision_mode( + cfg, mode_override: str | None = None, headless: bool = False +) -> str: + """决定本次运行用哪个决策模式。 + + 优先级:headless(强制无人值守)> 命令行 --mode > 配置文件。 + """ + if headless: + return DECISION_MODE_UNATTENDED + if mode_override: + return mode_override + return cfg.decision.mode + + +# ── init ──────────────────────────────────────────────────────────── +def cmd_init(args) -> int: + root = _project_root(args) + root.mkdir(parents=True, exist_ok=True) + paths = _queue_paths(args) + + qpath = queue_config_path(root) + if not qpath.exists(): + cfg = load_runner_config(root) + cfg.agent_command = args.agent or cfg.agent_command + cfg.agent_args = list(args.agent_args) if args.agent_args else cfg.agent_args + save_runner_config(root, cfg) + print(f"已创建运行配置: {qpath}") + else: + print(f"运行配置已存在,保持不变: {qpath}") + + if not paths.config.exists(): + paths.dir.mkdir(parents=True, exist_ok=True) + save_queue_defs(paths, Queue()) + print(f"已创建队列: {paths.name} → {paths.config}") + else: + print(f"队列已存在,保持不变: {paths.config}") + + ppath = root / ".overnight-runner" / "project.yaml" + if not ppath.exists(): + pcfg = ProjectConfig(name=root.name) + pcfg.agent_command = args.agent or DEFAULT_AGENT_COMMAND + pcfg.agent_args = list(args.agent_args) if args.agent_args else list(DEFAULT_AGENT_ARGS) + pcfg.default_prompt = DEFAULT_PROJECT_PROMPT + save_project_config(root, pcfg) + print(f"已创建项目配置: {ppath}") + else: + print(f"项目配置已存在,保持不变: {ppath}") + + print() + print("下一步:") + print(f" 1) 编辑 {paths.config} 填入 queue(plan 用相对项目根的路径)") + print(f" 2) 编辑 {ppath} 配默认提示词与默认决策") + print(f" 3) 运行: overnight-runner --queue {paths.name} run") + return 0 + + +# ── add ───────────────────────────────────────────────────────────── +def cmd_add(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + cfg = load_runner_config(root) + queue = load_queue(paths, load_queue_defs(paths)) + + try: + task = build_task( + root, + args.plan, + prompt=args.prompt or "", + role=args.role or "", + priority=args.priority, + existing_ids={t.id for t in queue.tasks}, + ) + queue.add(task) + except ValueError as exc: + print(f"错误: {exc}", file=sys.stderr) + return 1 + + save_queue_defs(paths, queue) + print(f"已加入队列 [{paths.name}]: {task.id} → {task.plan}") + return 0 + + +# ── list ──────────────────────────────────────────────────────────── +def cmd_list(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + queue = load_queue(paths, load_queue_defs(paths)) + + print(f"队列: {paths.name}") + if not len(queue): + print("队列为空。用 `overnight-runner add ` 追加。") + return 0 + + print(f"{'ID':<32} {'状态':<8} {'次':<3} {'耗时':<8} PLAN") + print("-" * 100) + for t in queue.tasks: + print( + f"{t.id:<32} {t.status:<8} {t.attempts:<3} " + f"{fmt_duration(t.duration_sec):<8} {t.plan}" + ) + return 0 + + +# ── status ────────────────────────────────────────────────────────── +def cmd_status(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + cfg = load_runner_config(root) + queue = load_queue(paths, load_queue_defs(paths)) + stats = queue.stats() + + print(f"项目: {root}") + print(f"队列: {paths.name}") + print(f"agent: {cfg.agent_command} {' '.join(cfg.agent_args)}") + print(f"决策: {cfg.decision.mode}({DECISION_MODE_ATTENDED}=有人值守 / " + f"{DECISION_MODE_UNATTENDED}=无人值守)· 等待 {cfg.decision.timeout_sec}s") + print(f"看门狗: 重试 {cfg.watchdog.max_retries} 次 · 退避 {cfg.watchdog.backoff_sec}s · " + f"空闲超时 {cfg.watchdog.idle_timeout_sec}s · 总超时 {cfg.watchdog.total_timeout_sec}s") + print() + for k in ("pending", "running", "retrying", "success", "failed", "blocked", "stopped"): + if stats.get(k): + print(f" {k:<10} {stats[k]}") + print() + for t in queue.tasks: + if t.status in ("failed", "blocked"): + print(f" ✘ {t.id}: {t.last_error}") + return 0 + + +# ── decisions ─────────────────────────────────────────────────────── +def cmd_decisions(args) -> int: + paths = _queue_paths(args) + log = DecisionLog(paths.decisions) + records = log.load() + + if not records: + print(f"队列 [{paths.name}] 还没有决策记录。") + return 0 + + if args.json: + print(json.dumps(records, ensure_ascii=False, indent=2)) + return 0 + + print(f"队列: {paths.name}") + print(f"{'时间':<20} {'任务':<28} {'来源':<9} 问题 → 答案") + print("-" * 110) + for r in records: + print( + f"{str(r.get('at',''))[:19]:<20} {str(r.get('task_id',''))[:27]:<28} " + f"{str(r.get('source','')):<9} {r.get('question','')} → {r.get('answer','')}" + ) + return 0 + + +# ── queues ────────────────────────────────────────────────────────── +def cmd_queues(args) -> int: + root = _project_root(args) + note = migrate_legacy_queue(root) + if note: + print(f"已迁移旧队列布局 → .overnight-runner/queue/{DEFAULT_QUEUE_NAME}/({note})") + names = queue_names(root) + if not names: + print("还没有任何队列。用 `overnight-runner init` 建一条。") + return 0 + + print(f"{'队列':<16} {'任务':<6} {'待跑':<6} {'运行':<6} {'成功':<6} {'失败':<6} 最后活动") + print("-" * 78) + for name in names: + paths = queue_paths(root, name) + queue = load_queue(paths, load_queue_defs(paths)) + stats = queue.stats() + last = _last_activity(queue) + print( + f"{name:<16} {len(queue):<6} {stats.get(PENDING, 0):<6} " + f"{stats.get('running', 0):<6} {stats.get('success', 0):<6} " + f"{stats.get('failed', 0):<6} {last}" + ) + return 0 + + +def _last_activity(queue: Queue) -> str: + times = [t.finished_at or t.started_at for t in queue.tasks] + times = [t for t in times if t is not None] + if not times: + return "-" + return fmt_ts(max(times)) + + +# ── run ───────────────────────────────────────────────────────────── +def cmd_run(args) -> int: + root = _project_root(args) + paths = _queue_paths(args) + cfg = load_runner_config(root) + project_cfg = load_project_config(root) + queue = load_queue(paths, load_queue_defs(paths)) + + # 决策模式:命令行优先;headless 强制无人值守(没人看面板,不能卡在等决策上) + cfg.decision.mode = resolve_decision_mode( + cfg, getattr(args, "mode", None), args.headless + ) + + if getattr(args, "retry_failed", False): + reset = 0 + for t in queue.tasks: + if t.status in ("failed", "blocked", "stopped"): + t.status = PENDING + t.attempts = 0 + t.last_error = "" + t.exit_code = None + t.finished_at = None + t.summary = "" + reset += 1 + if reset: + save_state(paths, queue) + print(f"已重置 {reset} 个失败/阻塞任务。") + + lock = QueueLock(paths.lock) + ok, err = lock.acquire() + if not ok: + print(f"错误: {err}(同一条队列不能同时跑两个 runner)", file=sys.stderr) + return 2 + + stop = StopFlag() + controller = RunnerController(root, cfg, project_cfg, queue, paths, stop=stop) + + try: + if args.headless: + return _run_headless(controller, queue, paths, stop, args) + + try: + from .ui import RunnerUI + except ImportError as exc: # pragma: no cover - 只在环境被破坏时触发 + print(f"无法启动面板: {exc}", file=sys.stderr) + print("也可以用 --headless 无界面运行。", file=sys.stderr) + return 2 + + ui = RunnerUI(controller, queue, cfg, root, paths) + + worker = threading.Thread(target=controller.run_forever, name="runner", daemon=True) + worker.start() + heartbeat = threading.Thread(target=_heartbeat, args=(lock, stop), daemon=True) + heartbeat.start() + + try: + ui.run() + finally: + stop.set() + worker.join(timeout=10) + finally: + lock.release() + + save_state(paths, queue) + return 0 + + +def _heartbeat(lock: QueueLock, stop: StopFlag) -> None: + """定期更新锁的心跳(长跑时用来识别 stale 锁)。""" + while not stop.is_set(): + lock.touch() + stop.wait(timeout=15) + + +def _run_headless(controller, queue, paths, stop, args) -> int: + """无界面模式:直接跑,输出到 stdout。适合 CI / 脚本。""" + def on_event(kind: str, task) -> None: + if task is not None: + print(f"[{fmt_ts(now())}] {kind:<16} {task.id} {task.plan}") + else: + print(f"[{fmt_ts(now())}] {kind}") + + def on_log(line: str) -> None: + if args.verbose: + print(f" {line}") + + controller.on_event = on_event + controller.on_log = on_log + + controller.run_forever() + save_state(paths, queue) + + stats = queue.stats() + failed = [t for t in queue.tasks if t.status in ("failed", "blocked")] + print() + print(controller.snapshot()) + if failed: + print() + print("失败任务:") + for t in failed: + print(f" ✘ {t.id}: {t.last_error}") + return 1 if failed else 0 + + +# ── 参数解析 ──────────────────────────────────────────────────────── +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + prog="overnight-runner", + description="把一串 plan 交给 coding agent 无人值守地跑", + ) + p.add_argument("--version", action="version", version=f"overnight-runner {__version__}") + p.add_argument("--project", default=".", help="项目根目录(默认当前目录)") + p.add_argument( + "--queue", + default=DEFAULT_QUEUE_NAME, + help=f"队列名(默认 {DEFAULT_QUEUE_NAME})", + ) + sub = p.add_subparsers(dest="command") + + s = sub.add_parser("init", help="初始化配置文件") + s.add_argument("--agent", help="coding agent 命令,如 opencode / claude / codex") + s.add_argument("--agent-args", nargs="*", help="agent 参数,默认 run") + s.set_defaults(func=cmd_init) + + s = sub.add_parser("add", help="往队列追加 plan") + s.add_argument("plan", help="plan 文件路径(相对项目根或绝对路径)") + s.add_argument("--prompt", default="", help="补充要求") + s.add_argument("--role", default="", help="角色标签 BA / DEV / QA") + s.add_argument("--priority", type=int, default=100, help="优先级,数字小的先跑") + s.set_defaults(func=cmd_add) + + s = sub.add_parser("list", help="列出队列") + s.set_defaults(func=cmd_list) + + s = sub.add_parser("status", help="查看运行状态") + s.set_defaults(func=cmd_status) + + s = sub.add_parser("decisions", help="查看决策记录") + s.add_argument("--json", action="store_true", help="输出 JSON") + s.set_defaults(func=cmd_decisions) + + s = sub.add_parser("queues", help="列出所有队列") + s.set_defaults(func=cmd_queues) + + s = sub.add_parser("run", help="启动(默认分屏面板;--headless 无界面)") + s.add_argument("--headless", action="store_true", help="无界面模式") + s.add_argument("--verbose", action="store_true", help="headless 模式下打印 agent 输出") + s.add_argument( + "--retry-failed", + action="store_true", + help="把失败/阻塞的任务重置为待跑", + ) + s.add_argument( + "--mode", + choices=list(DECISION_MODES), + default=None, + help=( + f"决策模式:{DECISION_MODE_ATTENDED}=有人值守(弹窗问人," + f"超时自动决策)/ {DECISION_MODE_UNATTENDED}=无人值守(直接决策)" + ), + ) + s.set_defaults(func=cmd_run) + + return p + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + if not getattr(args, "func", None): + parser.print_help() + return 2 + return args.func(args) + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/overnight-runner/overnight_runner/config.py b/overnight-runner/overnight_runner/config.py new file mode 100644 index 0000000..ff4d6fc --- /dev/null +++ b/overnight-runner/overnight_runner/config.py @@ -0,0 +1,534 @@ +"""配置加载:队列配置(overnight-runner.yaml)与项目配置(.overnight-runner/project.yaml)。 + +配置分三层: + +- **runner 级**:`overnight-runner.yaml` —— agent 命令、看门狗、UI、决策策略(项目共享) +- **project 级**:`.overnight-runner/project.yaml` —— 默认提示词与默认决策规则(全队列共享) +- **queue 级**:`.overnight-runner/queue//queue.yaml` —— 队列里的任务列表(每条队列一份) +""" + +from __future__ import annotations + +import re +import shutil +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from . import yaml_lite as yaml + +from .util import atomic_write + +QUEUE_CONFIG_NAME = "overnight-runner.yaml" +PROJECT_DIR_NAME = ".overnight-runner" +PROJECT_CONFIG_NAME = "project.yaml" + +# 多队列:每条队列在 .overnight-runner/queue// 下有一份独立目录 +QUEUE_DIR_NAME = "queue" +DEFAULT_QUEUE_NAME = "default" +QUEUE_FILE_NAME = "queue.yaml" +STATE_FILE_NAME = "state.json" +LOGS_DIR_NAME = "logs" +DECISIONS_FILE_NAME = "decisions.jsonl" +LOCK_FILE_NAME = ".lock" + +DEFAULT_AGENT_COMMAND = "opencode" +DEFAULT_AGENT_ARGS: list[str] = ["run"] + +# 决策模式:attended = 有人值守(弹窗问人);unattended = 无人值守(直接决策) +DECISION_MODE_ATTENDED = "attended" +DECISION_MODE_UNATTENDED = "unattended" +DECISION_MODES = (DECISION_MODE_ATTENDED, DECISION_MODE_UNATTENDED) + +# 队列名白名单:不允许路径穿越 +QUEUE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + + + +# ── 项目配置 ──────────────────────────────────────────────────────── +@dataclass +class DecisionRule: + """一条默认决策:命中问题类别就用预设答案,并且记一笔。""" + + id: str + question: str = "" + match: str = "" + answer: str = "" + enabled: bool = True + + def describe(self) -> str: + return f"{self.id}: {self.question or self.match} → {self.answer}" + + +@dataclass +class ProjectConfig: + name: str = "" + agent_command: str = DEFAULT_AGENT_COMMAND + agent_args: list[str] = field(default_factory=lambda: list(DEFAULT_AGENT_ARGS)) + agent_env: dict[str, str] = field(default_factory=dict) + default_prompt: str = "" + decisions: list[DecisionRule] = field(default_factory=list) + on_unknown_decision: str = "跳过并记录到决策日志" + source_path: Path | None = None + + def decision_text(self) -> str: + if not self.decisions: + return "" + lines = [f"- [{d.id}] {d.question or d.match} → {d.answer}" for d in self.decisions] + return "\n".join(lines) + + def to_yaml(self) -> str: + data = { + "project": { + "name": self.name, + "agent": { + "command": self.agent_command, + "args": self.agent_args, + "env": self.agent_env, + }, + }, + "default": { + "prompt": self.default_prompt, + "onUnknownDecision": self.on_unknown_decision, + }, + "decisions": [ + { + "id": d.id, + "question": d.question, + "match": d.match, + "answer": d.answer, + "enabled": d.enabled, + } + for d in self.decisions + ], + } + return yaml.dumps(data) + + +DEFAULT_PROJECT_PROMPT = """\ +你在无人值守模式下工作,不要停下来等待人工确认。 + +按下面的方案执行,遇到需要决策的问题,按"默认决策"处理: +{{DECISIONS}} + +{{PLAN}} + +执行要求: +1. 每做出一个决策,输出一行:DECISION: <问题> → <决策> +2. 全部完成后输出一行:DONE: <一句话总结> +3. 如果无法继续,输出一行:BLOCKED: <原因> +""" + + +def load_project_config(project_root: Path) -> ProjectConfig: + path = project_root / PROJECT_DIR_NAME / PROJECT_CONFIG_NAME + cfg = ProjectConfig(source_path=path) + if not path.exists(): + cfg.default_prompt = DEFAULT_PROJECT_PROMPT + return cfg + + data = yaml.loads(path.read_text(encoding="utf-8")) or {} + proj = data.get("project") or {} + cfg.name = proj.get("name") or project_root.name + + agent = proj.get("agent") or {} + cfg.agent_command = agent.get("command") or DEFAULT_AGENT_COMMAND + cfg.agent_args = list(agent.get("args") or DEFAULT_AGENT_ARGS) + cfg.agent_env = dict(agent.get("env") or {}) + + default = data.get("default") or {} + cfg.default_prompt = default.get("prompt") or DEFAULT_PROJECT_PROMPT + cfg.on_unknown_decision = default.get("onUnknownDecision") or cfg.on_unknown_decision + + for item in data.get("decisions") or []: + cfg.decisions.append( + DecisionRule( + id=str(item.get("id") or f"rule-{len(cfg.decisions) + 1}"), + question=item.get("question") or "", + match=item.get("match") or "", + answer=item.get("answer") or "", + enabled=bool(item.get("enabled", True)), + ) + ) + return cfg + + +def save_project_config(project_root: Path, cfg: ProjectConfig) -> Path: + path = project_root / PROJECT_DIR_NAME / PROJECT_CONFIG_NAME + atomic_write(path, cfg.to_yaml()) + return path + + +# ── 多队列:路径解析与老布局迁移 ──────────────────────────────────── +@dataclass(frozen=True) +class QueuePaths: + """一条队列在磁盘上的全部路径。""" + + root: Path + name: str + + @property + def dir(self) -> Path: + return self.root / PROJECT_DIR_NAME / QUEUE_DIR_NAME / self.name + + @property + def config(self) -> Path: + """队列定义(进版本库)。""" + return self.dir / QUEUE_FILE_NAME + + @property + def state(self) -> Path: + """运行时状态(不进版本库)。""" + return self.dir / STATE_FILE_NAME + + @property + def logs(self) -> Path: + """agent 日志与 prompt 文件(不进版本库)。""" + return self.dir / LOGS_DIR_NAME + + @property + def decisions(self) -> Path: + """决策记录(进版本库)。""" + return self.dir / DECISIONS_FILE_NAME + + @property + def lock(self) -> Path: + """单实例锁(不进版本库)。""" + return self.dir / LOCK_FILE_NAME + + +def queue_paths(project_root: Path, name: str = DEFAULT_QUEUE_NAME) -> QueuePaths: + """解析一条队列的路径。队列名非法直接报错(防路径穿越)。""" + if not name or not QUEUE_NAME_RE.match(name): + raise ValueError( + f"队列名不合法: {name!r}(只允许字母、数字、. _ -,且必须以字母或数字开头)" + ) + return QueuePaths(root=project_root, name=name) + + +def queue_names(project_root: Path) -> list[str]: + """列出磁盘上已有的队列名(按字典序)。""" + base = project_root / PROJECT_DIR_NAME / QUEUE_DIR_NAME + if not base.is_dir(): + return [] + out = [ + p.name + for p in sorted(base.iterdir(), key=lambda x: x.name) + if p.is_dir() and QUEUE_NAME_RE.match(p.name) + ] + return out + + +def strip_queue_section(text: str) -> str: + """从 YAML 文本里删掉顶层的 `queue:` 段,**其余内容原样保留**。 + + 为什么不用"解析 → 改 → 重新序列化":那样会把用户写的注释全弄丢。 + 这里按行做手术,只动 `queue:` 那一段。 + + - `queue:` 后面跟缩进内容(块序列)→ 整段删掉 + - `queue: []` 这种内联写法 → 改成 `queue: []`(保持只有一个空段) + """ + lines = text.split("\n") + out: list[str] = [] + i = 0 + n = len(lines) + while i < n: + line = lines[i] + m = re.match(r"^queue\s*:(.*)$", line) + if not m: + out.append(line) + i += 1 + continue + + tail = m.group(1).strip() + if tail and not tail.startswith("#"): + # 内联写法(queue: [] / queue: [...])—— 归一成空列表 + out.append("queue: []") + i += 1 + continue + + # 块序列:吃掉这一行 + 后面所有缩进行 + i += 1 + while i < n: + nxt = lines[i] + if nxt.strip() == "": + # 空行:后面若还有缩进内容就一并吃掉 + j = i + while j < n and lines[j].strip() == "": + j += 1 + if j < n and lines[j][:1] in (" ", "\t"): + i = j + continue + break + if nxt[:1] in (" ", "\t"): + i += 1 + continue + break + return "\n".join(out) + + +def migrate_legacy_queue(project_root: Path) -> str: + """把老布局迁移到 `.overnight-runner/queue/default/`。 + + 老布局: + /overnight-runner.yaml 的 queue: 段 + /.overnight-runner/state.json + /.overnight-runner/logs/ + /.overnight-runner/decisions.jsonl + + 迁移是 **幂等** 的:源清空后第二次调用直接返回空串。 + 用的是 move(rename)不是 copy,源文件不会留下两份。 + + 返回一句人类可读的迁移说明(没迁移则返回空串)。 + """ + notes: list[str] = [] + default = queue_paths(project_root, DEFAULT_QUEUE_NAME) + + # 1) 队列定义:根配置文件的 queue: 段 → queue/default/queue.yaml + legacy_cfg_path = queue_config_path(project_root) + if legacy_cfg_path.exists(): + raw = legacy_cfg_path.read_text(encoding="utf-8") + data = yaml.loads(raw) or {} + legacy_queue = list(data.get("queue") or []) + if legacy_queue and not default.config.exists(): + default.dir.mkdir(parents=True, exist_ok=True) + atomic_write( + default.config, + yaml.dumps({"queue": legacy_queue}), + ) + notes.append(f"队列定义 → {default.config}") + # 把根配置里的 queue: 段清空,保证只迁移一次。 + # 按行做手术,保留用户写的注释与排版。 + atomic_write(legacy_cfg_path, strip_queue_section(raw)) + + # 2) 运行时状态 / 日志 / 决策记录:整体搬进 default 队列目录 + legacy_dir = project_root / PROJECT_DIR_NAME + for name, dest in ( + (STATE_FILE_NAME, default.state), + (LOGS_DIR_NAME, default.logs), + (DECISIONS_FILE_NAME, default.decisions), + ): + src = legacy_dir / name + if not src.exists(): + continue + if dest.exists(): + continue + default.dir.mkdir(parents=True, exist_ok=True) + shutil.move(str(src), str(dest)) + notes.append(f"{src} → {dest}") + + return ";".join(notes) + + +# ── 队列配置 ──────────────────────────────────────────────────────── +@dataclass +class WatchdogConfig: + max_retries: int = 2 + backoff_sec: int = 60 + idle_timeout_sec: int = 1800 + total_timeout_sec: int = 7200 + kill_grace_sec: int = 15 + + @classmethod + def from_dict(cls, data: dict | None) -> "WatchdogConfig": + data = data or {} + return cls( + max_retries=int(data.get("maxRetries", 2)), + backoff_sec=int(data.get("backoffSec", 60)), + idle_timeout_sec=int(data.get("idleTimeoutSec", 1800)), + total_timeout_sec=int(data.get("totalTimeoutSec", 7200)), + kill_grace_sec=int(data.get("killGraceSec", 15)), + ) + + def to_dict(self) -> dict: + return { + "maxRetries": self.max_retries, + "backoffSec": self.backoff_sec, + "idleTimeoutSec": self.idle_timeout_sec, + "totalTimeoutSec": self.total_timeout_sec, + "killGraceSec": self.kill_grace_sec, + } + + +@dataclass +class DecisionConfig: + """决策策略。 + + - `mode=attended`(有人值守):agent 抛问题时打断它,TUI 弹决策窗口问人; + 超时没人答就按规则/兜底策略自动决策。 + - `mode=unattended`(无人值守):不打断 agent,按规则/兜底策略直接决策。 + """ + + mode: str = DECISION_MODE_ATTENDED + timeout_sec: int = 600 + resume: str = "session" # session | restart + output_format: str = "json" # json | text + json_args: list[str] = field(default_factory=lambda: ["--format", "json"]) + session_args: list[str] = field(default_factory=lambda: ["--session", "{session}"]) + session_pattern: str = r'"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"' + + @classmethod + def from_dict(cls, data: dict | None) -> "DecisionConfig": + data = data or {} + mode = str(data.get("mode") or DECISION_MODE_ATTENDED) + if mode not in DECISION_MODES: + mode = DECISION_MODE_ATTENDED + resume = str(data.get("resume") or "session") + if resume not in ("session", "restart"): + resume = "session" + output_format = str(data.get("outputFormat") or "json") + if output_format not in ("json", "text"): + output_format = "json" + args = data.get("sessionArgs") + if not isinstance(args, list) or not args: + args = ["--session", "{session}"] + json_args = data.get("jsonArgs") + if not isinstance(json_args, list) or not json_args: + json_args = ["--format", "json"] + return cls( + mode=mode, + timeout_sec=int(data.get("timeoutSec", 600)), + resume=resume, + output_format=output_format, + json_args=[str(a) for a in json_args], + session_args=[str(a) for a in args], + session_pattern=str( + data.get("sessionPattern") + or r'"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"' + ), + ) + + def to_dict(self) -> dict: + return { + "mode": self.mode, + "timeoutSec": self.timeout_sec, + "resume": self.resume, + "outputFormat": self.output_format, + "jsonArgs": list(self.json_args), + "sessionArgs": list(self.session_args), + "sessionPattern": self.session_pattern, + } + + def session_command(self, session_id: str) -> list[str]: + """把 session_args 里的 {session} 占位符替换成真实 session id。""" + return [a.replace("{session}", session_id) for a in self.session_args] + + +@dataclass +class RunnerConfig: + """启动时用的队列配置(overnight-runner.yaml)。""" + + agent_command: str = DEFAULT_AGENT_COMMAND + agent_args: list[str] = field(default_factory=lambda: list(DEFAULT_AGENT_ARGS)) + agent_env: dict[str, str] = field(default_factory=dict) + watchdog: WatchdogConfig = field(default_factory=WatchdogConfig) + decision: DecisionConfig = field(default_factory=DecisionConfig) + state_dir: str = PROJECT_DIR_NAME + workdir: str = "." + refresh_hz: int = 8 + log_tail: int = 400 + queue: list[dict] = field(default_factory=list) + source_path: Path | None = None + + @classmethod + def from_dict(cls, data: dict, source_path: Path | None = None) -> "RunnerConfig": + runner = data.get("runner") or {} + agent = runner.get("agent") or {} + cfg = cls( + agent_command=agent.get("command") or DEFAULT_AGENT_COMMAND, + agent_args=list(agent["args"]) if agent.get("args") is not None else list(DEFAULT_AGENT_ARGS), + agent_env=dict(agent.get("env") or {}), + watchdog=WatchdogConfig.from_dict(runner.get("watchdog")), + decision=DecisionConfig.from_dict(runner.get("decision")), + state_dir=runner.get("state", {}).get("dir") or PROJECT_DIR_NAME, + workdir=runner.get("workdir") or ".", + refresh_hz=int((runner.get("ui") or {}).get("refreshHz", 8)), + log_tail=int((runner.get("ui") or {}).get("logTail", 400)), + queue=list(data.get("queue") or []), + source_path=source_path, + ) + return cfg + + def to_dict(self) -> dict: + data: dict[str, Any] = { + "runner": { + "agent": { + "command": self.agent_command, + "args": self.agent_args, + "env": self.agent_env, + }, + "watchdog": self.watchdog.to_dict(), + "decision": self.decision.to_dict(), + "state": {"dir": self.state_dir}, + "workdir": self.workdir, + "ui": {"refreshHz": self.refresh_hz, "logTail": self.log_tail}, + } + } + # 队列定义已经搬到 .overnight-runner/queue//queue.yaml,这里只在 + # 还没迁移时保留(迁移后为空 → 不写出去) + if self.queue: + data["queue"] = self.queue + return data + + def to_yaml(self) -> str: + header = ( + "# overnight-runner 运行配置\n" + "# agent / 看门狗 / UI / 决策策略 —— 项目级,全队列共享\n" + "# 队列里的任务在 .overnight-runner/queue//queue.yaml\n" + ) + return header + yaml.dumps(self.to_dict()) + + +def queue_config_path(project_root: Path) -> Path: + return project_root / QUEUE_CONFIG_NAME + + +def load_runner_config(project_root: Path) -> RunnerConfig: + path = queue_config_path(project_root) + if not path.exists(): + return RunnerConfig(source_path=path) + data = yaml.loads(path.read_text(encoding="utf-8")) or {} + return RunnerConfig.from_dict(data, source_path=path) + + +def save_runner_config(project_root: Path, cfg: RunnerConfig) -> Path: + path = queue_config_path(project_root) + atomic_write(path, cfg.to_yaml()) + return path + + +def default_queue_config(project_root: Path) -> RunnerConfig: + cfg = RunnerConfig(source_path=queue_config_path(project_root)) + cfg.queue = [] + return cfg + + +__all__ = [ + "DECISION_MODES", + "DECISION_MODE_ATTENDED", + "DECISION_MODE_UNATTENDED", + "DEFAULT_QUEUE_NAME", + "DecisionConfig", + "DecisionRule", + "ProjectConfig", + "QueuePaths", + "RunnerConfig", + "WatchdogConfig", + "default_queue_config", + "load_project_config", + "load_runner_config", + "migrate_legacy_queue", + "queue_config_path", + "queue_names", + "queue_paths", + "save_project_config", + "save_runner_config", + "DEFAULT_AGENT_ARGS", + "DEFAULT_AGENT_COMMAND", + "DEFAULT_PROJECT_PROMPT", + "PROJECT_CONFIG_NAME", + "PROJECT_DIR_NAME", + "QUEUE_CONFIG_NAME", + "QUEUE_DIR_NAME", + "QUEUE_FILE_NAME", +] diff --git a/overnight-runner/overnight_runner/controller.py b/overnight-runner/overnight_runner/controller.py new file mode 100644 index 0000000..9225f57 --- /dev/null +++ b/overnight-runner/overnight_runner/controller.py @@ -0,0 +1,605 @@ +"""调度器:取任务 → 跑 agent → 看门狗 → 决策 → 失败重试 → 落状态。 + +决策有两条路: + +- **unattended(无人值守)**:agent 抛 `QUESTION:` 时当场按规则/兜底策略决策, + **不打断** agent;决策会在下一次拉起 agent 时注入 prompt。 +- **attended(有人值守)**:打断 agent,TUI 弹决策窗口问人;人答了就用 + `opencode run --session ` 续跑;超时没人答就按规则/兜底策略兜底。 +""" + +from __future__ import annotations + +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +from .agent import AgentProcess, check_agent_available +from .config import ProjectConfig, QueuePaths, RunnerConfig +from .decisions import ( + SOURCE_AGENT, + SOURCE_FALLBACK, + SOURCE_HUMAN, + SOURCE_RULE, + SOURCE_TIMEOUT, + DecisionEvent, + DecisionLog, + parse_agent_line, + resolve_answer, + should_ask, +) +from .prompts import build_prompt, build_resume_prompt +from .queue import ( + BLOCKED, + FAILED, + PENDING, + RETRYING, + RUNNING, + STOPPED, + SUCCESS, + Queue, + Task, + save_state, +) +from .util import StopFlag, fmt_ts, now, sleep_interruptible + +EventCallback = Callable[[str, Task], None] + +# 单个任务最多被打断几次(防止 agent 无限提问拖死队列) +MAX_DECISIONS_PER_TASK = 10 + + +@dataclass +class TaskOutcome: + task_id: str + status: str + exit_code: int | None + attempts: int + duration_sec: float + error: str = "" + summary: str = "" + decisions: int = 0 + + +@dataclass +class WatchResult: + """一次 agent 运行的观察结果。""" + + kind: str = "exited" # exited | timeout | question | stopped + timeout_kind: str = "" + question: str = "" + session_id: str = "" + + +class RunnerController: + """把队列里的 plan 一个一个交给 coding agent 跑。""" + + def __init__( + self, + project_root: Path, + runner_cfg: RunnerConfig, + project_cfg: ProjectConfig, + queue: Queue, + paths: QueuePaths, + stop: StopFlag | None = None, + on_event: EventCallback | None = None, + on_log: Callable[[str], None] | None = None, + ) -> None: + self.project_root = project_root + self.runner_cfg = runner_cfg + self.project_cfg = project_cfg + self.queue = queue + self.paths = paths + self.stop = stop or StopFlag() + self.on_event = on_event + self.on_log = on_log + + self.log_dir = paths.logs + self.decision_log = DecisionLog(paths.decisions) + self.decision_log.load() + + self._current: Task | None = None + self._current_proc: AgentProcess | None = None + self._current_lines: list[str] = [] + self._lock = threading.Lock() + + # 决策:agent 抛出的问题、等待人回答、已作出的决策 + self._ask_question: tuple[str, str] | None = None + self._decisions_made: list[tuple[str, str]] = [] + self._decision_lock = threading.Lock() + self._decision_event = threading.Event() + self._pending: dict | None = None + self._answer: str | None = None + + # ── 事件 ──────────────────────────────────────────────────────── + def _emit(self, kind: str, task: Task | None = None) -> None: + if self.on_event is not None: + try: + self.on_event(kind, task or self._current) # type: ignore[arg-type] + except Exception: # noqa: BLE001 + pass + + def _log(self, line: str) -> None: + with self._lock: + self._current_lines.append(line) + if len(self._current_lines) > 2000: + self._current_lines = self._current_lines[-1000:] + if self.on_log is not None: + try: + self.on_log(line) + except Exception: # noqa: BLE001 + pass + + @property + def current_lines(self) -> list[str]: + with self._lock: + return list(self._current_lines) + + def clear_log(self) -> None: + with self._lock: + self._current_lines = [] + + # ── 决策:等待人回答 ──────────────────────────────────────────── + def pending_question(self) -> dict | None: + """当前正在等人回答的问题(没有则 None)。UI 渲染决策窗口用。""" + with self._decision_lock: + if self._pending is None: + return None + pending = dict(self._pending) + deadline = pending.get("deadline") + pending["remaining"] = ( + max(0.0, deadline - time.monotonic()) if deadline else None + ) + return pending + + def submit_decision(self, answer: str) -> None: + """人在 TUI 里回答了问题。""" + with self._decision_lock: + self._answer = answer + self._decision_event.set() + + def cancel_decision(self) -> None: + """人按 Esc:不等了,直接用默认决策兜底。""" + with self._decision_lock: + self._answer = None + self._decision_event.set() + + def _wait_for_human( + self, task: Task, question: str, session_id: str + ) -> tuple[str | None, float]: + """等人回答。返回 (答案 or None, 等了多久秒)。""" + timeout = self.runner_cfg.decision.timeout_sec + started = time.monotonic() + deadline = (started + timeout) if timeout else None + + with self._decision_lock: + self._pending = { + "task_id": task.id, + "question": question, + "session_id": session_id, + "deadline": deadline, + "timeout_sec": timeout, + } + self._answer = None + self._decision_event.clear() + + self._emit("question_pending", task) + answer: str | None = None + try: + while True: + if self._decision_event.wait(timeout=0.2): + with self._decision_lock: + answer = self._answer + break + if deadline is not None and time.monotonic() >= deadline: + answer = None + break + if self.stop.is_set(): + return None, time.monotonic() - started + finally: + with self._decision_lock: + self._pending = None + self._decision_event.clear() + return answer, time.monotonic() - started + + def _resolve_question( + self, task: Task, question: str, session_id: str + ) -> tuple[str, str, float, str]: + """有人值守模式下的决策:问人 → 答 / 超时兜底。""" + answer, waited = self._wait_for_human(task, question, session_id) + + if answer is None: + fallback, rule_id = resolve_answer(self.project_cfg, question) + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=question, + answer=fallback, + source=SOURCE_TIMEOUT, + rule_id=rule_id, + waited_sec=waited, + session_id=session_id, + ) + ) + return fallback, SOURCE_TIMEOUT, waited, session_id + + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=question, + answer=answer, + source=SOURCE_HUMAN, + waited_sec=waited, + session_id=session_id, + ) + ) + return answer, SOURCE_HUMAN, waited, session_id + + def _append_decision(self, question: str, answer: str) -> None: + with self._lock: + self._decisions_made.append((question, answer)) + + @property + def decisions_made(self) -> list[tuple[str, str]]: + with self._lock: + return list(self._decisions_made) + + # ── 主循环 ────────────────────────────────────────────────────── + def run_forever(self) -> None: + """一直取任务跑,直到队列跑完或收到停止信号。""" + self._emit("runner_started") + while not self.stop.is_set(): + task = self.queue.next_ready() + if task is None: + if not self.queue.has_unfinished(): + break + # 有任务卡在依赖或重试等待里 + if not self._wait_for_retry(): + break + continue + self.run_task(task) + self._emit("runner_stopped") + self._save() + + def _wait_for_retry(self) -> bool: + """等一个正在重试等待中的任务到期。返回 False 表示应该退出。""" + for t in self.queue.tasks: + if t.status == RETRYING: + wait = max(0.0, t.duration_sec or 0.0) + if wait <= 0: + return True + self._emit("retry_wait", t) + sleep_interruptible(min(wait, 5), self.stop) + return True + # 没有在重试的任务,但还有未完成 —— 说明被依赖卡住了 + blocked = [t for t in self.queue.tasks if t.status == PENDING and not t.enabled] + if blocked: + self._emit("queue_blocked", blocked[0]) + return False + return False + + # ── 单任务 ────────────────────────────────────────────────────── + def run_task(self, task: Task) -> TaskOutcome: + """跑一个任务(含看门狗、决策打断与重试)。""" + self.clear_log() + self._current = task + with self._lock: + self._decisions_made = [] + task.status = RUNNING + task.started_at = now() + task.finished_at = None + task.exit_code = None + task.last_error = "" + task.summary = "" + self._emit("task_started", task) + + max_attempts = self.runner_cfg.watchdog.max_retries + 1 + outcome = TaskOutcome(task.id, FAILED, None, 0, 0.0) + + for attempt in range(1, max_attempts + 1): + if self.stop.is_set(): + task.status = STOPPED + task.finished_at = now() + break + + task.attempts = attempt + self._save() + + kind, info = self._run_leg(task) + + if kind == "success": + task.status = SUCCESS + task.last_error = "" + task.finished_at = now() + self._emit("task_succeeded", task) + break + + if kind == "timeout": + task.last_error = ( + f"{'总时长' if info == 'total' else '空闲'}超时 " + f"({info}),已终止 agent" + ) + self._emit("task_timeout", task) + elif kind == "stopped": + task.status = STOPPED + task.finished_at = now() + elif kind == "blocked": + task.status = BLOCKED + task.finished_at = now() + else: + task.last_error = task.last_error or info + self._emit("task_error", task) + + # 失败:决定是否重试 + task.finished_at = task.finished_at or now() + if attempt < max_attempts and not self.stop.is_set(): + task.status = RETRYING + self._emit("task_retrying", task) + self._save() + sleep_interruptible(self.runner_cfg.watchdog.backoff_sec, self.stop) + if self.stop.is_set(): + break + task.status = RUNNING + task.started_at = now() + continue + else: + task.status = FAILED if task.status != BLOCKED else BLOCKED + self._emit("task_failed", task) + + if task.status != SUCCESS: + task.status = task.status if task.status != RUNNING else FAILED + task.finished_at = task.finished_at or now() + + outcome = TaskOutcome( + task.id, + task.status, + task.exit_code, + task.attempts, + task.duration_sec or 0.0, + error=task.last_error, + summary=task.summary, + decisions=len(self.decisions_made), + ) + self._save() + self._emit("task_done", task) + self._current = None + self._current_proc = None + return outcome + + # ── 一次 agent 运行(含决策打断与续跑)──────────────────────── + def _run_leg(self, task: Task) -> tuple[str, str]: + """跑一次 agent。返回 (kind, info)。 + + kind ∈ success / failed / timeout / stopped / blocked + """ + session_id = "" + resume_prompt = "" + decision_count = 0 + + while True: + prompt, err = build_prompt( + self.project_root, + self.project_cfg, + task.plan, + task.prompt, + ) + if err: + task.last_error = err + return "failed", err + + made = self.decisions_made + if made: + prompt += "\n已经做出的决策(不要重复询问):\n" + "\n".join( + f"- {q} → {a}" for q, a in made + ) + "\n" + + if resume_prompt: + prompt = resume_prompt + + prompt_file = self.log_dir / f"{task.id}.prompt.md" + prompt_file.parent.mkdir(parents=True, exist_ok=True) + prompt_file.write_text(prompt, encoding="utf-8") + + ok, avail_err = check_agent_available(self.runner_cfg.agent_command) + if not ok: + task.last_error = avail_err + return "failed", avail_err + + command = self._build_command(prompt, session_id) + log_path = self.log_dir / f"{task.id}.log" + task.log_path = str(log_path.relative_to(self.project_root)) + + proc = AgentProcess( + command=command, + cwd=self.project_root / self.runner_cfg.workdir, + env={**self.runner_cfg.agent_env, **self.project_cfg.agent_env}, + on_line=lambda line: self._on_agent_line(task, line), + idle_timeout_sec=self.runner_cfg.watchdog.idle_timeout_sec, + total_timeout_sec=self.runner_cfg.watchdog.total_timeout_sec, + kill_grace_sec=self.runner_cfg.watchdog.kill_grace_sec, + output_format=self.runner_cfg.decision.output_format, + session_pattern=self.runner_cfg.decision.session_pattern, + ) + self._current_proc = proc + + try: + proc.start() + except (OSError, ValueError) as exc: + task.last_error = f"无法启动 agent: {exc}" + return "failed", task.last_error + + result = self._watch(proc, task) + exit_code = proc.wait(timeout=30) + if exit_code is None: + proc.terminate() + exit_code = proc.wait(timeout=10) + + task.exit_code = exit_code + self._write_log(task, log_path) + + # ── agent 抛了问题 ──────────────────────────────────── + if result.kind == "question": + decision_count += 1 + if decision_count > MAX_DECISIONS_PER_TASK: + task.last_error = ( + f"决策次数超过上限({MAX_DECISIONS_PER_TASK} 次),任务中止" + ) + return "failed", task.last_error + + answer, source, waited, sid = self._resolve_question( + task, result.question, result.session_id + ) + self._append_decision(result.question, answer) + self._log(f" ↳ 决策[{source}]: {answer}") + self._emit("decision", task) + + if ( + self.runner_cfg.decision.resume == "session" + and sid + and self.runner_cfg.decision.session_args + ): + # 用同一个 session 续跑,agent 的上下文不丢 + session_id = sid + resume_prompt = build_resume_prompt( + result.question, answer, task.plan + ) + continue + # 拿不到 session(或配置成 restart)→ 重跑整个任务, + # 决策历史会注入新一轮的 prompt + session_id = "" + resume_prompt = "" + continue + + if result.kind == "timeout": + return "timeout", result.timeout_kind + if result.kind == "stopped": + return "stopped", "" + if task.status == BLOCKED: + return "blocked", task.last_error + if exit_code == 0: + return "success", "" + return "failed", f"agent 退出码 {exit_code}" + + def _build_command(self, prompt: str, session_id: str) -> list[str]: + """组装 agent 命令行(含 json 输出格式与 session 续跑参数)。""" + cfg = self.runner_cfg.decision + command = [self.runner_cfg.agent_command, *self.runner_cfg.agent_args] + if cfg.output_format == "json": + command.extend(cfg.json_args) + if session_id: + command.extend(cfg.session_command(session_id)) + command.append(prompt) + return command + + def _write_log(self, task: Task, log_path: Path) -> None: + with self._lock: + log_text = "\n".join(self._current_lines) + try: + log_path.parent.mkdir(parents=True, exist_ok=True) + log_path.write_text(log_text + "\n", encoding="utf-8") + except OSError: + pass + + # ── 看门狗 ────────────────────────────────────────────────────── + def _watch(self, proc: AgentProcess, task: Task) -> WatchResult: + """盯住 agent:空闲超时 / 总时长超时 / agent 抛问题 → 终止。""" + while True: + if self.stop.is_set(): + proc.terminate() + return WatchResult(kind="stopped") + + asked = self._take_question() + if asked is not None: + proc.terminate() + return WatchResult( + kind="question", question=asked[0], session_id=asked[1] + ) + + timed_out, kind = proc.check_timeout() + if timed_out: + proc.terminate() + return WatchResult(kind="timeout", timeout_kind=kind) + + if not proc.alive: + # agent 可能问完就退出了 —— 再查一次标志,别漏掉 + asked = self._take_question() + if asked is not None: + return WatchResult( + kind="question", question=asked[0], session_id=asked[1] + ) + return WatchResult(kind="exited") + + time.sleep(0.1) + + # ── agent 输出处理 ────────────────────────────────────────────── + def _take_question(self) -> tuple[str, str] | None: + with self._lock: + asked = self._ask_question + self._ask_question = None + return asked + + def _on_agent_line(self, task: Task, line: str) -> None: + self._log(line) + kind, value = parse_agent_line(line) + if kind == "decision": + question, answer = value # type: ignore[misc] + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=question, + answer=answer, + source=SOURCE_AGENT, + session_id=self._session_id(), + ) + ) + self._append_decision(question, answer) + self._emit("decision", task) + elif kind == "question": + if should_ask(self.runner_cfg.decision.mode): + # 有人值守:打断 agent,等人来答 + with self._lock: + self._ask_question = (value, self._session_id()) # type: ignore[assignment] + return + # 无人值守:当场按规则/兜底策略决策,agent 继续跑 + answer, rule_id = resolve_answer(self.project_cfg, value) # type: ignore[arg-type] + self.decision_log.record( + DecisionEvent( + task_id=task.id, + question=value, # type: ignore[arg-type] + answer=answer, + source=SOURCE_RULE if rule_id else SOURCE_FALLBACK, + rule_id=rule_id, + session_id=self._session_id(), + ) + ) + self._append_decision(value, answer) # type: ignore[arg-type] + self._log(f" ↳ 默认决策[{rule_id or 'fallback'}]: {answer}") + self._emit("decision", task) + elif kind == "done": + task.summary = value # type: ignore[assignment] + self._emit("task_summary", task) + elif kind == "blocked": + task.last_error = value # type: ignore[assignment] + task.status = BLOCKED + self._emit("task_blocked", task) + + def _session_id(self) -> str: + proc = self._current_proc + return proc.session_id if proc is not None else "" + + # ── 状态持久化 ────────────────────────────────────────────────── + def _save(self) -> None: + try: + save_state(self.paths, self.queue) + except OSError: + pass + + def snapshot(self) -> str: + stats = self.queue.stats() + return ( + f"{fmt_ts(now())} 总 {len(self.queue)} · " + f"待跑 {stats.get(PENDING, 0)} · 运行 {stats.get(RUNNING, 0)} · " + f"成功 {stats.get(SUCCESS, 0)} · 失败 {stats.get(FAILED, 0)}" + ) diff --git a/overnight-runner/overnight_runner/decisions.py b/overnight-runner/overnight_runner/decisions.py new file mode 100644 index 0000000..72b156e --- /dev/null +++ b/overnight-runner/overnight_runner/decisions.py @@ -0,0 +1,174 @@ +"""默认决策:规则匹配 + 决策记录。 + +三种来源: +1. agent 自己按默认决策执行后输出 `DECISION: <问题> → <决策>`,我们解析并记录; +2. agent 抛出一个待决问题(输出 `QUESTION: <问题>`)—— 无人值守时用规则匹配给答案, + 有人值守时先问人(见 controller),答案最终都会回灌给 agent 并记录。 + +记录写在 `/decisions.jsonl`,一行一条,便于后续回溯。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +from .config import DECISION_MODE_ATTENDED, DecisionRule, ProjectConfig +from .util import append_jsonl, now_iso + +DECISION_RE = re.compile(r"^\s*DECISION\s*[::]\s*(.+?)\s*(?:→|->)\s*(.+?)\s*$") +QUESTION_RE = re.compile(r"^\s*QUESTION\s*[::]\s*(.+?)\s*$") +BLOCKED_RE = re.compile(r"^\s*BLOCKED\s*[::]\s*(.+?)\s*$") +DONE_RE = re.compile(r"^\s*DONE\s*[::]\s*(.+?)\s*$") + +# 决策来源 +SOURCE_AGENT = "agent" # agent 自己输出的 DECISION +SOURCE_RULE = "rule" # 命中预设规则 +SOURCE_FALLBACK = "fallback" # 兜底策略(onUnknownDecision) +SOURCE_HUMAN = "human" # 人在 TUI 里回答的 +SOURCE_TIMEOUT = "timeout" # 等待超时后自动兜底的 + + +@dataclass +class DecisionEvent: + task_id: str + question: str + answer: str + source: str = SOURCE_AGENT + rule_id: str = "" + at: str = "" + waited_sec: float | None = None + session_id: str = "" + + def to_record(self) -> dict: + return { + "at": self.at or now_iso(), + "task_id": self.task_id, + "question": self.question, + "answer": self.answer, + "source": self.source, + "rule_id": self.rule_id, + "waited_sec": round(self.waited_sec, 1) if self.waited_sec is not None else 0.0, + "session_id": self.session_id, + } + + +class DecisionLog: + """决策记录:JSONL 追加写 + 内存缓存。""" + + def __init__(self, path: Path) -> None: + self.path = path + self._records: list[dict] = [] + + def load(self) -> list[dict]: + import json + + if not self.path.exists(): + self._records = [] + return self._records + out = [] + for line in self.path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + try: + out.append(json.loads(line)) + except json.JSONDecodeError: + continue + self._records = out + return out + + def record(self, event: DecisionEvent) -> dict: + rec = event.to_record() + append_jsonl(self.path, rec) + self._records.append(rec) + return rec + + @property + def records(self) -> list[dict]: + return list(self._records) + + def for_task(self, task_id: str) -> list[dict]: + return [r for r in self._records if r.get("task_id") == task_id] + + +def match_rule(rules: list[DecisionRule], question: str) -> DecisionRule | None: + """用关键词/正则匹配一条默认决策。""" + q = question.strip() + for rule in rules: + if not rule.enabled: + continue + if rule.question and (rule.question.strip() == q or rule.question.strip() in q): + return rule + if rule.match: + try: + if re.search(rule.match, q): + return rule + except re.error: + if rule.match.lower() in q.lower(): + return rule + return None + + +def parse_agent_line(line: str) -> tuple[str, str]: + """解析 agent 的一行输出。 + + 返回 (kind, value),kind ∈ decision / question / blocked / done / ''。 + """ + m = DECISION_RE.match(line) + if m: + return "decision", (m.group(1).strip(), m.group(2).strip()) # type: ignore[return-value] + m = QUESTION_RE.match(line) + if m: + return "question", m.group(1).strip() # type: ignore[return-value] + m = BLOCKED_RE.match(line) + if m: + return "blocked", m.group(1).strip() # type: ignore[return-value] + m = DONE_RE.match(line) + if m: + return "done", m.group(1).strip() # type: ignore[return-value] + return "", "" + + +def resolve_answer(project_cfg: ProjectConfig, question: str) -> tuple[str, str]: + """算出(答案, rule_id)—— **纯函数,不写日志**。 + + 命中规则就用规则答案,否则用项目的兜底策略。 + """ + rule = match_rule(project_cfg.decisions, question) + if rule is not None: + return (rule.answer or project_cfg.on_unknown_decision), rule.id + return project_cfg.on_unknown_decision, "" + + +def should_ask(mode: str) -> bool: + """该模式下要不要问人。 + + - `attended`(有人值守):要问 + - `unattended`(无人值守):不问 + """ + return mode == DECISION_MODE_ATTENDED + + +def decide( + project_cfg: ProjectConfig, + log: DecisionLog, + task_id: str, + question: str, +) -> tuple[str, str]: + """给 agent 抛出的问题一个默认答案(无人值守路径)。 + + 返回 (answer, rule_id)。命中规则就用规则答案,否则用项目的兜底策略。 + """ + answer, rule_id = resolve_answer(project_cfg, question) + log.record( + DecisionEvent( + task_id=task_id, + question=question, + answer=answer, + source=SOURCE_RULE if rule_id else SOURCE_FALLBACK, + rule_id=rule_id, + ) + ) + return answer, rule_id diff --git a/overnight-runner/overnight_runner/keys.py b/overnight-runner/overnight_runner/keys.py new file mode 100644 index 0000000..7442877 --- /dev/null +++ b/overnight-runner/overnight_runner/keys.py @@ -0,0 +1,329 @@ +"""跨平台按键读取:POSIX 用 termios,Windows 用 msvcrt。 + +只依赖标准库,不需要 prompt_toolkit 之类的重依赖。 +""" + +from __future__ import annotations + +import os +import sys +import threading +from typing import Callable + +from .util import is_windows + +# 规范化按键名 +UP = "up" +DOWN = "down" +LEFT = "left" +RIGHT = "right" +ENTER = "enter" +ESC = "esc" +BACKSPACE = "backspace" +TAB = "tab" +CTRL_C = "ctrl-c" +NONE = "" + +KEYBOARD_HELP = ( + "↑↓ 选择 a 追加 plan r 重试 p 暂停/恢复 d 移除 " + "Enter 查看日志 Esc 返回 c 清屏 q 退出" +) + +DECISION_HELP = ( + "待决策时: Enter 提交答案 · Esc 用默认决策 · Ctrl-C 退出" +) + +_WIN_SPECIAL = { + "H": UP, + "P": DOWN, + "K": LEFT, + "M": RIGHT, + "G": ENTER, + "S": LEFT, + "R": RIGHT, + "\x0d": ENTER, + "\x1b": ESC, + "\x08": BACKSPACE, + "\x09": TAB, +} + +# 按下 ESC 后等这么久还等不到后续字节,就认为用户是单独按了 ESC +ESC_TIMEOUT = 0.05 +# 轮询间隔(秒):让读线程能及时响应 stop() +POLL_INTERVAL = 0.2 + + +class RawMode: + """进入原始模式(按键立即返回,不回显),退出时恢复。""" + + def __init__(self) -> None: + self._fd = None + self._old = None + self._active = False + + def __enter__(self) -> "RawMode": + if is_windows(): + self._active = True + return self + try: + import termios + import tty + + self._fd = sys.stdin.fileno() + self._old = termios.tcgetattr(self._fd) + tty.setraw(self._fd) + self._active = True + except Exception: # noqa: BLE001 - 没有 tty 时降级为行模式 + self._active = False + return self + + def __exit__(self, *exc) -> None: + if not self._active or self._fd is None or self._old is None: + return + try: + import termios + + termios.tcsetattr(self._fd, termios.TCSADRAIN, self._old) + except Exception: # noqa: BLE001 + pass + + +def _utf8_seq_len(lead: int) -> int: + """按 UTF-8 首字节判断这个字符总共占几个字节。 + + 汉字 3 字节、emoji 4 字节。读键盘必须 **按字节凑齐再解**, + 否则一个汉字会被拆成 3 次读、每次都解码失败 → 中文全变问号。 + """ + if lead < 0x80: + return 1 + if lead >= 0xF0: + return 4 + if lead >= 0xE0: + return 3 + if lead >= 0xC0: + return 2 + return 1 # 非法首字节(续字节开头)—— 当 1 字节处理,别死循环 + + +def _normalize_key(ch: str) -> str: + """把一个字符归一成按键名(控制键给名字,其余原样返回)。""" + if ch in ("\r", "\n"): + return ENTER + if ch in ("\x7f", "\x08"): + return BACKSPACE + if ch == "\x03": + return CTRL_C + if ch == "\t": + return TAB + return ch + + +_CSI_KEYS = { + "[A": UP, + "[B": DOWN, + "[C": RIGHT, + "[D": LEFT, + "[H": UP, + "[F": DOWN, +} + + +class PosixKeyReader: + """POSIX 下的按键读取:懂 UTF-8 多字节字符,也懂 ESC 序列。 + + 为什么不用"一次 os.read(fd, 1)":那样会把一个汉字的 3 个字节 + 拆成 3 次读,每次 `decode(errors="replace")` 都失败 → 中文全变问号 + (实测:决策窗口里输入"先修 Bug",落盘变成"??? Bug")。 + + 做法:字节先进缓冲区,按 UTF-8 首字节凑齐长度再整体解码。 + """ + + def __init__(self) -> None: + self._buf = bytearray() + self._eof = False + + # ── 字节层 ────────────────────────────────────────────────────── + def _pump(self, fd: int, timeout: float | None) -> bool: + """把 fd 里的可用字节读进缓冲区。返回是否读到东西。""" + import select + + try: + ready, _, _ = select.select([fd], [], [], timeout) + except (OSError, ValueError): + return False + if not ready: + return False + try: + data = os.read(fd, 1024) + except OSError: + return False + if not data: + self._eof = True + return False + self._buf.extend(data) + return True + + def _take_char(self) -> str | None: + """从缓冲区头部取一个完整字符;字节还不够返回 None。""" + if not self._buf: + return None + need = _utf8_seq_len(self._buf[0]) + if len(self._buf) < need: + return None + raw = bytes(self._buf[:need]) + del self._buf[:need] + return raw.decode("utf-8", errors="replace") + + def _find_csi_final(self) -> int | None: + """在缓冲区里找 CSI 序列的结束字节下标。 + + 缓冲区形如 b"[A" / b"[1;5C"(下标 0 是 '[')。 + 返回 None 表示"还没收全";返回 -1 表示"非法序列"。 + """ + for i in range(1, len(self._buf)): + b = self._buf[i] + if 0x40 <= b <= 0x7E: + return i + if not (0x20 <= b <= 0x3F): + return -1 + return None + + # ── ESC 序列 ──────────────────────────────────────────────────── + def _read_escape(self, fd: int) -> str: + """已经读到 ESC,判断它是单独按键还是某个序列的开头。""" + if not self._buf: + self._pump(fd, ESC_TIMEOUT) + if not self._buf or self._buf[0] != 0x5B: # '[' + return ESC # 后面的字节留给下一次读 + while True: + idx = self._find_csi_final() + if idx is not None and idx >= 0: + seq = bytes(self._buf[: idx + 1]) + del self._buf[: idx + 1] + return _CSI_KEYS.get(seq.decode("ascii", errors="replace"), NONE) + if idx == -1: # 非法序列,丢掉 ESC[ 别把后面的正文吃掉 + del self._buf[:1] + return NONE + if not self._pump(fd, ESC_TIMEOUT): + del self._buf[:1] + return NONE + + # ── 对外 ──────────────────────────────────────────────────────── + def read_key(self, fd: int) -> str: + """读一个按键(控制键给名字,其余返回原字符)。 + + 返回 NONE 表示"暂时没读到"(超时或输入流结束)。 + """ + while True: + ch = self._take_char() + if ch is None: + if self._eof: + return NONE + self._pump(fd, POLL_INTERVAL) + continue + if ch == "\x1b": + return self._read_escape(fd) + return _normalize_key(ch) + + +_POSIX_READER = PosixKeyReader() + + +def _read_posix_key(fd: int) -> str: + """读一个按键(POSIX)。保留函数形式,内部共用一个带缓冲的读取器。""" + return _POSIX_READER.read_key(fd) + + +def _read_win_key() -> str: + import msvcrt + + ch = msvcrt.getwch() + if ch in ("\x00", "\xe0"): + ch2 = msvcrt.getwch() + return _WIN_SPECIAL.get(ch2, NONE) + if ch in ("\r", "\n"): + return ENTER + if ch in ("\x7f", "\x08"): + return BACKSPACE + if ch == "\x03": + return CTRL_C + if ch == "\t": + return TAB + return ch + + +class KeyReader: + """后台线程读按键,交给回调。""" + + def __init__(self, on_key: Callable[[str], None]) -> None: + self.on_key = on_key + self._thread: threading.Thread | None = None + self._stop = threading.Event() + self._raw = RawMode() + self._posix = PosixKeyReader() + + def start(self) -> None: + self._raw.__enter__() + self._thread = threading.Thread(target=self._loop, name="key-reader", daemon=True) + self._thread.start() + + def stop(self) -> None: + self._stop.set() + self._raw.__exit__() + + def _loop(self) -> None: + while not self._stop.is_set(): + try: + if is_windows(): + key = _read_win_key() + else: + fd = sys.stdin.fileno() + key = self._posix.read_key(fd) + except Exception: # noqa: BLE001 + break + if key == NONE: + continue + try: + self.on_key(key) + except Exception: # noqa: BLE001 + pass + if key == CTRL_C: + break + + +def read_line(prompt: str = "") -> str: + """行模式读一行(用于非 TUI 场景)。""" + if prompt: + print(prompt, end="", flush=True) + try: + return sys.stdin.readline().strip() + except (EOFError, KeyboardInterrupt): + return "" + + +def confirm(prompt: str, default: bool = False) -> bool: + suffix = "[Y/n]" if default else "[y/N]" + ans = read_line(f"{prompt} {suffix} ").lower() + if not ans: + return default + return ans in ("y", "yes") + + +__all__ = [ + "BACKSPACE", + "CTRL_C", + "DOWN", + "ENTER", + "ESC", + "KEYBOARD_HELP", + "KeyReader", + "LEFT", + "NONE", + "PosixKeyReader", + "RawMode", + "RIGHT", + "TAB", + "UP", + "confirm", + "read_line", +] diff --git a/overnight-runner/overnight_runner/prompts.py b/overnight-runner/overnight_runner/prompts.py new file mode 100644 index 0000000..45fd918 --- /dev/null +++ b/overnight-runner/overnight_runner/prompts.py @@ -0,0 +1,66 @@ +"""提示词组装:把项目默认提示词 + 默认决策 + plan 内容拼成给 agent 的一次性提示。""" + +from __future__ import annotations + +from pathlib import Path + +from .config import ProjectConfig + +PLAN_PLACEHOLDER = "{{PLAN}}" +DECISIONS_PLACEHOLDER = "{{DECISIONS}}" + + +def read_plan(project_root: Path, plan_rel: str) -> tuple[str, str]: + """读 plan 文件,返回 (内容, 错误信息)。""" + path = project_root / plan_rel + if not path.exists(): + return "", f"plan 文件不存在: {plan_rel}" + try: + text = path.read_text(encoding="utf-8") + except OSError as exc: + return "", f"plan 文件读取失败: {plan_rel} ({exc})" + if not text.strip(): + return "", f"plan 文件为空: {plan_rel}" + return text, "" + + +def build_prompt( + project_root: Path, + project_cfg: ProjectConfig, + plan_rel: str, + task_prompt: str = "", +) -> tuple[str, str]: + """返回 (最终提示词, 错误信息)。""" + plan_text, err = read_plan(project_root, plan_rel) + if err: + return "", err + + decisions = project_cfg.decision_text() or "(无预设决策,遇到需决策的问题请选择最安全、可回滚的方案)" + + template = project_cfg.default_prompt or "" + if PLAN_PLACEHOLDER in template: + prompt = template.replace(PLAN_PLACEHOLDER, plan_text) + else: + prompt = f"{template}\n\n{plan_text}" + + if DECISIONS_PLACEHOLDER in prompt: + prompt = prompt.replace(DECISIONS_PLACEHOLDER, decisions) + elif decisions: + prompt = f"{prompt}\n\n默认决策:\n{decisions}" + + prompt += f"\n\n---\n本次任务:{plan_rel}\n" + + if task_prompt: + prompt += f"补充要求:\n{task_prompt}\n" + + return prompt, "" + + +def build_resume_prompt(question: str, answer: str, plan_rel: str) -> str: + """续跑时的提示词:把人的决策送回给同一个 session 的 agent。""" + return ( + f"针对你刚才提出的问题:{question}\n\n" + f"决策如下:{answer}\n\n" + f"请基于这个决策继续完成原任务(计划:{plan_rel})。" + "不要重复已经完成的步骤,只做剩下的部分。" + ) diff --git a/overnight-runner/overnight_runner/queue.py b/overnight-runner/overnight_runner/queue.py new file mode 100644 index 0000000..3357ac6 --- /dev/null +++ b/overnight-runner/overnight_runner/queue.py @@ -0,0 +1,320 @@ +"""任务队列:加载 / 追加 / 状态跟踪。 + +队列定义在 `.overnight-runner/queue//queue.yaml`(可提交进仓库), +运行时状态放在同目录的 `state.json`(不提交)。 + +每条队列一个独立目录 —— 多人可以在同一个项目里各跑各的队列,互不干扰。 +""" + +from __future__ import annotations + +import json +import re +import threading +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +from typing import Any + +from . import yaml_lite as yaml +from .config import QueuePaths +from .util import atomic_write, now, now_iso, slugify, today_stamp + +# 任务状态 +PENDING = "pending" +RUNNING = "running" +RETRYING = "retrying" +SUCCESS = "success" +FAILED = "failed" +STOPPED = "stopped" +BLOCKED = "blocked" + +STATUSES = (PENDING, RUNNING, RETRYING, SUCCESS, FAILED, STOPPED, BLOCKED) + +# plan 文件名常带日期前缀(YYYYMMDD-xxx / YYYY-MM-DD-xxx),别再拼一遍 +DATE_PREFIX_RE = re.compile(r"^\d{4}-?\d{2}-?\d{2}[-_]") + + + +@dataclass +class Task: + id: str + plan: str + prompt: str = "" + priority: int = 100 + enabled: bool = True + role: str = "" # BA / DEV / QA —— 只是标签,用于分组显示 + depends_on: list[str] = field(default_factory=list) + + # 运行时状态 + status: str = PENDING + attempts: int = 0 + started_at: datetime | None = None + finished_at: datetime | None = None + exit_code: int | None = None + last_error: str = "" + summary: str = "" + log_path: str = "" + + @property + def plan_path(self) -> Path: + return Path(self.plan) + + @property + def duration_sec(self) -> float | None: + if self.started_at is None: + return None + end = self.finished_at or now() + # 状态文件是手改过的,可能写了不带时区的时间 —— 别让渲染循环炸掉 + if end.tzinfo is None and self.started_at.tzinfo is not None: + end = end.replace(tzinfo=self.started_at.tzinfo) + elif end.tzinfo is not None and self.started_at.tzinfo is None: + self.started_at = self.started_at.replace(tzinfo=end.tzinfo) + return (end - self.started_at).total_seconds() + + def to_def(self) -> dict: + """写回 YAML 的定义部分。""" + data: dict[str, Any] = {"id": self.id, "plan": self.plan} + if self.prompt: + data["prompt"] = self.prompt + if self.priority != 100: + data["priority"] = self.priority + if self.role: + data["role"] = self.role + if self.depends_on: + data["depends_on"] = self.depends_on + if not self.enabled: + data["enabled"] = False + return data + + def to_state(self) -> dict: + return { + "id": self.id, + "plan": self.plan, + "status": self.status, + "attempts": self.attempts, + "started_at": self.started_at.isoformat(timespec="seconds") if self.started_at else None, + "finished_at": self.finished_at.isoformat(timespec="seconds") if self.finished_at else None, + "exit_code": self.exit_code, + "last_error": self.last_error, + "summary": self.summary, + "log_path": self.log_path, + } + + +class Queue: + """线程安全的任务队列。""" + + def __init__(self, tasks: list[Task] | None = None) -> None: + self._tasks: list[Task] = tasks or [] + self._lock = threading.RLock() + + # ── 基本访问 ──────────────────────────────────────────────────── + @property + def tasks(self) -> list[Task]: + with self._lock: + return list(self._tasks) + + def get(self, task_id: str) -> Task | None: + with self._lock: + for t in self._tasks: + if t.id == task_id: + return t + return None + + def __len__(self) -> int: + with self._lock: + return len(self._tasks) + + # ── 变更 ──────────────────────────────────────────────────────── + def add(self, task: Task) -> Task: + with self._lock: + if self.get(task.id) is not None: + raise ValueError(f"任务 id 已存在: {task.id}") + self._tasks.append(task) + self._tasks.sort(key=lambda t: (t.priority, t.id)) + return task + + def remove(self, task_id: str) -> bool: + with self._lock: + before = len(self._tasks) + self._tasks = [t for t in self._tasks if t.id != task_id] + return len(self._tasks) != before + + def update(self, task_id: str, **fields) -> Task | None: + with self._lock: + task = self.get(task_id) + if task is None: + return None + for key, value in fields.items(): + setattr(task, key, value) + return task + + # ── 调度 ──────────────────────────────────────────────────────── + def next_ready(self) -> Task | None: + """下一个可以跑的任务:enabled + pending + 依赖已完成 + 优先级最高。""" + with self._lock: + done = {t.id for t in self._tasks if t.status == SUCCESS} + candidates = [ + t + for t in self._tasks + if t.enabled and t.status == PENDING and all(d in done for d in t.depends_on) + ] + if not candidates: + return None + candidates.sort(key=lambda t: (t.priority, t.id)) + return candidates[0] + + def pending_count(self) -> int: + with self._lock: + return sum(1 for t in self._tasks if t.status in (PENDING, RUNNING, RETRYING)) + + def has_unfinished(self) -> bool: + with self._lock: + return any(t.status in (PENDING, RUNNING, RETRYING) for t in self._tasks) + + def stats(self) -> dict[str, int]: + with self._lock: + out = {s: 0 for s in STATUSES} + for t in self._tasks: + out[t.status] = out.get(t.status, 0) + 1 + return out + + +def build_task( + project_root: Path, + plan: str, + prompt: str = "", + role: str = "", + priority: int = 100, + task_id: str | None = None, + existing_ids: set[str] | None = None, +) -> Task: + """由 plan 路径构造任务;plan 相对项目根目录。 + + id 默认取 plan 文件名(去掉日期前缀)—— 同一个 plan 可以在同一天被排多次, + 冲突时自动加 `-2` / `-3` 序号。 + """ + plan_rel = _normalize_rel(project_root, plan) + if task_id is None: + # plan 文件名通常已经带日期前缀(20261106-xxx),别再拼一遍变成双日期 + stem = DATE_PREFIX_RE.sub("", Path(plan_rel).stem) + base = slugify(stem, fallback="task") + task_id = f"{today_stamp()}-{base}" + taken = existing_ids or set() + if task_id in taken: + n = 2 + while f"{task_id}-{n}" in taken: + n += 1 + task_id = f"{task_id}-{n}" + return Task( + id=task_id, + plan=plan_rel, + prompt=prompt, + role=role, + priority=priority, + ) + + +def _normalize_rel(project_root: Path, plan: str) -> str: + """把 plan 路径规范成相对项目根的 POSIX 风格路径。""" + p = Path(plan) + if p.is_absolute(): + try: + p = p.resolve().relative_to(project_root.resolve()) + except ValueError: + return p.as_posix() + return p.as_posix() + + +def task_from_def(defs: dict, index: int = 0) -> Task: + plan = defs.get("plan") or "" + task_id = defs.get("id") or f"task-{index + 1}" + return Task( + id=str(task_id), + plan=plan, + prompt=defs.get("prompt") or "", + priority=int(defs.get("priority", 100)), + enabled=bool(defs.get("enabled", True)), + role=defs.get("role") or "", + depends_on=list(defs.get("depends_on") or []), + ) + + +def load_queue(paths: QueuePaths, queue_defs: list[dict]) -> Queue: + """把 YAML 定义与运行时状态合并成队列。""" + tasks = [task_from_def(d, i) for i, d in enumerate(queue_defs)] + queue = Queue(tasks) + + for st in _read_states(paths): + task = queue.get(st.get("id", "")) + if task is None: + # 兼容老 id(如 20261106-20261106-xxx)—— 退化成按 plan 路径匹配 + task = next( + (t for t in queue.tasks if t.plan == st.get("plan", "")), None + ) + if task is None: + continue + task.status = st.get("status", PENDING) + task.attempts = int(st.get("attempts", 0)) + task.exit_code = st.get("exit_code") + task.last_error = st.get("last_error", "") + task.summary = st.get("summary", "") + task.log_path = st.get("log_path", "") + started = st.get("started_at") + finished = st.get("finished_at") + task.started_at = datetime.fromisoformat(started) if started else None + task.finished_at = datetime.fromisoformat(finished) if finished else None + return queue + + +def _read_states(paths: QueuePaths) -> list[dict]: + """读运行时状态。 + + `state.json` 缺失或损坏时回落到 `state.json.bak` —— 避免误删状态文件 + 就把已经跑完的任务全部重新排队。 + """ + for path in (paths.state, paths.state.with_name(paths.state.name + ".bak")): + if not path.exists(): + continue + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + continue + if isinstance(data, dict): + return list(data.get("tasks") or []) + return [] + + +def save_state(paths: QueuePaths, queue: Queue) -> Path: + """写运行时状态(同时留一份 .bak 兜底)。""" + payload = { + "updated_at": now_iso(), + "tasks": [t.to_state() for t in queue.tasks], + } + text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n" + atomic_write(paths.state, text) + try: + atomic_write(paths.state.with_name(paths.state.name + ".bak"), text) + except OSError: + pass + return paths.state + + +def load_queue_defs(paths: QueuePaths) -> list[dict]: + """读队列定义(`.overnight-runner/queue//queue.yaml`)。""" + if not paths.config.exists(): + return [] + try: + data = yaml.loads(paths.config.read_text(encoding="utf-8")) or {} + except (OSError, ValueError): + return [] + return list(data.get("queue") or []) + + +def save_queue_defs(paths: QueuePaths, queue: Queue) -> Path: + """把队列定义写回 `queue.yaml`(追加 plan 用)。""" + paths.dir.mkdir(parents=True, exist_ok=True) + payload = {"queue": [t.to_def() for t in queue.tasks]} + atomic_write(paths.config, yaml.dumps(payload)) + return paths.config diff --git a/overnight-runner/overnight_runner/term.py b/overnight-runner/overnight_runner/term.py new file mode 100644 index 0000000..50a766d --- /dev/null +++ b/overnight-runner/overnight_runner/term.py @@ -0,0 +1,279 @@ +"""纯 ANSI 终端绘制 —— 零第三方依赖。 + +只依赖标准库。用 ANSI 转义序列直接画: + +- 备用屏幕(全屏面板) +- 光标定位 / 隐藏 +- 颜色(SGR) +- 边框(圆角 / 直角) +- 中日韩宽字符的显示宽度计算 + +没有 TTY 时(管道 / CI)会自动降级:不做任何转义,只输出纯文本。 +""" + +from __future__ import annotations + +import os +import shutil +import sys +import unicodedata +from typing import Iterable + +# ── 转义序列 ──────────────────────────────────────────────────────── +ESC = "\x1b" +CSI = ESC + "[" + +ALT_SCREEN_ON = CSI + "?1049h" +ALT_SCREEN_OFF = CSI + "?1049l" +CURSOR_HIDE = CSI + "?25l" +CURSOR_SHOW = CSI + "?25h" +CLEAR = CSI + "2J" +CURSOR_HOME = CSI + "H" +RESET = CSI + "0m" + + +def _sgr(*codes: int | str) -> str: + return CSI + ";".join(str(c) for c in codes) + "m" + + +class Style: + """语义色。""" + + RESET = _sgr(0) + BOLD = _sgr(1) + DIM = _sgr(2) + ITALIC = _sgr(3) + REVERSE = _sgr(7) + + BLACK = _sgr(30) + RED = _sgr(31) + GREEN = _sgr(32) + YELLOW = _sgr(33) + BLUE = _sgr(34) + MAGENTA = _sgr(35) + CYAN = _sgr(36) + WHITE = _sgr(37) + GREY = _sgr(90) + + BRIGHT_RED = _sgr(91) + BRIGHT_GREEN = _sgr(92) + BRIGHT_YELLOW = _sgr(93) + BRIGHT_BLUE = _sgr(94) + BRIGHT_MAGENTA = _sgr(95) + BRIGHT_CYAN = _sgr(96) + BRIGHT_WHITE = _sgr(97) + + +# ── 显示宽度 ──────────────────────────────────────────────────────── +import re + +_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]") + + +def char_width(ch: str) -> int: + """字符的显示宽度(0 / 1 / 2)。""" + if ch == "\t": + return 4 + if unicodedata.combining(ch): + return 0 + if unicodedata.east_asian_width(ch) in ("W", "F"): + return 2 + return 1 + + +def _tokens(text: str) -> list[tuple[str, int]]: + """把文本切成 (片段, 显示宽度) 序列。 + + ANSI 转义序列宽度算 0 —— 否则带颜色的文本会被算宽。 + """ + out: list[tuple[str, int]] = [] + i = 0 + while i < len(text): + if text[i] == "\x1b": + m = _ANSI_RE.match(text, i) + if m: + out.append((m.group(0), 0)) + i = m.end() + continue + out.append((text[i], char_width(text[i]))) + i += 1 + return out + + +def dwidth(text: str) -> int: + """字符串的显示宽度(忽略 ANSI 转义序列)。""" + return sum(w for _, w in _tokens(text)) + + +def truncate(text: str, width: int, ellipsis: str = "…") -> str: + """按显示宽度截断(不切断 ANSI 序列)。""" + if width <= 0: + return "" + if dwidth(text) <= width: + return text + limit = width - dwidth(ellipsis) + out: list[str] = [] + used = 0 + for tok, w in _tokens(text): + if used + w > limit: + break + out.append(tok) + used += w + return "".join(out) + ellipsis + Style.RESET + + +def pad(text: str, width: int, align: str = "left") -> str: + """按显示宽度补齐(忽略 ANSI 转义序列)。""" + w = dwidth(text) + if w >= width: + return text + space = " " * (width - w) + if align == "right": + return space + text + if align == "center": + left = (width - w) // 2 + return " " * left + text + " " * (width - w - left) + return text + space + + +def wrap(text: str, width: int) -> list[str]: + """按显示宽度折行(不打断宽字符,不切断 ANSI 序列)。""" + if width <= 0: + return [""] + lines: list[str] = [] + for raw in text.split("\n"): + if dwidth(raw) <= width: + lines.append(raw) + continue + cur: list[str] = [] + used = 0 + for tok, w in _tokens(raw): + if used + w > width and cur: + lines.append("".join(cur)) + cur = [] + used = 0 + cur.append(tok) + used += w + lines.append("".join(cur)) + return lines or [""] + + +# ── 边框字符 ──────────────────────────────────────────────────────── +class Box: + ROUND = "┌┐└┘─│├┤┬┴┼" + SQUARE = "┌┐└┘─│├┤┬┴┼" + ASCII = "+-++|+++++" + + +class Term: + """终端绘制器。""" + + def __init__(self, stream=None) -> None: + self.out = stream or sys.stdout + self.tty = bool(getattr(self.out, "isatty", lambda: False)()) + self._alt = False + + # ── 尺寸 ──────────────────────────────────────────────────────── + def size(self) -> tuple[int, int]: + try: + size = shutil.get_terminal_size(fallback=(120, 40)) + return max(40, size.columns), max(10, size.lines) + except OSError: + return 120, 40 + + # ── 基础输出 ──────────────────────────────────────────────────── + def write(self, text: str) -> None: + try: + self.out.write(text) + except (OSError, ValueError): + pass + + def flush(self) -> None: + try: + self.out.flush() + except (OSError, ValueError): + pass + + def enter(self) -> None: + """进备用屏幕 + 隐藏光标。""" + if not self.tty: + return + self.write(ALT_SCREEN_ON + CURSOR_HIDE + CLEAR + CURSOR_HOME) + self._alt = True + self.flush() + + def leave(self) -> None: + """退出备用屏幕 + 恢复光标。""" + if not self.tty: + self.flush() + return + self.write(CURSOR_SHOW + ALT_SCREEN_OFF) + self._alt = False + self.flush() + + def clear(self) -> None: + if self.tty: + self.write(CLEAR + CURSOR_HOME) + + def move(self, row: int, col: int) -> None: + """移动光标(1-based)。""" + if self.tty: + self.write(f"{CSI}{row};{col}H") + + def style(self, code: str, text: str) -> str: + if not self.tty or not code: + return text + return f"{code}{text}{Style.RESET}" + + # ── 画框 ──────────────────────────────────────────────────────── + def draw_box( + self, + x: int, + y: int, + w: int, + h: int, + title: str = "", + lines: Iterable[str] = (), + border: str = Style.CYAN, + title_style: str = Style.BOLD, + footer: str = "", + ) -> None: + """在 (x, y) 处画一个 w×h 的框,内容放 lines。""" + if w < 4 or h < 3: + return + b = Box.ROUND + tl, tr, bl, br, hz, vt = b[0], b[1], b[2], b[3], b[4], b[5] + + # 上边框(带标题) + self.move(y, x) + if title: + label = " " + truncate(title, max(0, w - 6)) + " " + self.write(self.style(border, tl)) + self.write(self.style(title_style, label)) + self.write(self.style(border, hz * max(0, w - 2 - dwidth(label)) + tr)) + else: + self.write(self.style(border, tl + hz * (w - 2) + tr)) + + # 内容 + body = list(lines) + for i in range(h - 2): + content = body[i] if i < len(body) else "" + self.move(y + 1 + i, x) + self.write(self.style(border, vt)) + self.write(pad(truncate(content, w - 2), w - 2)) + self.write(self.style(border, vt)) + + # 下边框(带 footer) + self.move(y + h - 1, x) + if footer: + label = " " + truncate(footer, max(0, w - 6)) + " " + self.write(self.style(border, bl)) + self.write(self.style(Style.DIM, label)) + self.write(self.style(border, hz * max(0, w - 2 - dwidth(label)) + br)) + else: + self.write(self.style(border, bl + hz * (w - 2) + br)) + + def draw_line(self, x: int, y: int, text: str, style: str = "") -> None: + """在 (x, y) 处写一行(1-based 坐标)。""" + self.move(y, x) + self.write(self.style(style, text)) diff --git a/overnight-runner/overnight_runner/ui.py b/overnight-runner/overnight_runner/ui.py new file mode 100644 index 0000000..c129aed --- /dev/null +++ b/overnight-runner/overnight_runner/ui.py @@ -0,0 +1,460 @@ +"""分屏面板:左边任务队列,右边 coding agent 输出。 + +零第三方依赖 —— 用 ANSI 转义序列直接画(见 term.py)。 +""" + +from __future__ import annotations + +import threading +import time +from pathlib import Path +from typing import Callable + +from .config import QueuePaths, RunnerConfig +from .controller import RunnerController +from .keys import ( + BACKSPACE, + CTRL_C, + DECISION_HELP, + DOWN, + ENTER, + ESC, + KEYBOARD_HELP, + UP, +) +from .queue import BLOCKED, FAILED, PENDING, RETRYING, RUNNING, SUCCESS, STOPPED, Queue, Task +from .term import Style, Term, dwidth, pad, truncate, wrap + +STATUS_STYLE = { + PENDING: Style.DIM, + RUNNING: Style.BRIGHT_CYAN, + RETRYING: Style.BRIGHT_YELLOW, + SUCCESS: Style.BRIGHT_GREEN, + FAILED: Style.BRIGHT_RED, + BLOCKED: Style.BRIGHT_MAGENTA, + STOPPED: Style.GREY, +} + +STATUS_LABEL = { + PENDING: "待跑", + RUNNING: "运行中", + RETRYING: "待重试", + SUCCESS: "成功", + FAILED: "失败", + BLOCKED: "阻塞", + STOPPED: "已停", +} + +LEFT_WIDTH = 46 +FOOTER_HEIGHT = 3 + + +class RunnerUI: + """overnight-runner 的分屏界面。""" + + def __init__( + self, + controller: RunnerController, + queue: Queue, + runner_cfg: RunnerConfig, + project_root: Path, + paths: QueuePaths | None = None, + ) -> None: + self.controller = controller + self.queue = queue + self.cfg = runner_cfg + self.project_root = project_root + self.paths = paths + + self.term = Term() + self.selected = 0 + self.detail_task_id: str | None = None + self.message = "" + self.message_level = "info" + self._quit = threading.Event() + self._input: dict | None = None # {"prompt": str, "buffer": str} + self._log_lines: list[str] = [] + self._log_lock = threading.Lock() + + # 决策窗口:人正在回答 agent 的问题 + self._decision_buffer: str | None = None + self._decision_lock = threading.Lock() + + controller.on_log = self._on_log + controller.on_event = self._on_event + + # ── 回调 ──────────────────────────────────────────────────────── + def _on_log(self, line: str) -> None: + with self._log_lock: + self._log_lines.append(line) + if len(self._log_lines) > 4000: + self._log_lines = self._log_lines[-2000:] + + def _on_event(self, kind: str, task: Task | None) -> None: + labels = { + "task_started": f"▶ 开始 {task.id if task else ''}", + "task_succeeded": f"✔ 成功 {task.id if task else ''}", + "task_failed": f"✘ 失败 {task.id if task else ''}", + "task_timeout": f"⏱ 超时 {task.id if task else ''}", + "task_retrying": f"↻ 重试 {task.id if task else ''}", + "task_blocked": f"⛔ 阻塞 {task.id if task else ''}", + "task_done": f"— 结束 {task.id if task else ''}", + "decision": f"◆ 决策已记录 {task.id if task else ''}", + "retry_wait": f"⏳ 等待重试 {task.id if task else ''}", + "runner_started": "启动 overnight-runner", + "runner_stopped": "overnight-runner 已停止", + } + text = labels.get(kind) + if text: + self._set_message(text, "warn" if kind.endswith(("failed", "timeout", "blocked")) else "info") + + def _set_message(self, text: str, level: str = "info") -> None: + self.message = text + self.message_level = level + + # ── 交互 ──────────────────────────────────────────────────────── + def handle_key(self, key: str) -> None: + # 决策窗口优先级最高 —— 它在阻塞 agent,等不起 + if self.controller.pending_question() is not None: + self._handle_decision_key(key) + return + + if self._input is not None: + self._handle_input_key(key) + return + + if key == CTRL_C or key == "q": + self._quit.set() + self.controller.stop.set() + elif key == UP: + self.selected = max(0, self.selected - 1) + elif key == DOWN: + self.selected = min(max(0, len(self.queue) - 1), self.selected + 1) + elif key == "a": + self._input = {"prompt": "追加 plan 路径:", "buffer": ""} + elif key == "r": + self._retry_selected() + elif key == "p": + self._toggle_pause() + elif key == "d": + self._delete_selected() + elif key == ENTER: + task = self._selected_task() + if task is not None: + self.detail_task_id = task.id + elif key == ESC: + self.detail_task_id = None + elif key == "c": + self.controller.clear_log() + with self._log_lock: + self._log_lines = [] + + def _handle_decision_key(self, key: str) -> None: + """决策窗口的按键处理。""" + with self._decision_lock: + if self._decision_buffer is None: + self._decision_buffer = "" + buffer = self._decision_buffer + + if key == CTRL_C: + self._decision_buffer = None + self._quit.set() + self.controller.stop.set() + return + if key == ESC: + self._decision_buffer = None + self.controller.cancel_decision() + self._set_message("已放弃回答,按默认决策继续", "warn") + return + if key == ENTER: + answer = buffer.strip() + self._decision_buffer = None + if answer: + self.controller.submit_decision(answer) + else: + self.controller.cancel_decision() + return + if key == BACKSPACE: + self._decision_buffer = buffer[:-1] + return + if len(key) == 1 and key.isprintable(): + self._decision_buffer = buffer + key + + def _handle_input_key(self, key: str) -> None: + assert self._input is not None + if key == ESC: + self._input = None + return + if key == ENTER: + value = self._input["buffer"].strip() + self._input = None + if value: + self._append_plan(value) + return + if key == BACKSPACE: + self._input["buffer"] = self._input["buffer"][:-1] + return + if key == CTRL_C: + self._input = None + self._quit.set() + self.controller.stop.set() + return + if len(key) == 1 and key.isprintable(): + self._input["buffer"] += key + + def _append_plan(self, plan: str) -> None: + from .queue import build_task, save_queue_defs + + if self.paths is None: + self._set_message("队列路径未设置,无法追加", "error") + return + task = build_task( + self.project_root, + plan, + existing_ids={t.id for t in self.queue.tasks}, + ) + try: + self.queue.add(task) + save_queue_defs(self.paths, self.queue) + self._set_message(f"已加入队列: {task.id} → {task.plan}", "ok") + except ValueError as exc: + self._set_message(str(exc), "error") + + def _selected_task(self) -> Task | None: + tasks = self.queue.tasks + if not tasks: + return None + self.selected = min(self.selected, len(tasks) - 1) + return tasks[self.selected] + + def _running_task(self) -> Task | None: + """当前正在跑的任务(可能没有)。""" + for t in self.queue.tasks: + if t.status == RUNNING: + return t + return None + + def _retry_selected(self) -> None: + task = self._selected_task() + if task is None: + return + task.status = PENDING + task.attempts = 0 + task.last_error = "" + task.exit_code = None + task.finished_at = None + self._set_message(f"已重置 {task.id},将重新排队", "ok") + + def _toggle_pause(self) -> None: + task = self._selected_task() + if task is None: + return + task.enabled = not task.enabled + self._set_message(f"{task.id} 已{'恢复' if task.enabled else '暂停'}", "ok") + + def _delete_selected(self) -> None: + task = self._selected_task() + if task is None: + return + if task.status == RUNNING: + self._set_message("任务正在运行,不能删除", "error") + return + self.queue.remove(task.id) + self.selected = max(0, self.selected - 1) + self._set_message(f"已移除 {task.id}", "ok") + + # ── 渲染:左边 ────────────────────────────────────────────────── + def _left_lines(self, width: int) -> list[str]: + tasks = self.queue.tasks + stats = self.queue.stats() + + if not tasks: + body = ["", "队列为空", "", "按 a 追加 plan", ""] + else: + body = [] + id_w = max(8, min(18, width - 22)) + for idx, t in enumerate(tasks): + marker = "▶" if idx == self.selected else " " + name = truncate(t.id, id_w) + status = STATUS_LABEL.get(t.status, t.status) + line = f"{marker} {pad(name, id_w)} {pad(status, 6)} {t.attempts:>2}" + if idx == self.selected: + line = Style.BRIGHT_WHITE + line + Style.RESET + else: + line = f"{marker} {name}{' ' * max(0, id_w - dwidth(name))} " \ + f"{STATUS_STYLE.get(t.status, '')}{pad(status, 6)}{Style.RESET} {t.attempts:>2}" + body.append(line) + body.append("") + body.append( + Style.DIM + + f"待跑 {stats.get(PENDING, 0)} · 运行 {stats.get(RUNNING, 0)} · " + + f"成功 {stats.get(SUCCESS, 0)} · 失败 {stats.get(FAILED, 0)}" + + Style.RESET + ) + return body + + # ── 渲染:决策窗口 ────────────────────────────────────────────── + def _decision_lines(self, width: int) -> list[str]: + """正在等人回答时的决策框(没有则空)。""" + pending = self.controller.pending_question() + if pending is None: + self._decision_buffer = None + return [] + + with self._decision_lock: + if self._decision_buffer is None: + self._decision_buffer = "" + buffer = self._decision_buffer + + remaining = pending.get("remaining") + if remaining is None: + countdown = "不限时" + else: + secs = int(max(0, remaining)) + countdown = f"剩余 {secs // 60}:{secs % 60:02d}" + + box: list[str] = [ + Style.BOLD + Style.BRIGHT_YELLOW + "◆ 待决策" + Style.RESET, + Style.DIM + f" 任务: {pending.get('task_id', '')}" + Style.RESET, + ] + for ln in wrap(str(pending.get("question", "")), max(10, width - 4)): + box.append(" " + ln) + box.append("") + box.append(Style.BOLD + " 你的决策:" + Style.RESET) + box.append(" > " + Style.BRIGHT_WHITE + buffer + Style.RESET + "▏") + box.append("") + box.append( + Style.DIM + + f" {countdown} Enter 确认 · Esc 用默认决策 · Ctrl-C 退出" + + Style.RESET + ) + box.append("") + return box + + # ── 渲染:右边 ────────────────────────────────────────────────── + def _right_lines(self, width: int) -> list[str]: + if self._input is not None: + return [ + "", + self._input["prompt"] + Style.BRIGHT_WHITE + self._input["buffer"] + Style.RESET + "▏", + "", + Style.DIM + "Enter 确认 · Esc 取消" + Style.RESET, + ] + + detail = self.queue.get(self.detail_task_id) if self.detail_task_id else None + + lines: list[str] = self._decision_lines(width) + if detail is not None: + log_file = self.project_root / detail.log_path if detail.log_path else None + if log_file and log_file.exists(): + raw = log_file.read_text(encoding="utf-8", errors="replace").splitlines() + else: + raw = [f"({detail.id} 还没有日志)"] + else: + with self._log_lock: + raw = list(self._log_lines) + raw = raw[-self.cfg.log_tail:] + + if self.message: + style = {"error": Style.BRIGHT_RED, "warn": Style.BRIGHT_YELLOW, "ok": Style.BRIGHT_GREEN}.get( + self.message_level, "" + ) + lines.append(style + self.message + Style.RESET) + lines.append("") + + for ln in raw: + lines.extend(wrap(ln, width)) + + decisions = self.controller.decision_log.records[-6:] + if decisions: + lines.append("") + lines.append(Style.BOLD + Style.DIM + "最近决策" + Style.RESET) + # 问题占 40%,答案占剩下的 + q_w = max(8, (width - 3) * 2 // 5) + a_w = max(8, width - q_w - 3) + for d in decisions: + q = truncate(str(d.get("question", "")), q_w) + a = truncate(str(d.get("answer", "")), a_w) + lines.append(f"{Style.DIM}{q}{Style.RESET} → {a}") + + if not lines: + lines = [Style.DIM + "等待任务开始…" + Style.RESET] + return lines + + # ── 渲染:整体 ────────────────────────────────────────────────── + def render(self) -> None: + term = self.term + cols, rows = term.size() + left_w = min(LEFT_WIDTH, max(30, cols // 3)) + right_x = left_w + 1 + right_w = cols - left_w - 1 + body_h = max(3, rows - FOOTER_HEIGHT) + + term.clear() + + # 左:任务队列 + title = f"任务队列 ({len(self.queue)})" + term.draw_box( + x=1, + y=1, + w=left_w, + h=body_h, + title=title, + lines=self._left_lines(left_w - 4), + border=Style.CYAN, + title_style=Style.BOLD + Style.CYAN, + ) + + # 右:agent 输出 + # 标题用 **正在跑** 的任务,而不是选中行 —— 否则按 ↓ 切行后标题和内容对不上 + running = self._running_task() + if self._input is not None: + right_title = "追加任务" + elif self.detail_task_id: + right_title = f"任务日志 · {self.detail_task_id}" + elif running is not None: + right_title = f"Coding Agent · {running.id}" + else: + right_title = "Coding Agent" + + term.draw_box( + x=right_x, + y=1, + w=right_w, + h=body_h, + title=right_title, + lines=self._right_lines(right_w - 4), + border=Style.CYAN, + title_style=Style.BOLD + Style.CYAN, + ) + + # 底:快捷键 + if self.controller.pending_question() is not None: + hint = truncate(DECISION_HELP, cols - 4) + else: + hint = truncate(KEYBOARD_HELP, cols - 4) + term.draw_box( + x=1, + y=body_h + 1, + w=cols - 1, + h=FOOTER_HEIGHT, + lines=[Style.DIM + hint + Style.RESET], + border=Style.GREY, + ) + term.flush() + + # ── 主循环 ────────────────────────────────────────────────────── + def run(self) -> None: + from .keys import KeyReader + + reader = KeyReader(self.handle_key) + self.term.enter() + reader.start() + try: + while not self._quit.is_set(): + self.render() + time.sleep(1.0 / max(1, self.cfg.refresh_hz)) + finally: + reader.stop() + self.term.leave() + print(self.controller.snapshot()) diff --git a/overnight-runner/overnight_runner/util.py b/overnight-runner/overnight_runner/util.py new file mode 100644 index 0000000..deb1581 --- /dev/null +++ b/overnight-runner/overnight_runner/util.py @@ -0,0 +1,233 @@ +"""跨平台小工具:时间、时长、原子写、终端宽度。""" + +from __future__ import annotations + +import os +import shutil +import tempfile +import time +from datetime import datetime, timezone +from pathlib import Path + + +def now() -> datetime: + return datetime.now(timezone.utc).astimezone() + + +def now_iso() -> str: + return now().isoformat(timespec="seconds") + + +def fmt_ts(dt: datetime | None) -> str: + if dt is None: + return "-" + return dt.strftime("%m-%d %H:%M:%S") + + +def fmt_duration(seconds: float | None) -> str: + if seconds is None: + return "-" + seconds = int(max(0, seconds)) + h, rem = divmod(seconds, 3600) + m, s = divmod(rem, 60) + if h: + return f"{h}h{m:02d}m" + if m: + return f"{m}m{s:02d}s" + return f"{s}s" + + +def atomic_write(path: Path, text: str) -> None: + """同目录临时文件 + rename,避免读到写了一半的内容。""" + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh: + fh.write(text) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def append_jsonl(path: Path, record: dict) -> None: + import json + + path.parent.mkdir(parents=True, exist_ok=True) + line = json.dumps(record, ensure_ascii=False, sort_keys=False) + with path.open("a", encoding="utf-8", newline="\n") as fh: + fh.write(line + "\n") + fh.flush() + os.fsync(fh.fileno()) + + +def terminal_size() -> tuple[int, int]: + size = shutil.get_terminal_size(fallback=(100, 30)) + return size.columns, size.lines + + +def is_windows() -> bool: + return os.name == "nt" + + +def slugify(text: str, fallback: str = "task") -> str: + keep = [] + for ch in text.lower(): + if ch.isalnum() or ch in "-_": + keep.append(ch) + elif ch in " /\\": + keep.append("-") + slug = "".join(keep).strip("-") + while "--" in slug: + slug = slug.replace("--", "-") + return slug[:48] or fallback + + +def today_stamp() -> str: + return now().strftime("%Y%m%d") + + +def sleep_interruptible(seconds: float, stop: "StopFlag") -> None: + """可被 stop 打断的 sleep。""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if stop.is_set(): + return + time.sleep(min(0.25, max(0.0, deadline - time.monotonic()))) + + +class StopFlag: + """线程安全的停止标志。""" + + def __init__(self) -> None: + import threading + + self._event = threading.Event() + + def set(self) -> None: + self._event.set() + + def is_set(self) -> bool: + return self._event.is_set() + + def wait(self, timeout: float | None = None) -> bool: + return self._event.wait(timeout) + + +def pid_alive(pid: int) -> bool: + """进程还活着吗? + + Windows 上不能用 `os.kill(pid, 0)` —— 那会真的把进程杀掉, + 所以 Windows 走心跳判断(见 QueueLock)。 + """ + if pid <= 0: + return False + if is_windows(): + return True # Windows 上无法安全探测,交给心跳 + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + return True + + +class QueueLock: + """队列级单实例锁。 + + 同一个队列同时跑两个 runner 会把同一个 pending 任务跑两遍(白烧 agent), + 所以每条队列目录放一个锁文件。 + + 锁文件内容:{"pid": 12345, "started_at": "...", "heartbeat": 1793...} + 判定为 stale 的条件:pid 已死(POSIX)或心跳超过 STALE_SEC(Windows / 兜底)。 + """ + + STALE_SEC = 120.0 + + def __init__(self, path: Path) -> None: + self.path = path + self._held = False + + # ── 内部 ──────────────────────────────────────────────────────── + def _read(self) -> dict: + import json + + try: + data = json.loads(self.path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + def _write(self, data: dict) -> None: + import json + + atomic_write(self.path, json.dumps(data, ensure_ascii=False) + "\n") + + def _is_stale(self, data: dict) -> bool: + pid = int(data.get("pid") or 0) + if pid and not pid_alive(pid): + return True + if is_windows(): + heartbeat = float(data.get("heartbeat") or 0) + if heartbeat and (time.time() - heartbeat) > self.STALE_SEC: + return True + return False + + # ── 对外 ──────────────────────────────────────────────────────── + def acquire(self) -> tuple[bool, str]: + """拿锁。返回 (是否成功, 失败原因)。""" + self.path.parent.mkdir(parents=True, exist_ok=True) + if self.path.exists(): + data = self._read() + if not self._is_stale(data): + pid = int(data.get("pid") or 0) + return False, f"队列已被 pid {pid} 占用" + # 残留锁,清掉重建 + try: + self.path.unlink() + except OSError: + pass + self._write( + { + "pid": os.getpid(), + "started_at": now_iso(), + "heartbeat": time.time(), + } + ) + self._held = True + return True, "" + + def touch(self) -> None: + """更新心跳(长跑时定期调)。""" + if not self._held: + return + data = self._read() + data["heartbeat"] = time.time() + try: + self._write(data) + except OSError: + pass + + def release(self) -> None: + if not self._held: + return + self._held = False + try: + self.path.unlink() + except OSError: + pass + + def __enter__(self) -> "QueueLock": + ok, err = self.acquire() + if not ok: + raise RuntimeError(err) + return self + + def __exit__(self, *exc) -> None: + self.release() diff --git a/overnight-runner/overnight_runner/yaml_lite.py b/overnight-runner/overnight_runner/yaml_lite.py new file mode 100644 index 0000000..8374f82 --- /dev/null +++ b/overnight-runner/overnight_runner/yaml_lite.py @@ -0,0 +1,566 @@ +"""极简 YAML 子集解析 / 序列化 —— 零第三方依赖。 + +支持(覆盖本仓库用到的全部语法): + +- 缩进映射、序列 +- 序列项为映射(``- key: value`` 及其续行) +- 标量:plain / ``'single'`` / ``"double"`` +- 流式序列 ``[a, b]`` 与流式映射 ``{a: 1}`` +- 块标量 ``|`` ``|-`` ``>`` ``>-`` +- 注释(引号外、行首或前置空白后) +- 类型推断:bool / null / int / float / str +- 文档分隔符 ``---`` + +不支持(遇到会明确报错,不静默出错): + +- 锚点 ``&`` / 别名 ``*`` / 标签 ``!`` +- 复杂键(``? key``) +- 多文档(只取第一个) + +之所以自己写而不是用 PyYAML:让 overnight-runner **零依赖**, +在任何装了 Python 3.9+ 的机器上直接跑,不用 pip install。 +""" + +from __future__ import annotations + +from typing import Any + +__all__ = ["loads", "dumps", "YamlError"] + + +class YamlError(ValueError): + """YAML 解析失败。消息里带行号,便于定位。""" + + +# 序列项标记(用不可能出现在正文里的字符,避免与缩进层级混淆) +_SEQ = "\x00seq" + + +# ── 行处理 ────────────────────────────────────────────────────────── +class _Line: + __slots__ = ("indent", "text", "lineno", "raw_idx") + + def __init__(self, indent: int, text: str, lineno: int, raw_idx: int) -> None: + self.indent = indent + self.text = text + self.lineno = lineno + self.raw_idx = raw_idx + + def __repr__(self) -> str: # pragma: no cover - 调试用 + return f"_Line({self.indent}, {self.text!r}, line={self.lineno})" + + +def _strip_comment(text: str) -> str: + """去掉引号外的注释。""" + out = [] + quote = "" + i = 0 + while i < len(text): + ch = text[i] + if quote: + out.append(ch) + if ch == "\\" and quote == '"' and i + 1 < len(text): + out.append(text[i + 1]) + i += 2 + continue + if ch == quote: + quote = "" + i += 1 + continue + if ch in ("'", '"'): + quote = ch + out.append(ch) + i += 1 + continue + if ch == "#" and (not out or out[-1] in " \t"): + break + out.append(ch) + i += 1 + return "".join(out).rstrip() + + +def _split_key(text: str) -> tuple[str, str, str]: + """拆 ``key: value``。 + + 返回 (key, sep, value)。sep 为空表示这一行不是映射项。 + 引号内的冒号不算分隔符。 + """ + quote = "" + i = 0 + while i < len(text): + ch = text[i] + if quote: + if ch == "\\" and quote == '"' and i + 1 < len(text): + i += 2 + continue + if ch == quote: + quote = "" + i += 1 + continue + if ch in ("'", '"'): + quote = ch + i += 1 + continue + if ch in "[{": + break + if ch == ":": + rest = text[i + 1:] + if rest == "" or rest[0] in " \t": + return text[:i].strip(), ":", rest.strip() + i += 1 + return text.strip(), "", "" + + +def _unterminated(text: str) -> bool: + """引号没闭合(只关心行尾的引号状态)。""" + t = text.rstrip() + if len(t) >= 1 and t[-1] in ("'", '"'): + # 可能闭合了,也可能是转义过的 + return t.count(t[-1]) % 2 == 1 + if t.startswith("'") or t.startswith('"'): + return True + return False + + +def _fold(parts: list[str]) -> str: + """多行引号标量的折行规则:单换行折成空格,空行保留为换行。""" + result = "" + prev_blank = False + for i, ln in enumerate(parts): + if i == 0: + result = ln + continue + if ln.strip() == "": + result += "\n" + prev_blank = True + continue + if not prev_blank: + result += " " + result += ln + prev_blank = False + return result + + +def _preprocess(raw_lines: list[str]) -> list[_Line]: + """把原始行变成逻辑行。 + + 做三件事: + 1. 跳过空行、整行注释、``---`` + 2. 把 ``- key: value`` 拆成序列标记 + 内容行 + 3. 把跨行的引号标量合并成一行 + """ + out: list[_Line] = [] + idx = 0 + total = len(raw_lines) + while idx < total: + raw = raw_lines[idx] + if "\t" in raw[: len(raw) - len(raw.lstrip())]: + raise YamlError(f"第 {idx + 1} 行:YAML 缩进不能用 Tab") + stripped = raw.strip() + if not stripped or stripped.startswith("#"): + idx += 1 + continue + if stripped == "---": + idx += 1 + continue + if stripped in ("...",): + break + indent = len(raw) - len(raw.lstrip(" ")) + text = _strip_comment(raw[indent:]) + + if text == "-" or text.startswith("- "): + rest = text[1:].strip() + key, sep, _ = _split_key(rest) + # 统一拆成:序列标记 + 内容行 + out.append(_Line(indent, _SEQ, idx + 1, idx)) + if rest: + content_indent = indent + 2 if (sep and key) else indent + out.append(_Line(content_indent, rest, idx + 1, idx)) + idx += 1 + continue + + # 跨行的引号标量(PyYAML 会把带换行的字符串写成这种形式) + key, sep, val = _split_key(text) + if sep and val and _unterminated(val): + prefix = text[: len(text) - len(val)] + parts = [val] + j = idx + 1 + while j < total and _unterminated(_fold(parts)): + parts.append(raw_lines[j].strip()) + j += 1 + out.append(_Line(indent, prefix + _fold(parts), idx + 1, idx)) + idx = j + continue + + out.append(_Line(indent, text, idx + 1, idx)) + idx += 1 + return out + + +# ── 标量 ──────────────────────────────────────────────────────────── +_TRUE = {"true", "True", "TRUE"} +_FALSE = {"false", "False", "FALSE"} +_NULL = {"", "~", "null", "Null", "NULL"} + + +def _parse_scalar(text: str, lineno: int) -> Any: + t = text.strip() + if len(t) >= 2 and t[0] == '"' and t[-1] == '"': + return _unescape_double(t[1:-1], lineno) + if len(t) >= 2 and t[0] == "'" and t[-1] == "'": + return t[1:-1].replace("''", "'") + if t.startswith("[") and t.endswith("]"): + return _parse_flow_seq(t[1:-1], lineno) + if t.startswith("{") and t.endswith("}"): + return _parse_flow_map(t[1:-1], lineno) + if t in _TRUE: + return True + if t in _FALSE: + return False + if t in _NULL: + return None + try: + if t.lstrip("+-").isdigit(): + return int(t) + except ValueError: + pass + try: + if any(c in t for c in ".eE") and t.lstrip("+-").replace(".", "", 1).isdigit(): + return float(t) + except ValueError: + pass + return t + + +def _unescape_double(s: str, lineno: int) -> str: + out = [] + i = 0 + while i < len(s): + ch = s[i] + if ch == "\\" and i + 1 < len(s): + nxt = s[i + 1] + mapping = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\", "/": "/", "0": "\0"} + if nxt in mapping: + out.append(mapping[nxt]) + i += 2 + continue + if nxt == "u" and i + 5 < len(s) + 1: + try: + out.append(chr(int(s[i + 2: i + 6], 16))) + i += 6 + continue + except ValueError: + raise YamlError(f"第 {lineno} 行:非法的 \\u 转义") + raise YamlError(f"第 {lineno} 行:未知的转义 \\{nxt}") + out.append(ch) + i += 1 + return "".join(out) + + +def _split_flow(body: str, lineno: int) -> list[str]: + """按顶层逗号切分流式集合的内容。""" + parts = [] + buf = [] + depth = 0 + quote = "" + for ch in body: + if quote: + buf.append(ch) + if ch == quote: + quote = "" + continue + if ch in ("'", '"'): + quote = ch + buf.append(ch) + continue + if ch in "[{": + depth += 1 + elif ch in "]}": + depth -= 1 + if ch == "," and depth == 0: + parts.append("".join(buf)) + buf = [] + continue + buf.append(ch) + tail = "".join(buf) + if tail.strip() or parts: + parts.append(tail) + return [p.strip() for p in parts] + + +def _parse_flow_seq(body: str, lineno: int) -> list: + body = body.strip() + if not body: + return [] + return [_parse_scalar(p, lineno) for p in _split_flow(body, lineno)] + + +def _parse_flow_map(body: str, lineno: int) -> dict: + body = body.strip() + if not body: + return {} + out = {} + for part in _split_flow(body, lineno): + key, sep, value = _split_key(part) + if not sep: + raise YamlError(f"第 {lineno} 行:流式映射项格式错误: {part!r}") + out[_parse_scalar(key, lineno)] = _parse_scalar(value, lineno) + return out + + +# ── 块标量 ────────────────────────────────────────────────────────── +def _read_block_scalar( + raw_lines: list[str], start_raw: int, key_indent: int, style: str, lineno: int +) -> tuple[str, int]: + """读块标量(| 或 >)。返回 (文本, 消耗到的 raw 索引)。""" + folded = style[0] == ">" + chomp = "clip" + if style.endswith("-"): + chomp = "strip" + elif style.endswith("+"): + chomp = "keep" + + body: list[str] = [] + i = start_raw + block_indent: int | None = None + while i < len(raw_lines): + raw = raw_lines[i] + if raw.strip() == "": + body.append("") + i += 1 + continue + indent = len(raw) - len(raw.lstrip(" ")) + if indent <= key_indent: + break + if block_indent is None: + block_indent = indent + body.append(raw[block_indent:] if len(raw) >= block_indent else "") + i += 1 + + # 去掉尾部空行(按 chomp 策略再决定加不加回来) + while body and body[-1] == "": + body.pop() + i -= 1 + + if folded: + text = "" + for idx, ln in enumerate(body): + if idx == 0: + text = ln + elif ln == "" or body[idx - 1] == "": + text += "\n" + ln + else: + text += " " + ln + else: + text = "\n".join(body) + + if chomp == "strip": + return text, i + if chomp == "keep": + return text + "\n", i + return (text + "\n") if text else "", i + + +# ── 主解析 ────────────────────────────────────────────────────────── +def loads(text: str) -> Any: + """解析 YAML 文本。""" + raw_lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") + lines = _preprocess(raw_lines) + if not lines: + return None + value, idx = _parse_node(lines, 0, lines[0].indent, raw_lines) + if idx < len(lines): + raise YamlError(f"第 {lines[idx].lineno} 行:缩进异常") + return value + + +def _parse_node(lines: list[_Line], i: int, indent: int, raw_lines: list[str]) -> tuple[Any, int]: + if lines[i].text == _SEQ: + return _parse_sequence(lines, i, indent, raw_lines) + return _parse_mapping(lines, i, indent, raw_lines) + + +def _parse_mapping( + lines: list[_Line], i: int, indent: int, raw_lines: list[str] +) -> tuple[dict, int]: + result: dict = {} + while i < len(lines) and lines[i].indent == indent: + line = lines[i] + if line.text == _SEQ: + break + key, sep, rest = _split_key(line.text) + if not sep: + raise YamlError(f"第 {line.lineno} 行:期望 `key: value`,得到 {line.text!r}") + if key.startswith("&") or key.startswith("*") or key.startswith("!"): + raise YamlError(f"第 {line.lineno} 行:不支持锚点/别名/标签") + key_value = _parse_scalar(key, line.lineno) + + if rest and rest[0] in "|>": + value, consumed = _read_block_scalar( + raw_lines, line.raw_idx + 1, indent, rest, line.lineno + ) + result[key_value] = value + # 跳到块标量之后的第一条逻辑行 + i += 1 + while i < len(lines) and lines[i].raw_idx < consumed: + i += 1 + continue + + if rest == "": + nxt = lines[i + 1] if i + 1 < len(lines) else None + # 块序列可以与它的 key 同缩进(PyYAML 的写法),也可以更深 + if nxt is not None and ( + nxt.indent > indent + or (nxt.indent == indent and nxt.text == _SEQ) + ): + value, i = _parse_node(lines, i + 1, nxt.indent, raw_lines) + else: + value = None + i += 1 + else: + value = _parse_scalar(rest, line.lineno) + i += 1 + result[key_value] = value + return result, i + + +def _parse_sequence( + lines: list[_Line], i: int, indent: int, raw_lines: list[str] +) -> tuple[list, int]: + result: list = [] + while i < len(lines) and lines[i].indent == indent and lines[i].text == _SEQ: + marker = lines[i] + i += 1 + + if i >= len(lines): + result.append(None) + break + + content = lines[i] + if content.indent == indent + 2: + # 序列项是映射 + value, i = _parse_mapping(lines, i, content.indent, raw_lines) + result.append(value) + continue + + if content.indent != indent: + # 空项 / 嵌套块 + value, i = _parse_node(lines, i, content.indent, raw_lines) + result.append(value) + continue + + rest = content.text + if rest and rest[0] in "|>": + value, consumed = _read_block_scalar( + raw_lines, marker.raw_idx + 1, indent, rest, marker.lineno + ) + result.append(value) + i += 1 + while i < len(lines) and lines[i].raw_idx < consumed: + i += 1 + continue + + result.append(_parse_scalar(rest, marker.lineno)) + i += 1 + return result, i + + +# ── 序列化 ────────────────────────────────────────────────────────── +_PLAIN_SAFE = set( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./+@" +) + + +def _needs_quote(s: str) -> bool: + if s == "": + return True + if s.strip() != s: + return True + if s[0] in "-?:,[]{}#&*!|>'\"%@`": + return True + if ": " in s or " #" in s or s.endswith(":"): + return True + if "\n" in s or "\t" in s: + return True + if any(c not in _PLAIN_SAFE for c in s): + # 含中文、空格等 —— 加引号更安全 + return True + if s in _TRUE or s in _FALSE or s in _NULL: + return True + try: + float(s) + return True + except ValueError: + return False + + +def _dump_scalar(value: Any) -> str: + if value is None: + return "null" + if value is True: + return "true" + if value is False: + return "false" + if isinstance(value, (int, float)): + return str(value) + s = str(value) + if "\n" in s: + return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"' + if _needs_quote(s): + return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"' + return s + + +def dumps(data: Any, indent: int = 0) -> str: + """把数据序列化成 YAML 子集文本。""" + lines: list[str] = [] + + def emit(node: Any, level: int) -> None: + pad = " " * (level * 2) + if isinstance(node, dict): + for key, value in node.items(): + if isinstance(value, dict) and value: + lines.append(f"{pad}{key}:") + emit(value, level + 1) + elif isinstance(value, list) and value: + lines.append(f"{pad}{key}:") + emit(value, level + 1) + elif isinstance(value, dict): + lines.append(f"{pad}{key}: {{}}") + elif isinstance(value, list): + lines.append(f"{pad}{key}: []") + elif isinstance(value, str) and "\n" in value: + lines.append(f"{pad}{key}: |") + for ln in value.rstrip("\n").split("\n"): + lines.append(f"{pad} {ln}") + else: + lines.append(f"{pad}{key}: {_dump_scalar(value)}") + elif isinstance(node, list): + for item in node: + if isinstance(item, dict) and item: + first = True + for key, value in item.items(): + prefix = f"{pad}- " if first else f"{pad} " + first = False + if isinstance(value, dict) and value: + lines.append(f"{prefix}{key}:") + emit(value, level + 2) + elif isinstance(value, list) and value: + lines.append(f"{prefix}{key}:") + emit(value, level + 2) + elif isinstance(value, str) and "\n" in value: + lines.append(f"{prefix}{key}: |") + for ln in value.rstrip("\n").split("\n"): + lines.append(f"{pad} {ln}") + else: + lines.append(f"{prefix}{key}: {_dump_scalar(value)}") + elif isinstance(item, (list, dict)): + lines.append(f"{pad}-") + emit(item, level + 1) + else: + lines.append(f"{pad}- {_dump_scalar(item)}") + else: + lines.append(f"{pad}{_dump_scalar(node)}") + + emit(data, indent) + return "\n".join(lines) + "\n" diff --git a/overnight-runner/scripts/install.sh b/overnight-runner/scripts/install.sh new file mode 100755 index 0000000..d2d5b55 --- /dev/null +++ b/overnight-runner/scripts/install.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# 把 overnight-runner 安装到目标项目。 +# +# 用法: +# ./install.sh <目标项目目录> [--dry-run] [--force] [--no-config] +# +# --dry-run 只打印将要发生的改动,不写文件 +# --force 覆盖已存在的 runner 代码 +# --no-config 不创建队列配置与项目配置 +# +# 零依赖:只用 Python 3.9+ 标准库,不需要 pip install。 + +set -euo pipefail + +INSTALLER_DIR="$(cd "$(dirname "$0")/.." && pwd)" +PKG_DIR="$INSTALLER_DIR/overnight_runner" +TARGET_TOOLS="tools/overnight-runner" + +DRY_RUN=0 +FORCE=0 +NO_CONFIG=0 + +usage() { + sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//' + exit "${1:-0}" +} + +while [ $# -gt 0 ]; do + case "$1" in + --dry-run) DRY_RUN=1 ;; + --force) FORCE=1 ;; + --no-config) NO_CONFIG=1 ;; + -h|--help) usage 0 ;; + -*) echo "未知参数: $1" >&2; usage 1 ;; + *) TARGET="$1" ;; + esac + shift +done + +if [ -z "${TARGET:-}" ]; then + echo "错误:缺少目标项目目录。" >&2 + usage 1 +fi +if [ ! -d "$TARGET" ]; then + echo "错误:目标目录不存在: $TARGET" >&2 + exit 1 +fi + +PROJECT_ROOT="$(cd "$TARGET" && pwd)" +DEST="$PROJECT_ROOT/$TARGET_TOOLS" + +# ── 找 python ────────────────────────────────────────────────────── +PYTHON="" +for c in python3 python; do + if command -v "$c" >/dev/null 2>&1; then + if "$c" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 9) else 1)' 2>/dev/null; then + PYTHON="$c" + break + fi + fi +done +if [ -z "$PYTHON" ]; then + echo "错误:找不到 Python 3.9+。请先安装 Python。" >&2 + exit 1 +fi + +echo "overnight-runner 安装器" +echo " 模板目录 : $INSTALLER_DIR" +echo " 目标项目 : $PROJECT_ROOT" +echo " 安装位置 : $TARGET_TOOLS" +echo " Python : $PYTHON ($($PYTHON -V 2>&1))" +echo "" + +if [ ! -d "$PKG_DIR" ]; then + echo "错误:找不到 runner 包 $PKG_DIR" >&2 + exit 1 +fi + +# ── 拷贝代码 ─────────────────────────────────────────────────────── +if [ -d "$DEST" ] && [ "$FORCE" -eq 0 ]; then + echo " [跳过] $TARGET_TOOLS 已存在(用 --force 覆盖)" +else + if [ "$DRY_RUN" -eq 1 ]; then + echo " [计划] 安装 runner 代码 → $DEST" + else + rm -rf "$DEST" + mkdir -p "$DEST" + cp -R "$PKG_DIR" "$DEST/overnight_runner" + echo " [安装] runner 代码 → $DEST" + fi +fi + +# ── 启动脚本 ─────────────────────────────────────────────────────── +if [ "$DRY_RUN" -eq 1 ]; then + echo " [计划] 生成 overnight-runner 启动脚本" +else + cat > "$DEST/overnight-runner" < "$DEST/overnight-runner.cmd" <&1))" +fi + +# ── 配置文件 ─────────────────────────────────────────────────────── +if [ "$NO_CONFIG" -eq 0 ]; then + if [ "$DRY_RUN" -eq 1 ]; then + echo " [计划] 创建 overnight-runner.yaml 与 .overnight-runner/project.yaml" + else + if [ ! -f "$PROJECT_ROOT/overnight-runner.yaml" ]; then + cp "$INSTALLER_DIR/config/overnight-runner.example.yaml" "$PROJECT_ROOT/overnight-runner.yaml" + echo " [安装] 运行配置 → overnight-runner.yaml" + else + echo " [保留] overnight-runner.yaml 已存在" + fi + + mkdir -p "$PROJECT_ROOT/.overnight-runner" + if [ ! -f "$PROJECT_ROOT/.overnight-runner/project.yaml" ]; then + cp "$INSTALLER_DIR/config/project.example.yaml" "$PROJECT_ROOT/.overnight-runner/project.yaml" + echo " [安装] 项目配置 → .overnight-runner/project.yaml" + else + echo " [保留] .overnight-runner/project.yaml 已存在" + fi + fi +else + echo " [跳过] 未创建配置文件(--no-config)" +fi + +# ── gitignore 提醒 ───────────────────────────────────────────────── +# 逐层往上找 .gitignore(项目自己的 / 仓库根的),找到已排除队列运行时产物的就不提醒 +if [ "$NO_CONFIG" -eq 0 ]; then + NEED_IGNORE=1 + DIR="$PROJECT_ROOT" + while [ "$DIR" != "/" ] && [ -n "$DIR" ]; do + if [ -f "$DIR/.gitignore" ] && grep -q "overnight-runner/queue" "$DIR/.gitignore" 2>/dev/null; then + NEED_IGNORE=0 + break + fi + DIR="$(dirname "$DIR")" + done + if [ "$NEED_IGNORE" -eq 1 ]; then + echo "" + echo "提示:把运行时状态加进 .gitignore(保留 project.yaml / queue.yaml / decisions.jsonl):" + echo " **/.overnight-runner/queue/*/state.json" + echo " **/.overnight-runner/queue/*/logs/" + echo " **/.overnight-runner/queue/*/.lock" + fi +fi + +echo "" +echo "完成。" +echo "" +echo "下一步:" +echo " 1) 编辑 overnight-runner.yaml 配 agent / 看门狗 / 决策模式" +echo " 2) 编辑 .overnight-runner/project.yaml 配默认提示词与默认决策规则" +echo " 3) 追加任务:$TARGET_TOOLS/overnight-runner add docs/plans/xxx.md" +echo " 4) 启动面板:$TARGET_TOOLS/overnight-runner run" +echo " 5) 多队列:$TARGET_TOOLS/overnight-runner --queue alice add docs/plans/yyy.md" diff --git a/overnight-runner/tests/test_smoke.py b/overnight-runner/tests/test_smoke.py new file mode 100644 index 0000000..9bb370d --- /dev/null +++ b/overnight-runner/tests/test_smoke.py @@ -0,0 +1,431 @@ +"""冒烟测试:不依赖真实 agent,用假脚本验证队列、决策、看门狗。 + +运行: + python -m pytest tests/ -q +或直接: + python tests/test_smoke.py +""" + +from __future__ import annotations + +import json +import os +import shutil +import sys +import tempfile +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from overnight_runner import yaml_lite as yaml # noqa: E402 + +from overnight_runner.cli import main as cli_main # noqa: E402 +from overnight_runner.config import ( # noqa: E402 + DECISION_MODE_ATTENDED, + DECISION_MODE_UNATTENDED, + load_project_config, + load_runner_config, + queue_paths, +) +from overnight_runner.controller import RunnerController # noqa: E402 +from overnight_runner.decisions import DecisionLog, match_rule, parse_agent_line # noqa: E402 +from overnight_runner.queue import ( # noqa: E402 + FAILED, + SUCCESS, + build_task, + load_queue, + load_queue_defs, + save_queue_defs, +) +from overnight_runner.util import StopFlag # noqa: E402 + + +# 假 agent 统一前缀:记录第几次调用 + 把参数写进 args 文件(换行压成 ~) +FAKE_PROLOGUE = """ +COUNT_FILE="${FAKE_COUNT:-/dev/null}" +ARGS_FILE="${FAKE_ARGS:-/dev/null}" +n=$(cat "$COUNT_FILE" 2>/dev/null || echo 0) +n=$((n+1)) +echo "$n" > "$COUNT_FILE" 2>/dev/null || true +printf 'CALL %s: %s\\n' "$n" "$(printf '%s' "$*" | tr '\\n' '~')" >> "$ARGS_FILE" 2>/dev/null || true +""" + + +def _write_fake_agent(path: Path, body: str) -> str: + path.write_text( + f"#!/usr/bin/env bash\n{FAKE_PROLOGUE}{body}\n", encoding="utf-8" + ) + path.chmod(0o755) + return str(path) + + +# 假 agent:第一次调用抛问题,第二次(带 --session)回答"拿到答案" +FAKE_ASK_THEN_ANSWER = """ +if [ "$n" -eq 1 ]; then + echo '{"type":"text","sessionID":"ses_fake0001","part":{"type":"text","text":"QUESTION: 要改吗?"}}' + exit 0 +fi +echo '{"type":"text","sessionID":"ses_fake0001","part":{"type":"text","text":"DONE: 拿到答案继续干"}}' +exit 0 +""" + + +def _setup( + tmp: Path, + agent: str, + queue: list[dict], + watchdog: dict | None = None, + decision: dict | None = None, +) -> Path: + root = tmp / "proj" + (root / "docs" / "plans").mkdir(parents=True) + (root / "docs" / "plans" / "p1.md").write_text("# Plan 1\n做点事\n", encoding="utf-8") + + cfg = { + "runner": { + "agent": { + "command": agent, + "args": [], + "env": { + "FAKE_COUNT": str(tmp / "count"), + "FAKE_ARGS": str(tmp / "args"), + }, + }, + "watchdog": watchdog + or {"maxRetries": 0, "backoffSec": 1, "idleTimeoutSec": 30, "totalTimeoutSec": 60}, + "decision": decision or {"mode": DECISION_MODE_UNATTENDED}, + "state": {"dir": ".overnight-runner"}, + "workdir": ".", + "ui": {"refreshHz": 8, "logTail": 100}, + }, + } + (root / "overnight-runner.yaml").write_text(yaml.dumps(cfg), encoding="utf-8") + + pcfg = { + "project": {"name": "proj", "agent": {"command": agent, "args": [], "env": {}}}, + "default": {"prompt": "{{DECISIONS}}\n{{PLAN}}", "onUnknownDecision": "跳过并记录"}, + "decisions": [ + { + "id": "db", + "question": "是否执行数据库迁移脚本?", + "match": "数据库迁移", + "answer": "先写回滚脚本", + "enabled": True, + } + ], + } + (root / ".overnight-runner").mkdir() + (root / ".overnight-runner" / "project.yaml").write_text( + yaml.dumps(pcfg), encoding="utf-8" + ) + + paths = queue_paths(root, "default") + paths.dir.mkdir(parents=True, exist_ok=True) + (paths.config).write_text(yaml.dumps({"queue": queue}), encoding="utf-8") + return root + + +def _controller(root: Path) -> tuple[RunnerController, object]: + cfg = load_runner_config(root) + pcfg = load_project_config(root) + paths = queue_paths(root, "default") + q = load_queue(paths, load_queue_defs(paths)) + ctl = RunnerController(root, cfg, pcfg, q, paths, stop=StopFlag()) + return ctl, q + + +def _wait_pending(ctl: RunnerController, timeout: float = 10.0) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if ctl.pending_question() is not None: + return True + time.sleep(0.05) + return False + + +def _fake_calls(tmp: Path) -> list[str]: + path = tmp / "args" + if not path.exists(): + return [] + return [ln for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip()] + + +# ── 既有场景 ──────────────────────────────────────────────────────── +def test_queue_add_and_append(tmp: Path) -> None: + root = _setup(tmp, "true", []) + cfg = load_runner_config(root) + paths = queue_paths(root, "default") + q = load_queue(paths, load_queue_defs(paths)) + + t1 = build_task(root, "docs/plans/p1.md", existing_ids={t.id for t in q.tasks}) + q.add(t1) + t2 = build_task(root, "docs/plans/p1.md", existing_ids={t.id for t in q.tasks}) + q.add(t2) + assert t1.id != t2.id, "同一天同一个 plan 也要能排两次" + + save_queue_defs(paths, q) + again = load_queue_defs(paths) + assert len(again) == 2 + assert cfg.agent_command == "true" + + +def test_successful_task_records_decision(tmp: Path) -> None: + agent = _write_fake_agent( + tmp / "ok.sh", + 'echo "DECISION: 是否执行数据库迁移脚本? → 先写回滚脚本"\necho "DONE: 搞定"', + ) + root = _setup(tmp, agent, [{"id": "t1", "plan": "docs/plans/p1.md"}]) + ctl, q = _controller(root) + ctl.run_forever() + + task = q.get("t1") + assert task is not None + assert task.status == SUCCESS, f"期望成功,实际 {task.status}: {task.last_error}" + assert task.summary == "搞定" + + records = DecisionLog(queue_paths(root, "default").decisions).load() + assert len(records) == 1 + assert records[0]["source"] == "agent" + assert records[0]["question"] == "是否执行数据库迁移脚本?" + + +def test_failed_task_retries_then_fails(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "fail.sh", 'echo "boom"\nexit 3') + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + watchdog={"maxRetries": 2, "backoffSec": 0, "idleTimeoutSec": 30, "totalTimeoutSec": 60}, + ) + ctl, q = _controller(root) + ctl.run_forever() + + task = q.get("t1") + assert task is not None + assert task.status == FAILED + assert task.attempts == 3, f"期望 1 次 + 2 次重试,实际 {task.attempts} 次" + + +def test_idle_timeout_kills_agent(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "hang.sh", 'echo "开始"\nsleep 30') + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + watchdog={ + "maxRetries": 0, + "backoffSec": 0, + "idleTimeoutSec": 1, + "totalTimeoutSec": 60, + "killGraceSec": 1, + }, + ) + ctl, q = _controller(root) + ctl.run_forever() + + task = q.get("t1") + assert task is not None + assert task.status == FAILED + assert "超时" in task.last_error, task.last_error + + +def test_question_hits_rule(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "q.sh", 'echo "QUESTION: 是否执行数据库迁移脚本?"\necho "DONE: ok"') + root = _setup(tmp, agent, [{"id": "t1", "plan": "docs/plans/p1.md"}]) + ctl, q = _controller(root) + ctl.run_forever() + + records = DecisionLog(queue_paths(root, "default").decisions).load() + assert len(records) == 1 + assert records[0]["source"] == "rule" + assert records[0]["rule_id"] == "db" + assert records[0]["answer"] == "先写回滚脚本" + + +def test_parse_agent_line(tmp: Path) -> None: + assert parse_agent_line("DECISION: A → B") == ("decision", ("A", "B")) + assert parse_agent_line("QUESTION: 要改吗?") == ("question", "要改吗?") + assert parse_agent_line("DONE: 好了") == ("done", "好了") + assert parse_agent_line("BLOCKED: 卡住了") == ("blocked", "卡住了") + assert parse_agent_line("普通输出") == ("", "") + + +def test_match_rule(tmp: Path) -> None: + pcfg = load_project_config(_setup(Path(tempfile.mkdtemp()), "true", [])) + assert match_rule(pcfg.decisions, "是否执行数据库迁移脚本?") is not None + assert match_rule(pcfg.decisions, "要不要重构") is None + + +# ── 有人值守:人回答 ──────────────────────────────────────────────── +def test_attended_human_answer_resumes_session(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "ask.sh", FAKE_ASK_THEN_ANSWER) + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + decision={"mode": DECISION_MODE_ATTENDED, "timeoutSec": 30}, + ) + ctl, q = _controller(root) + + worker = threading.Thread(target=ctl.run_forever, daemon=True) + worker.start() + assert _wait_pending(ctl), "应该弹出决策窗口" + ctl.submit_decision("先修 Bug,不要扩大改动范围") + worker.join(timeout=30) + + task = q.get("t1") + assert task is not None and task.status == SUCCESS, task.last_error + + calls = _fake_calls(tmp) + assert len(calls) == 2, f"agent 应被拉起两次(问 + 续跑),实际 {len(calls)} 次" + assert "--session ses_fake0001" in calls[1], f"续跑应带 --session: {calls[1]}" + assert "先修 Bug" in calls[1], "续跑的 prompt 里应带上人的答案" + + records = DecisionLog(queue_paths(root, "default").decisions).load() + humans = [r for r in records if r["source"] == "human"] + assert len(humans) == 1, records + assert humans[0]["answer"] == "先修 Bug,不要扩大改动范围" + assert humans[0]["session_id"] == "ses_fake0001" + assert humans[0]["waited_sec"] >= 0 + + +# ── 有人值守:超时兜底 ────────────────────────────────────────────── +def test_attended_timeout_falls_back(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "ask.sh", FAKE_ASK_THEN_ANSWER) + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + decision={"mode": DECISION_MODE_ATTENDED, "timeoutSec": 1}, + ) + ctl, q = _controller(root) + + worker = threading.Thread(target=ctl.run_forever, daemon=True) + worker.start() + assert _wait_pending(ctl), "应该弹出决策窗口" + worker.join(timeout=30) # 不回答,等它超时 + + task = q.get("t1") + assert task is not None and task.status == SUCCESS, task.last_error + + calls = _fake_calls(tmp) + assert len(calls) == 2, f"超时后仍要续跑,实际 {len(calls)} 次" + assert "--session ses_fake0001" in calls[1] + + records = DecisionLog(queue_paths(root, "default").decisions).load() + timeouts = [r for r in records if r["source"] == "timeout"] + assert len(timeouts) == 1, records + assert timeouts[0]["answer"] == "跳过并记录", "超时应该用兜底策略" + + +# ── 决策历史注入 ──────────────────────────────────────────────────── +def test_decision_history_is_injected(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "ask.sh", FAKE_ASK_THEN_ANSWER) + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + decision={"mode": DECISION_MODE_ATTENDED, "timeoutSec": 30}, + ) + ctl, q = _controller(root) + + worker = threading.Thread(target=ctl.run_forever, daemon=True) + worker.start() + assert _wait_pending(ctl) + ctl.submit_decision("按 Plan §11.1 改类型声明") + worker.join(timeout=30) + + calls = _fake_calls(tmp) + assert len(calls) == 2 + # 续跑用的是 resume prompt(决策直接带进去) + assert "按 Plan §11.1 改类型声明" in calls[1] + + +# ── 无人值守 ──────────────────────────────────────────────────────── +def test_unattended_does_not_interrupt(tmp: Path) -> None: + agent = _write_fake_agent( + tmp / "q.sh", + 'echo "QUESTION: 是否执行数据库迁移脚本?"\necho "DONE: ok"', + ) + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + decision={"mode": DECISION_MODE_UNATTENDED}, + ) + ctl, q = _controller(root) + ctl.run_forever() + + calls = _fake_calls(tmp) + assert len(calls) == 1, f"无人值守不该打断 agent,实际调用 {len(calls)} 次" + records = DecisionLog(queue_paths(root, "default").decisions).load() + assert any(r["source"] == "rule" for r in records), records + + +# ── CLI:headless 强制无人值守 ────────────────────────────────────── +def test_cli_headless_forces_unattended(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "q.sh", 'echo "QUESTION: 要改吗?"\necho "DONE: ok"') + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + decision={"mode": DECISION_MODE_ATTENDED, "timeoutSec": 600}, + ) + rc = cli_main( + ["--project", str(root), "--queue", "default", "run", "--headless"] + ) + assert rc == 0, rc + calls = _fake_calls(tmp) + assert len(calls) == 1, "headless 不该等人回答" + records = DecisionLog(queue_paths(root, "default").decisions).load() + assert not [r for r in records if r["source"] in ("human", "timeout")], records + + +def test_cli_mode_override_unattended(tmp: Path) -> None: + agent = _write_fake_agent(tmp / "q.sh", 'echo "QUESTION: 要改吗?"\necho "DONE: ok"') + root = _setup( + tmp, + agent, + [{"id": "t1", "plan": "docs/plans/p1.md"}], + decision={"mode": DECISION_MODE_ATTENDED, "timeoutSec": 600}, + ) + rc = cli_main( + [ + "--project", + str(root), + "--queue", + "default", + "run", + "--headless", + "--mode", + DECISION_MODE_UNATTENDED, + ] + ) + assert rc == 0, rc + calls = _fake_calls(tmp) + assert len(calls) == 1, "--mode unattended 不该打断" + + +def _run_all() -> int: + tmp = Path(tempfile.mkdtemp(prefix="orn-test-")) + failures = [] + tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")] + for fn in tests: + case_dir = tmp / fn.__name__ + case_dir.mkdir(parents=True, exist_ok=True) + try: + fn(case_dir) + print(f" ✔ {fn.__name__}") + except Exception as exc: # noqa: BLE001 + failures.append((fn.__name__, exc)) + print(f" ✘ {fn.__name__}: {exc}") + shutil.rmtree(tmp, ignore_errors=True) + print() + print(f"{len(tests) - len(failures)}/{len(tests)} 通过") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(_run_all()) diff --git a/overnight-runner/tests/test_units.py b/overnight-runner/tests/test_units.py new file mode 100644 index 0000000..a4c09bf --- /dev/null +++ b/overnight-runner/tests/test_units.py @@ -0,0 +1,648 @@ +"""yaml_lite 与 term 的单元测试(零依赖)。 + +运行:python tests/test_units.py +""" + +from __future__ import annotations + +import json +import os +import pathlib +import sys +import tempfile +from datetime import datetime, timedelta, timezone + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) + +from overnight_runner import yaml_lite # noqa: E402 +from overnight_runner.agent import extract_session_id, parse_agent_output # noqa: E402 +from overnight_runner.cli import resolve_decision_mode # noqa: E402 +from overnight_runner.config import ( # noqa: E402 + DECISION_MODE_ATTENDED, + DECISION_MODE_UNATTENDED, + DecisionConfig, + DecisionRule, + ProjectConfig, + RunnerConfig, + load_runner_config, + migrate_legacy_queue, + queue_names, + queue_paths, + save_runner_config, +) +from overnight_runner.decisions import resolve_answer, should_ask # noqa: E402 +from overnight_runner.queue import ( # noqa: E402 + SUCCESS, + build_task, + load_queue, + load_queue_defs, + save_queue_defs, + save_state, +) +from overnight_runner.term import dwidth, pad, truncate, wrap # noqa: E402 +from overnight_runner.util import QueueLock # noqa: E402 + + +# ── yaml_lite ─────────────────────────────────────────────────────── +def test_yaml_scalar_types() -> None: + d = yaml_lite.loads( + """ +i: 42 +f: 3.14 +t: true +f2: false +n: null +tilde: ~ +empty: +s: hello +q: "quoted: value" +sq: 'single' +""" + ) + assert d["i"] == 42 and isinstance(d["i"], int) + assert d["f"] == 3.14 + assert d["t"] is True and d["f2"] is False + assert d["n"] is None and d["tilde"] is None and d["empty"] is None + assert d["s"] == "hello" + assert d["q"] == "quoted: value" + assert d["sq"] == "single" + + +def test_yaml_nested_and_lists() -> None: + d = yaml_lite.loads( + """ +runner: + agent: + command: opencode + args: ["run", "--verbose"] + env: {} + watchdog: + maxRetries: 2 +queue: + - id: a + plan: docs/plans/a.md + tags: [x, y] + - id: b + plan: docs/plans/b.md +""" + ) + assert d["runner"]["agent"]["command"] == "opencode" + assert d["runner"]["agent"]["args"] == ["run", "--verbose"] + assert d["runner"]["agent"]["env"] == {} + assert d["runner"]["watchdog"]["maxRetries"] == 2 + assert len(d["queue"]) == 2 + assert d["queue"][0]["id"] == "a" + assert d["queue"][0]["tags"] == ["x", "y"] + assert d["queue"][1]["plan"] == "docs/plans/b.md" + + +def test_yaml_sequence_at_same_indent_as_key() -> None: + """PyYAML 会把序列写在与 key 同缩进的位置,必须能读。""" + d = yaml_lite.loads( + """ +queue: +- id: a + plan: p1.md +- id: b + plan: p2.md +""" + ) + assert len(d["queue"]) == 2 + assert d["queue"][0]["id"] == "a" + assert d["queue"][1]["plan"] == "p2.md" + + +def test_yaml_block_scalar() -> None: + d = yaml_lite.loads( + """ +default: + prompt: | + 第一行 + 第二行 + other: x +""" + ) + assert d["default"]["prompt"] == "第一行\n第二行\n" + assert d["default"]["other"] == "x" + + +def test_yaml_multi_line_quoted_scalar() -> None: + """PyYAML 会把带换行的字符串写成跨行引号形式,必须能读。""" + d = yaml_lite.loads( + """ +prompt: '第一行 + +第二行' +other: y +""" + ) + assert d["prompt"] == "第一行\n第二行" + assert d["other"] == "y" + + +def test_yaml_comments_ignored() -> None: + d = yaml_lite.loads( + """ +# 整行注释 +a: 1 # 行尾注释 +b: "带 # 号的字符串" +""" + ) + assert d["a"] == 1 + assert d["b"] == "带 # 号的字符串" + + +def test_yaml_roundtrip() -> None: + data = { + "runner": {"agent": {"command": "opencode", "args": ["run"], "env": {}}}, + "queue": [ + {"id": "a", "plan": "docs/plans/a.md", "priority": 10}, + {"id": "b", "plan": "docs/plans/b.md", "prompt": "做点事"}, + ], + "note": "带: 冒号的字符串", + } + text = yaml_lite.dumps(data) + assert yaml_lite.loads(text) == data + + +def test_yaml_real_config_files() -> None: + base = pathlib.Path(__file__).resolve().parent.parent / "config" + for f in ("overnight-runner.example.yaml", "project.example.yaml"): + d = yaml_lite.loads((base / f).read_text(encoding="utf-8")) + assert isinstance(d, dict) and d + assert yaml_lite.loads(yaml_lite.dumps(d)) == d + + +# ── term ──────────────────────────────────────────────────────────── +def test_term_width_counts_cjk_as_two() -> None: + assert dwidth("abc") == 3 + assert dwidth("成功") == 4 + assert dwidth("a成b") == 4 + assert dwidth("") == 0 + + +def test_term_width_ignores_ansi() -> None: + assert dwidth("\x1b[32mabc\x1b[0m") == 3 + assert dwidth("\x1b[97m成功\x1b[0m") == 4 + + +def test_term_truncate() -> None: + assert truncate("abcdef", 10) == "abcdef" + out = truncate("abcdef", 4) + assert dwidth(out) <= 4 + # 截断时会在末尾补 RESET,判定前先去掉 + assert out.replace("\x1b[0m", "").endswith("…") + assert dwidth(truncate("成功成功", 5)) <= 5 + + +def test_term_pad() -> None: + assert dwidth(pad("成功", 10)) == 10 + assert dwidth(pad("abc", 10)) == 10 + assert pad("abc", 10).endswith(" ") + + +def test_term_wrap_keeps_width() -> None: + lines = wrap("a" * 25, 10) + assert len(lines) == 3 + assert all(dwidth(x) <= 10 for x in lines) + lines = wrap("成功成功成功成功", 8) + assert all(dwidth(x) <= 8 for x in lines) + + +def _tmp_root() -> pathlib.Path: + return pathlib.Path(tempfile.mkdtemp(prefix="orn-unit-")) + + +def _legacy_project(root: pathlib.Path, queue: list[dict] | None = None) -> None: + """造一个老布局的项目:队列写在项目根的 overnight-runner.yaml。""" + (root / ".overnight-runner").mkdir(parents=True, exist_ok=True) + cfg = { + "runner": { + "agent": {"command": "opencode", "args": ["run"], "env": {}}, + "watchdog": {"maxRetries": 1, "backoffSec": 0}, + }, + "queue": queue if queue is not None else [ + {"id": "t1", "plan": "docs/plans/p1.md", "priority": 10} + ], + } + (root / "overnight-runner.yaml").write_text( + yaml_lite.dumps(cfg), encoding="utf-8" + ) + + +# ── 多队列:路径与迁移 ────────────────────────────────────────────── +def test_queue_paths_resolution() -> None: + root = _tmp_root() + p = queue_paths(root, "alice") + assert p.dir == root / ".overnight-runner" / "queue" / "alice" + assert p.config.name == "queue.yaml" + assert p.state.name == "state.json" + assert p.logs.name == "logs" + assert p.decisions.name == "decisions.jsonl" + assert p.lock.name == ".lock" + # 默认队列名 + assert queue_paths(root).name == "default" + + +def test_queue_name_rejected() -> None: + root = _tmp_root() + for bad in ("", "..", "../evil", "a/b", ".hidden", "名字"): + try: + queue_paths(root, bad) + except ValueError: + continue + raise AssertionError(f"队列名 {bad!r} 应该被拒绝") + + +def test_legacy_queue_migrated() -> None: + root = _tmp_root() + _legacy_project(root) + note = migrate_legacy_queue(root) + assert note, "应该给出迁移说明" + paths = queue_paths(root, "default") + assert paths.config.exists(), "队列定义应搬到 queue/default/queue.yaml" + defs = load_queue_defs(paths) + assert len(defs) == 1 and defs[0]["id"] == "t1" + # 根配置里的 queue: 段被清空 + data = yaml_lite.loads((root / "overnight-runner.yaml").read_text(encoding="utf-8")) + assert not data.get("queue"), "根配置的 queue 段应被清空" + # runner 段还在 + assert data["runner"]["agent"]["command"] == "opencode" + + +def test_legacy_migration_is_idempotent() -> None: + root = _tmp_root() + _legacy_project(root) + migrate_legacy_queue(root) + paths = queue_paths(root, "default") + paths.config.write_text( + yaml_lite.dumps({"queue": [{"id": "new", "plan": "docs/plans/p2.md"}]}), + encoding="utf-8", + ) + migrate_legacy_queue(root) + migrate_legacy_queue(root) + defs = load_queue_defs(paths) + assert len(defs) == 1 and defs[0]["id"] == "new", "重复迁移不能覆盖已有队列" + + +def test_legacy_state_and_decisions_migrated() -> None: + root = _tmp_root() + _legacy_project(root) + legacy = root / ".overnight-runner" + (legacy / "state.json").write_text( + json.dumps( + { + "updated_at": "2026-11-06T00:00:00+08:00", + "tasks": [ + {"id": "t1", "status": "success", "attempts": 1}, + ], + } + ), + encoding="utf-8", + ) + (legacy / "decisions.jsonl").write_text( + json.dumps({"task_id": "t1", "question": "q", "answer": "a"}) + "\n", + encoding="utf-8", + ) + migrate_legacy_queue(root) + paths = queue_paths(root, "default") + assert paths.state.exists(), "state.json 应搬到队列目录" + assert not (legacy / "state.json").exists(), "旧文件应被移走而不是复制" + assert paths.decisions.exists() + q = load_queue(paths, load_queue_defs(paths)) + assert q.get("t1") is not None and q.get("t1").status == SUCCESS + + +def test_migration_preserves_comments() -> None: + """迁移不能把用户写在配置里的注释弄丢。""" + root = _tmp_root() + (root / ".overnight-runner").mkdir(parents=True, exist_ok=True) + (root / "overnight-runner.yaml").write_text( + "# 头部注释\n" + "runner:\n" + " agent:\n" + " command: opencode # 保留我\n" + "queue:\n" + " - id: t1\n" + " plan: docs/plans/p1.md\n" + "\n" + "# 末尾的注释也要留\n", + encoding="utf-8", + ) + migrate_legacy_queue(root) + text = (root / "overnight-runner.yaml").read_text(encoding="utf-8") + assert "# 头部注释" in text, text + assert "# 保留我" in text, text + assert "# 末尾的注释也要留" in text, text + assert "queue:" not in text, text + # runner 段还在 + assert yaml_lite.loads(text)["runner"]["agent"]["command"] == "opencode" + + +def test_strip_queue_section_variants() -> None: + from overnight_runner.config import strip_queue_section + + # 块序列在中间 + text = "a: 1\nqueue:\n - id: x\nb: 2\n" + out = strip_queue_section(text) + assert "queue" not in out and "a: 1" in out and "b: 2" in out, out + # 内联写法 + out2 = strip_queue_section("a: 1\nqueue: []\nb: 2\n") + assert "queue: []" in out2 and "a: 1" in out2, out2 + # 没有 queue 段 —— 原样返回 + out3 = strip_queue_section("a: 1\n# 注释\n") + assert out3 == "a: 1\n# 注释\n", out3 + + +def test_migration_on_fresh_project() -> None: + root = _tmp_root() + assert migrate_legacy_queue(root) == "" + paths = queue_paths(root, "default") + assert load_queue_defs(paths) == [] + + +def test_queues_are_isolated() -> None: + root = _tmp_root() + a = queue_paths(root, "a") + b = queue_paths(root, "b") + for p in (a, b): + p.dir.mkdir(parents=True, exist_ok=True) + qa = load_queue(a, load_queue_defs(a)) + qb = load_queue(b, load_queue_defs(b)) + qa.add(build_task(root, "docs/plans/a.md")) + qb.add(build_task(root, "docs/plans/b.md")) + save_queue_defs(a, qa) + save_queue_defs(b, qb) + assert len(load_queue_defs(a)) == 1 + assert len(load_queue_defs(b)) == 1 + assert load_queue_defs(a)[0]["plan"] == "docs/plans/a.md" + assert load_queue_defs(b)[0]["plan"] == "docs/plans/b.md" + assert queue_names(root) == ["a", "b"] + # 状态也隔离 + save_state(a, qa) + assert a.state.exists() and not b.state.exists() + + +# ── 决策 ──────────────────────────────────────────────────────────── +def test_should_ask_unattended() -> None: + assert should_ask(DECISION_MODE_UNATTENDED) is False + + +def test_should_ask_attended() -> None: + assert should_ask(DECISION_MODE_ATTENDED) is True + + +def test_mode_override_from_cli() -> None: + cfg = RunnerConfig() + cfg.decision.mode = DECISION_MODE_ATTENDED + assert resolve_decision_mode(cfg, None, False) == DECISION_MODE_ATTENDED + assert resolve_decision_mode(cfg, DECISION_MODE_UNATTENDED, False) == ( + DECISION_MODE_UNATTENDED + ) + + +def test_headless_forces_unattended() -> None: + cfg = RunnerConfig() + cfg.decision.mode = DECISION_MODE_ATTENDED + assert resolve_decision_mode(cfg, None, True) == DECISION_MODE_UNATTENDED + assert resolve_decision_mode(cfg, DECISION_MODE_ATTENDED, True) == ( + DECISION_MODE_UNATTENDED + ) + + +def test_decision_config_defaults() -> None: + cfg = DecisionConfig() + assert cfg.mode == DECISION_MODE_ATTENDED + assert cfg.timeout_sec == 600 + assert cfg.resume == "session" + assert cfg.output_format == "json" + assert cfg.session_args == ["--session", "{session}"] + # 从配置文件读也是同一套默认值 + parsed = DecisionConfig.from_dict({}) + assert parsed.mode == DECISION_MODE_ATTENDED and parsed.timeout_sec == 600 + + +def test_session_id_from_json_event() -> None: + line = json.dumps( + { + "type": "text", + "sessionID": "ses_abc123", + "part": {"type": "text", "text": "QUESTION: 要改吗?"}, + } + ) + lines, sid = parse_agent_output(line, "json") + assert sid == "ses_abc123" + assert lines == ["QUESTION: 要改吗?"] + + +def test_session_id_from_text_fallback() -> None: + pattern = r'"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"' + line = '{"sessionID":"ses_xyz789"}' + assert extract_session_id(line, pattern) == "ses_xyz789" + assert extract_session_id("没有 session 的行", pattern) == "" + assert extract_session_id("x", "") == "" + + +def test_session_args_placeholder() -> None: + cfg = DecisionConfig() + assert cfg.session_command("ses_1") == ["--session", "ses_1"] + cfg2 = DecisionConfig(session_args=["-s", "{session}", "--x"]) + assert cfg2.session_command("ses_2") == ["-s", "ses_2", "--x"] + + +def test_resolve_answer_fallback() -> None: + pcfg = ProjectConfig(on_unknown_decision="跳过并记录") + answer, rule_id = resolve_answer(pcfg, "完全没听过的问题") + assert answer == "跳过并记录" + assert rule_id == "" + + +def test_resolve_answer_rule() -> None: + pcfg = ProjectConfig( + on_unknown_decision="跳过并记录", + decisions=[ + DecisionRule(id="db", match="数据库迁移", answer="先写回滚脚本") + ], + ) + answer, rule_id = resolve_answer(pcfg, "要不要执行数据库迁移脚本?") + assert answer == "先写回滚脚本" + assert rule_id == "db" + + +def test_decision_record_has_new_fields() -> None: + from overnight_runner.decisions import DecisionEvent + + rec = DecisionEvent( + task_id="t1", + question="q", + answer="a", + source="human", + waited_sec=12.34, + session_id="ses_1", + ).to_record() + assert rec["source"] == "human" + assert rec["waited_sec"] == 12.3 + assert rec["session_id"] == "ses_1" + + +# ── 队列锁 ────────────────────────────────────────────────────────── +def test_lock_rejects_live_pid() -> None: + root = _tmp_root() + lock = QueueLock(root / ".lock") + ok, err = lock.acquire() + assert ok, err + # 另一个锁指向自己(活着的 pid) + other = QueueLock(root / ".lock") + ok2, err2 = other.acquire() + assert not ok2 and "占用" in err2 + lock.release() + # 释放后能再拿 + ok3, _ = other.acquire() + assert ok3 + other.release() + + +def test_lock_cleans_stale() -> None: + root = _tmp_root() + path = root / ".lock" + path.write_text(json.dumps({"pid": 999999999, "heartbeat": 0}), encoding="utf-8") + lock = QueueLock(path) + ok, err = lock.acquire() + assert ok, f"stale 锁应被清理: {err}" + assert json.loads(path.read_text(encoding="utf-8"))["pid"] == os.getpid() + lock.release() + + +# ── 既有缺陷 B2 / B3 ──────────────────────────────────────────────── +def test_task_id_has_no_double_date() -> None: + root = _tmp_root() + t = build_task(root, "docs/plans/20261106-fix-something.md") + assert t.id == "20261106-fix-something", t.id + assert not t.id.startswith("20261106-20261106"), t.id + # 冲突时加序号 + t2 = build_task(root, "docs/plans/20261106-fix-something.md", existing_ids={t.id}) + assert t2.id == "20261106-fix-something-2" + + +def test_running_task_duration_does_not_crash() -> None: + """任务在跑(没有 finished_at)时算耗时不许炸。 + + 这是个既有缺陷:`duration_sec` 用了 `now()` 但没 import, + 只要队列里有"running"状态的任务,`list` 就会崩。 + """ + root = _tmp_root() + paths = queue_paths(root, "default") + paths.dir.mkdir(parents=True, exist_ok=True) + q = load_queue(paths, [{"id": "t1", "plan": "docs/plans/p1.md"}]) + task = q.get("t1") + task.started_at = datetime(2026, 11, 6, 10, 0, 0, tzinfo=timezone(timedelta(hours=8))) + task.finished_at = None + assert task.duration_sec is not None and task.duration_sec >= 0 + # 状态文件里写了不带时区的时间,也不许炸 + task.started_at = datetime(2026, 11, 6, 10, 0, 0) + assert task.duration_sec is not None + + +# ── 按键读取(UTF-8 多字节)────────────────────────────────────────── +def _keys_from_bytes(data: bytes) -> list[str]: + """把字节喂进管道当按键,按读出来的顺序返回按键序列。""" + from overnight_runner.keys import PosixKeyReader + + r, w = os.pipe() + os.write(w, data) + os.close(w) + reader = PosixKeyReader() + out: list[str] = [] + while True: + key = reader.read_key(r) + if key == "": + break + out.append(key) + os.close(r) + return out + + +def test_key_reader_decodes_chinese() -> None: + """中文必须原样读出来。 + + 这是个既有缺陷:老实现一次只读 1 字节再解码, + 一个汉字的 3 个字节被拆成 3 次读、每次都失败 → 中文全变问号。 + """ + keys = _keys_from_bytes("先修 Bug\n".encode("utf-8")) + assert keys == ["先", "修", " ", "B", "u", "g", "enter"], keys + + +def test_key_reader_reassembles_split_utf8() -> None: + """一个汉字被拆到两次读里,也必须还原成完整的字。""" + import threading + import time + + from overnight_runner.keys import PosixKeyReader + + r, w = os.pipe() + raw = "中".encode("utf-8") + + def writer() -> None: + os.write(w, raw[:1]) + time.sleep(0.3) + os.write(w, raw[1:]) + os.close(w) + + t = threading.Thread(target=writer, daemon=True) + t.start() + reader = PosixKeyReader() + key = reader.read_key(r) + t.join(timeout=3) + os.close(r) + assert key == "中", repr(key) + + +def test_key_reader_handles_escape_sequences() -> None: + keys = _keys_from_bytes(b"\x1b[A\x1b[B\x1b[C\x1b[D") + assert keys == ["up", "down", "right", "left"], keys + + +def test_key_reader_single_escape() -> None: + """单独按 ESC(后面没有序列)要认成 esc。""" + keys = _keys_from_bytes(b"\x1b") + assert keys == ["esc"], keys + + +def test_key_reader_control_keys() -> None: + keys = _keys_from_bytes(b"\x7f\x03\t") + assert keys == ["backspace", "ctrl-c", "tab"], keys + + +def test_deleting_state_does_not_requeue() -> None: + root = _tmp_root() + paths = queue_paths(root, "default") + paths.dir.mkdir(parents=True, exist_ok=True) + q = load_queue(paths, [{"id": "t1", "plan": "docs/plans/p1.md"}]) + task = q.get("t1") + task.status = SUCCESS + save_state(paths, q) + assert paths.state.exists() + assert paths.state.with_name(paths.state.name + ".bak").exists() + # 误删 state.json —— 不该把已成功的任务重新排队 + paths.state.unlink() + q2 = load_queue(paths, load_queue_defs(paths) or [{"id": "t1", "plan": "docs/plans/p1.md"}]) + assert q2.get("t1").status == SUCCESS, "已成功的任务不该被重新排队" + + +def _run_all() -> int: + tests = [(k, v) for k, v in sorted(globals().items()) if k.startswith("test_")] + failures = [] + for name, fn in tests: + try: + fn() + print(f" ✔ {name}") + except Exception as exc: # noqa: BLE001 + failures.append((name, exc)) + print(f" ✘ {name}: {exc}") + print() + print(f"{len(tests) - len(failures)}/{len(tests)} 通过") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(_run_all()) diff --git a/scripts/verify.sh b/scripts/verify.sh new file mode 100755 index 0000000..5e008dc --- /dev/null +++ b/scripts/verify.sh @@ -0,0 +1,368 @@ +#!/usr/bin/env bash +# 一键验证本仓库。 +# +# 用法: +# ./scripts/verify.sh # 全部检查 +# ./scripts/verify.sh --fast # 跳过 overnight-runner 冒烟测试 +# +# 退出码:0 全绿,1 有失败。 + +set -uo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +FAST=0 +[ "${1:-}" = "--fast" ] && FAST=1 + +FAILED=0 +PASSED=0 + +ok() { PASSED=$((PASSED + 1)); printf ' \033[32m✔\033[0m %s\n' "$1"; } +bad() { FAILED=$((FAILED + 1)); printf ' \033[31m✘\033[0m %s\n' "$1"; } +skip() { printf ' \033[90m—\033[0m %s\n' "$1"; } +head_() { printf '\n\033[1m%s\033[0m\n' "$1"; } + +# ── 1. Bash 语法 ─────────────────────────────────────────────────── +head_ "1. Bash 语法" +while IFS= read -r f; do + if bash -n "$f" 2>/dev/null; then ok "$f"; else bad "$f"; bash -n "$f"; fi +done < <(find . -name "*.sh" -not -path "./.git/*" -not -path "*/.venv/*" -not -path "*/node_modules/*" | sort) + +# ── 2. Python 语法 ───────────────────────────────────────────────── +head_ "2. Python 语法" +PY="" +for c in python3 python; do + command -v "$c" >/dev/null 2>&1 && { PY="$c"; break; } +done +if [ -z "$PY" ]; then + skip "找不到 python" +else + while IFS= read -r f; do + if "$PY" -m py_compile "$f" 2>/dev/null; then ok "$f"; else bad "$f"; "$PY" -m py_compile "$f"; fi + done < <(find . -name "*.py" -not -path "./.git/*" -not -path "*/.venv/*" -not -path "*/node_modules/*" | sort) + find . -name "__pycache__" -type d -not -path "./.git/*" -exec rm -rf {} + 2>/dev/null +fi + +# ── 3. Node 语法 ─────────────────────────────────────────────────── +head_ "3. Node 语法" +if ! command -v node >/dev/null 2>&1; then + skip "找不到 node" +else + while IFS= read -r f; do + if node --check "$f" 2>/dev/null; then ok "$f"; else bad "$f"; node --check "$f"; fi + done < <(find . -name "*.mjs" -o -name "*.js" -not -path "./.git/*" -not -path "*/node_modules/*" | grep -v node_modules | sort) +fi + +# ── 4. JSON / YAML 可解析 ────────────────────────────────────────── +head_ "4. JSON / YAML 可解析" +if [ -n "$PY" ]; then + "$PY" - <<'PYEOF' +import json, pathlib, sys +import yaml + +bad = [] +files = [ + p for p in pathlib.Path('.').rglob('*') + if p.suffix in ('.json', '.jsonc', '.yaml', '.yml') + and '.git/' not in str(p) and '.venv/' not in str(p) + and 'node_modules' not in str(p) +] +for p in sorted(files): + try: + if p.suffix in ('.json', '.jsonc'): + json.loads(p.read_text(encoding='utf-8')) + else: + yaml.safe_load(p.read_text(encoding='utf-8')) + print(f' \033[32m✔\033[0m {p}') + except Exception as exc: + print(f' \033[31m✘\033[0m {p} — {exc}') + bad.append(p) +sys.exit(1 if bad else 0) +PYEOF + if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi +else + skip "找不到 python" +fi + +# ── 5. skill 名/目录一致、无重名 ─────────────────────────────────── +head_ "5. skill 名/目录一致、无重名" +if [ -n "$PY" ]; then + "$PY" - <<'PYEOF' +import collections, pathlib, re, sys + +seen = collections.Counter() +bad = [] +for md in sorted(pathlib.Path('.').rglob('SKILL.md')): + s = str(md) + if '.git/' in s or '.venv/' in s or 'node_modules' in s: + continue + m = re.search(r'^name:\s*(\S+)', md.read_text(encoding='utf-8'), re.M) + if not m: + print(f' \033[31m✘\033[0m {md} — 缺少 name') + bad.append(md) + continue + name = m.group(1) + seen[name] += 1 + if name != md.parent.name: + print(f' \033[31m✘\033[0m {md} — name={name} 与目录名 {md.parent.name} 不一致') + bad.append(md) +for name, n in seen.items(): + if n > 1: + print(f' \033[31m✘\033[0m 重名 skill: {name}({n} 处)') + bad.append(name) +if not bad: + print(f' \033[32m✔\033[0m {sum(seen.values())} 个 skill,名称与目录一致且无重名') +sys.exit(1 if bad else 0) +PYEOF + if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi +else + skip "找不到 python" +fi + +# ── 6. 清单 ↔ 模板 ↔ 已安装 三方一致 ────────────────────────────── +head_ "6. 清单 ↔ 模板 ↔ 已安装 一致" +if [ -n "$PY" ]; then + "$PY" - <<'PYEOF' +import json, pathlib, sys + +bad = [] +catalog_path = pathlib.Path('agile-team-sdd/catalog.json') +if not catalog_path.exists(): + print(' \033[31m✘\033[0m 缺 agile-team-sdd/catalog.json') + sys.exit(1) + +catalog = json.loads(catalog_path.read_text(encoding='utf-8')) +listed = {s['name'] for g in catalog.values() for s in g} + +tpl_root = pathlib.Path('agile-team-sdd/skills') +templates = {p.name.replace('-template', '') for p in tpl_root.iterdir() if p.is_dir()} + +installed_root = pathlib.Path('example-project/.agent/skills') +installed = {p.name for p in installed_root.iterdir() if p.is_dir()} if installed_root.exists() else set() + +if listed != templates: + print(f' \033[31m✘\033[0m 清单与模板不一致:{sorted(listed ^ templates)}') + bad.append('catalog/templates') +if listed != installed: + print(f' \033[31m✘\033[0m 清单与已安装不一致:{sorted(listed ^ installed)}') + bad.append('catalog/installed') +if not bad: + print(f' \033[32m✔\033[0m 三方一致({len(listed)} 个 skill)') +sys.exit(1 if bad else 0) +PYEOF + if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi +else + skip "找不到 python" +fi + +# ── 7. 占位符已登记 ─────────────────────────────────────────────── +head_ "7. 模板占位符已登记" +if [ -n "$PY" ]; then + "$PY" - <<'PYEOF' +import pathlib, re, sys + +used = set() +for f in pathlib.Path('agile-team-sdd/skills').rglob('*.md'): + used |= set(re.findall(r'\{\{([A-Z_]+)\}\}', f.read_text(encoding='utf-8'))) + +doc = pathlib.Path('agile-team-sdd/placeholders.md') +declared = set(re.findall(r'\{\{([A-Z_]+)\}\}', doc.read_text(encoding='utf-8'))) if doc.exists() else set() + +missing = sorted(used - declared) +if missing: + print(f' \033[31m✘\033[0m 未登记的占位符:{missing}') + sys.exit(1) +print(f' \033[32m✔\033[0m {len(used)} 个占位符全部已登记') +PYEOF + if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi +else + skip "找不到 python" +fi + +# ── 8. 已安装 skill 无残留占位符、无绝对路径 ─────────────────────── +head_ "8. 已安装 skill 无残留占位符 / 无绝对路径" +if [ -n "$PY" ]; then + "$PY" - <<'PYEOF' +import pathlib, re, sys + +root = pathlib.Path('example-project/.agent/skills') +bad = [] +files = sorted(root.rglob('*.md')) if root.exists() else [] +for f in files: + text = f.read_text(encoding='utf-8') + for ph in re.findall(r'\{\{[A-Z_]+\}\}', text): + print(f' \033[31m✘\033[0m {f} — 残留占位符 {ph}') + bad.append(f) + for m in re.findall(r'/(?:Users|home)/[^\s`"\')]+', text): + print(f' \033[31m✘\033[0m {f} — 泄漏绝对路径 {m}') + bad.append(f) +if not bad: + print(f' \033[32m✔\033[0m {len(files)} 个已安装文件干净') +sys.exit(1 if bad else 0) +PYEOF + if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi +else + skip "找不到 python" +fi + +# ── 9. Markdown 相对链接有效 ─────────────────────────────────────── +head_ "9. Markdown 相对链接有效" +if [ -n "$PY" ]; then + "$PY" - <<'PYEOF' +import pathlib, re, sys + +bad = [] +checked = 0 +for md in pathlib.Path('.').rglob('*.md'): + s = str(md) + if '.git/' in s or '.venv/' in s or 'node_modules' in s: + continue + text = md.read_text(encoding='utf-8') + for m in re.finditer(r'\[[^\]]*\]\(([^)]+)\)', text): + link = m.group(1).split('#')[0].strip() + if not link or link.startswith(('http://', 'https://', 'mailto:')): + continue + checked += 1 + if not (md.parent / link).resolve().exists(): + print(f' \033[31m✘\033[0m {md} → {link}') + bad.append(link) +if not bad: + print(f' \033[32m✔\033[0m {checked} 条相对链接全部有效') +sys.exit(1 if bad else 0) +PYEOF + if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi +else + skip "找不到 python" +fi + +# ── 10. overnight-runner 冒烟测试 ───────────────────────────────── +head_ "10. overnight-runner 测试" +if [ "$FAST" -eq 1 ]; then + skip "--fast 跳过" +elif [ -z "$PY" ]; then + skip "找不到 python" +else + # overnight-runner 零依赖,用系统 python 即可 + if "$PY" overnight-runner/tests/test_units.py > /tmp/orn-units.log 2>&1; then + tail -1 /tmp/orn-units.log | sed 's/^/ \033[32m✔\033[0m 单元测试 /' + PASSED=$((PASSED + 1)) + else + sed 's/^/ /' /tmp/orn-units.log + bad "单元测试" + fi + if "$PY" overnight-runner/tests/test_smoke.py > /tmp/orn-smoke.log 2>&1; then + tail -1 /tmp/orn-smoke.log | sed 's/^/ \033[32m✔\033[0m 冒烟测试 /' + PASSED=$((PASSED + 1)) + else + sed 's/^/ /' /tmp/orn-smoke.log + bad "冒烟测试" + fi +fi + +# ── 11. overnight-runner 队列布局 / 迁移 / 决策默认值 ─────────────── +head_ "11. overnight-runner 队列布局与决策默认值" +if [ "$FAST" -eq 1 ]; then + skip "--fast 跳过" +elif [ -z "$PY" ]; then + skip "找不到 python" +else + "$PY" - <<'PYEOF' +import pathlib, sys, tempfile + +sys.path.insert(0, str(pathlib.Path('overnight-runner').resolve())) +from overnight_runner import yaml_lite +from overnight_runner.config import ( + DECISION_MODES, + DECISION_MODE_ATTENDED, + DECISION_MODE_UNATTENDED, + DecisionConfig, + migrate_legacy_queue, + queue_names, + queue_paths, +) +from overnight_runner.queue import load_queue_defs + +bad = [] + +# 11.1 队列目录结构:常量与实际路径一致 +paths = queue_paths(pathlib.Path('/tmp/x'), 'alice') +expect = { + 'dir': '.overnight-runner/queue/alice', + 'config': '.overnight-runner/queue/alice/queue.yaml', + 'state': '.overnight-runner/queue/alice/state.json', + 'logs': '.overnight-runner/queue/alice/logs', + 'decisions': '.overnight-runner/queue/alice/decisions.jsonl', + 'lock': '.overnight-runner/queue/alice/.lock', +} +for attr, want in expect.items(): + got = getattr(paths, attr).as_posix().replace('/tmp/x/', '') + if got != want: + print(f' \033[31m✘\033[0m 队列路径 {attr}: {got} ≠ {want}') + bad.append(attr) + +# 11.2 决策模式默认值与合法取值 +cfg = DecisionConfig() +if cfg.mode != DECISION_MODE_ATTENDED: + print(f' \033[31m✘\033[0m 默认决策模式 {cfg.mode} ≠ attended') + bad.append('mode') +if cfg.timeout_sec != 600: + print(f' \033[31m✘\033[0m 默认决策窗口 {cfg.timeout_sec}s ≠ 600s') + bad.append('timeout') +if cfg.resume != 'session': + print(f' \033[31m✘\033[0m 默认续跑方式 {cfg.resume} ≠ session') + bad.append('resume') +if set(DECISION_MODES) != {DECISION_MODE_ATTENDED, DECISION_MODE_UNATTENDED}: + print(f' \033[31m✘\033[0m 决策模式取值应为 attended/unattended,实际 {DECISION_MODES}') + bad.append('modes') + +# 11.3 迁移幂等:连跑两次,队列不丢不重 +with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + (root / '.overnight-runner').mkdir(parents=True) + (root / 'overnight-runner.yaml').write_text( + yaml_lite.dumps({ + 'runner': {'agent': {'command': 'opencode', 'args': ['run']}}, + 'queue': [{'id': 't1', 'plan': 'docs/plans/p1.md'}], + }), + encoding='utf-8', + ) + migrate_legacy_queue(root) + migrate_legacy_queue(root) + p = queue_paths(root, 'default') + defs = load_queue_defs(p) + if len(defs) != 1 or defs[0].get('id') != 't1': + print(f' \033[31m✘\033[0m 迁移后队列内容不对: {defs}') + bad.append('migrate') + if queue_names(root) != ['default']: + print(f' \033[31m✘\033[0m 迁移后队列名不对: {queue_names(root)}') + bad.append('migrate-names') + raw = yaml_lite.loads((root / 'overnight-runner.yaml').read_text(encoding='utf-8')) + if raw.get('queue'): + print(' \033[31m✘\033[0m 迁移后根配置的 queue 段没清空') + bad.append('migrate-clear') + +# 11.4 .gitignore 排除了队列运行时产物 +gi = pathlib.Path('.gitignore').read_text(encoding='utf-8') +for pat in ('**/.overnight-runner/queue/*/state.json', + '**/.overnight-runner/queue/*/logs/', + '**/.overnight-runner/queue/*/.lock'): + if pat not in gi: + print(f' \033[31m✘\033[0m .gitignore 缺 {pat}') + bad.append('gitignore') + +if not bad: + print(' \033[32m✔\033[0m 队列布局、迁移幂等、决策默认值一致') +sys.exit(1 if bad else 0) +PYEOF + if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi +fi + +# ── 汇总 ─────────────────────────────────────────────────────────── +printf '\n\033[1m%s\033[0m\n' "────────────────────────────" +if [ "$FAILED" -eq 0 ]; then + printf '\033[32m全部通过\033[0m(%s 项)\n' "$PASSED" + exit 0 +fi +printf '\033[31m失败 %s 项\033[0m(通过 %s 项)\n' "$FAILED" "$PASSED" +exit 1 diff --git a/team-workflow-guide/README.md b/team-workflow-guide/README.md new file mode 100644 index 0000000..e21bf8f --- /dev/null +++ b/team-workflow-guide/README.md @@ -0,0 +1,17 @@ +# 团队 AI 编程工作流指南 + +本目录以 **HTML 单页** 为主文档(便于预览矩阵图与排版): + +**→ 打开 [`index.html`](index.html)**(浏览器或 IDE 简易预览) + +内容覆盖: + +0. 总览矩阵(人 / AI 动作 / skill / 输入 / 输出) +1. 项目准备(TL 装机定规) +2. 迭代前:BA 规格+原型 · TL 高阶 TRD · QA 用例(并行) +3. 迭代中:DEV 写 Plan → 实现 · QA 验收 · TL 发布 / PM 复盘 +4. 测试分层与归属 +5. 角色手册(BA / PM / TL / DEV / QA / AI) +6. Skill 对照 + +规范硬约束仍在各项目的 `AGENTS.md`。本指南讲 **人怎么配合**。 diff --git a/team-workflow-guide/index.html b/team-workflow-guide/index.html new file mode 100644 index 0000000..0a289b3 --- /dev/null +++ b/team-workflow-guide/index.html @@ -0,0 +1,990 @@ + + + + + +团队 AI 编程工作流指南 + + + +
+ +
+

团队 AI 编程工作流指南

+

团队级协作手册:项目怎么准备、迭代前怎么设计、迭代中怎么开发。规范硬约束在项目 AGENTS.md;本页讲人怎么配合,AI 只做执行。

+ +
+ +
+

0. 团队工作流程

+

一张图看清:谁在哪个阶段、用什么 skill、吃什么输入、吐什么产物。

+

原则:人做决策,AI 做执行。规格确认后,TL 高阶技术方案与 QA 文本用例可并行;迭代中由 DEV 编写 Plan 再实现。

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
人AI 驱动动作工具和技能输入输出物
项目准备TL装机与定规 +
    +
  • 初始化 harness 与 docs 骨架
  • +
  • 安装 SDD skill 与 MCP 工具链
  • +
  • 定架构边界、标准与 CI 闸门
  • +
+
+
harness-installer
+
agile-team-sdd
+
tool-chain-installer
+
+
    +
  • 空项目 / 存量仓库
  • +
  • 团队技术选型
  • +
+
+
    +
  • AGENTS.md + docs/
  • +
  • .agent/skills/
  • +
  • MCP 配置、测试闸门约定
  • +
+
BA / PM定方向 +
    +
  • 对齐业务目标与首迭范围
  • +
  • 定迭代节奏
  • +
+
—业务背景、干系人预期迭代目标一页纸
迭代前BA规格 + 原型 +
    +
  • 拷问需求,消除歧义
  • +
  • 落需求规格:字段、规则、权限、验收
  • +
  • 输出 HTML 原型图
  • +
+
+
ba-grill-me
+
ba-write-spec
+
pm-estimate(配合 PM)
+
一句话需求 / 访谈材料 +
    +
  • docs/features/iteration[n]/*.md
  • +
  • docs/features/iteration[n]/prototypes/ 原型图
  • +
  • 编号 R-xxx / AC-xxx
  • +
+
TL高阶方案 ★ +
    +
  • 需求 Review
  • +
  • 编写高阶技术方案(TRD)+ Review
  • +
+
自定义工具 +
    +
  • iteration[n]/*.md 规格
  • +
  • 原型图
  • +
  • 现有 designs / 架构边界
  • +
+
+
    +
  • TRD 文件
  • +
  • 技术边界与取舍
  • +
+
QA用例(并行) +
    +
  • 按 AC/R 写 QA 文本用例
  • +
  • 与 TRD 并行,规格确认后即可开始
  • +
+
+
qa-write-cases
+
+
    +
  • iteration[n]/*.md 中的 AC / R
  • +
  • 原型图(辅助)
  • +
+
+
    +
  • docs/test-cases/e2e-cases/(验收)
  • +
  • 编号 TC-xxx 映射表
  • +
+
迭代中DEVPlan + 实现 +
    +
  • 编写 Plan(对照 TRD / 规格)★确认
  • +
  • dev-build 循环:实现 ↔ 自测直至通过
  • +
  • UI / 代码评审、更新事实文档、开 MR
  • +
+
+
dev-plan
+
dev-build(含自测循环)
+
dev-ui-review / dev-code-review
+
ba-gen-facts · dev-create-mr
+
overnight-runner(可选)
+
+
    +
  • TRD + 规格 + 原型图
  • +
  • TC 文本基线
  • +
+
+
    +
  • docs/plans/YYYYMMDD-*.md
  • +
  • 业务代码 + 开发自测
  • +
  • 更新后的事实文档、MR / PR
  • +
+
QA验收 ★ +
    +
  • 跑 E2E 验收 + 文本勾选
  • +
  • 手工 / 冒烟补测
  • +
+
+
qa-run-e2e
+
qa-write-manual-plan
+
+
    +
  • 实现产物
  • +
  • TC 文本用例
  • +
+
+
    +
  • 验收结论(合并闸门)
  • +
  • E2E / 手动 / 冒烟报告
  • +
+
TL / PM发布与复盘 +
    +
  • 上线清单(DB 单独评估)
  • +
  • 复盘并把改进回写 harness
  • +
+
+
dev-release-plan
+
pm-retro
+
已合并变更 + 验收记录 +
    +
  • docs/releases/
  • +
  • harness 改进项(可验证)
  • +
+
+
+ +
+ 项目准备 + 迭代前 + 迭代中 +
+
+ ★ TRD 确认 · 迭代前 + ★ Plan 确认 · 编码前(DEV) + ★ QA 验收 · 合并前 +
+
+ +
+

1. 项目准备

+

目标:项目「可被 harness 管理」——规范、目录、工具齐。

+

协作口诀:TL 装机与定规矩,QA 定闸门,BA 定方向。规矩未定不进迭代。

+ +

1.1 谁做什么

+ + + + + + + + + + +
步骤主责产物
初始化 AGENTS.md + docs/TLAGENTS.md、docs/**
安装 SDD skillTL.agent/skills/
安装 MCPTL.mcp.json / opencode.jsonc
定架构与标准TLdocs/standards/、docs/designs/
定测试闸门QA + TLtest:qa 进 CI
业务目标与首迭范围BA / PM迭代目标一页纸
+ +

1.2 接入顺序

+

全部交给 AI Agent 按 skill 执行,人只确认目标项目路径与关键决策。顺序不能变:

+
    +
  1. + 铺 harness — 对 Agent 说:用 harness-installer 给目标项目初始化 AGENTS.md 与 docs/ 骨架。
    + 完成后由 TL 补全 AGENTS.md 里的业务 / 架构 TODO(Agent 可起草,人必须拍板)。 +
  2. +
  3. + 装 SDD skills — 对 Agent 说:用 agile-team-sdd 把 16 个流程 skill 安装到目标项目的 .agent/skills/。 +
  4. +
  5. + 装 MCP 工具链 — 对 Agent 说:用 tool-chain-installer 把 MCP 配置写入项目(如 .mcp.json / opencode.jsonc)。 +
  6. +
  7. + (可选)装 overnight-runner — 需要夜跑 Plan 时,再让 Agent 安装并写好队列配置。 +
  8. +
+
装完 skill / MCP 后必须重启 opencode(或等价 IDE Agent),配置才生效。不要跳步:先有 AGENTS.md 与 docs/,再装 skills,路径才指向真实目录。
+ +

1.3 出口条件

+
    +
  • AGENTS.md 关键 TODO 已填
  • +
  • skill + MCP 可用
  • +
  • 文档树与测试归属约定写清
  • +
  • 团队对齐三条铁律(规范先于代码 / 测试先于实现 / 文档同批次)
  • +
+
+ +
+

2. 迭代前方案设计

+

目标:进开发前,业务与技术都「可测、可估、可确认」。

+ +

2.1 流水线

+ +

规格与原型落在 docs/features/iteration[n]/。TRD 未确认不得进入迭代中写 Plan;QA 文本用例未齐不得声称有验收基线。

+ +

2.2 交接

+ + + + + + + +
从 → 到交出什么
BA → TL / QA / DEViteration[n]/*.md 规格 + 原型图 + 范围边界 + AC/R
TL → DEV已确认 TRD(技术边界与取舍)
QA → DEVTC 映射表(自动化可代写)
+ +

2.3 可进入迭代中 DoR

+
    +
  • 本迭规格已确认(docs/features/iteration[n]/*.md,R / AC 齐)
  • +
  • 本迭原型图已输出(docs/features/iteration[n]/prototypes/)
  • +
  • TRD 已人工确认
  • +
  • 本迭 TC 文本用例齐,且映射到 AC/R
  • +
+
+ +
+

3. 迭代中开发

+

目标:DEV 先写 Plan(对照 TRD),确认后再实现;经自测与 QA 验收后合并、可发布;复盘回写 harness。

+ +

3.1 流水线

+ +
Plan 未确认不得写实现。overnight-runner 只跑已确认的 Plan;不做 Plan / TRD 闸门本身。
+ +

3.2 并行边界

+
    +
  • 多 DEV 可并行,契约以已确认 Plan + api.yaml 为准(并服从 TRD 边界)
  • +
  • QA 自动化可由 DEV 代写,勾选与放行权在 QA
  • +
  • 自测绿 ≠ 可合;QA 过 ≠ 可忽略自测红
  • +
  • 规格外行为 = 缺陷(除非 BA 认可)
  • +
+ +

3.3 Definition of Done

+
    +
  • Plan 已确认且按 Plan 实现
  • +
  • 每条 AC / R 都有对应 QA 用例且通过;文本用例勾选完毕
  • +
  • 开发自测全绿;关键 API 覆盖 Happy Path + 失败分支
  • +
  • 事实文档已更新;无遗留 TODO / 调试代码
  • +
  • 上线清单完成(TL);复盘改进已回写 harness(PM)
  • +
+
+ +
+

4. 测试分层与归属

+

开发自测对「我写的代码」负责;QA 测试对「需求有没有被实现」负责。

+ + + + + + + + + + + + +
维度开发自测QA 测试
验证什么代码按 Plan 工作系统符合需求规格
判定人开发本人QA
编号无TC-xxx
位置源码旁、e2e/tests/dev/docs/、e2e/tests/qa/
合并闸门否是
+ +

编号映射:每条 R-xxx、AC-xxx 至少对应一条 TC-xxx。

+
+ +
+

5. 角色手册(速查)

+ +
+

BA · 业务分析

+

让开发不需要猜就能开始做。规格写「做什么」,不写表名/SQL;同步输出 HTML 原型图。本迭产物放在 docs/features/iteration[n]/。

+
+ ba-grill-meba-write-spec +
+
+ +
+

PM · 项目经理

+

估算有据;复盘必须落到可验证的 harness 文件改动。

+
+ pm-estimatepm-retro +
+
+ +
+

TL · 技术负责人

+

装机定规;迭代前写高阶技术方案(TRD)并确认;迭代中做代码评审与发布清单。工具链与密钥不落盘也归 TL。

+
+ dev-code-reviewba-gen-factsdev-release-plan +
+
+ +
+

DEV · 开发

+

迭代中先写 Plan(对照 TRD / 规格),确认后再实现与自测。复用现有模式,不自创;自测不写 TC 编号。

+
+ dev-plandev-builddev-ui-reviewdev-debug +
+
+ +
+

QA · 测试

+

定义与判定权归 QA。先文本用例,再自动化;不过不能合。

+
+ qa-write-casesqa-run-e2eqa-write-manual-plan +
+
+ +
+

AI Agent

+

可靠执行者,不是打字机。需求/规范有歧义 → 停下来问。不把「自测全绿」写成「需求已满足」。

+
+
+ +
+

6. Skill 与步骤对照

+ + + + + + + + + + + + + + + + + + +
步骤阶段skill产出
拷问§2ba-grill-me澄清纪要
写规格 + 原型§2ba-write-specdocs/features/iteration[n]/*.md + prototypes/
估算§2pm-estimate点数与人日
高阶技术方案§2自定义 / TRDTRD(人工确认)
QA 文本用例§2 并行qa-write-casesdocs/test-cases/e2e-cases/
手动 / 冒烟§3qa-write-manual-plandocs/test-cases/manual-cases/ · smoking-cases/
开发自测索引§3dev-builddocs/test-cases/dev-self-cases/(可选)
写 Plan§3dev-plandocs/plans/(人工确认)
实现(含自测循环)§3dev-build代码 + 自测通过
评审 / 更新事实文档§3dev-code-review / ba-gen-facts意见 + 事实文档
开 MR§3dev-create-mrMR / PR
验收§3qa-run-e2e验收报告
上线§3dev-release-plandocs/releases/
复盘§3pm-retro改进 → harness
+
+ +
+ team-workflow-guide · 打开本文件即可预览 · 规范细节见各项目 AGENTS.md +
+ +
+ + diff --git a/tool-chain-installer/README.md b/tool-chain-installer/README.md new file mode 100644 index 0000000..72ad366 --- /dev/null +++ b/tool-chain-installer/README.md @@ -0,0 +1,51 @@ +# tool-chain-installer + +把 MCP 工具链写进项目配置,**不依赖开发机的全局状态**。 + +``` +tool-chain-installer/ +├── SKILL.md +├── scripts/install-tools.mjs +└── catalog/mcp-catalog.json # 工具清单(可自行扩展) +``` + +## 用法 + +```bash +# 看清单 +node tool-chain-installer/scripts/install-tools.mjs --list + +# 装浏览器 + 上下文工具 +node tool-chain-installer/scripts/install-tools.mjs ../my-project --group browser --group context + +# 按名称 +node tool-chain-installer/scripts/install-tools.mjs ../my-project --tools chrome-devtools,playwright + +# 全部 + 预览 +node tool-chain-installer/scripts/install-tools.mjs ../my-project --all --dry-run +``` + +## 写入位置 + +| 文件 | 键名 | 适用 | +|---|---|---| +| `.mcp.json` | `mcpServers` | Claude Code / 通用 MCP 客户端 | +| `opencode.jsonc` | `mcp` | opencode 原生格式 | + +两个文件默认都写(`--format both`)。已有配置会被 **合并**,其他字段保留。 + +## 现有工具 + +| 分组 | 工具 | 用途 | +|---|---|---| +| browser | `chrome-devtools` | 调试:导航 / 截图 / 控制台 / 网络 / 性能 | +| browser | `playwright` | 浏览器自动化 | +| context | `context7` | 拉最新官方文档 | +| context | `sequential-thinking` | 结构化推理 | +| data | `filesystem` | 限定目录文件读写 | +| data | `git` | 仓库历史 / 分支 / diff | +| observability | `sentry` | 线上错误排查(需 `SENTRY_TOKEN`) | + +## 扩展 + +编辑 `catalog/mcp-catalog.json` 加一项即可,脚本自动读取。 diff --git a/tool-chain-installer/SKILL.md b/tool-chain-installer/SKILL.md new file mode 100644 index 0000000..dd94ff6 --- /dev/null +++ b/tool-chain-installer/SKILL.md @@ -0,0 +1,97 @@ +--- +name: tool-chain-installer +description: 安装 MCP 工具链(chrome-devtools / playwright / context7 / sequential-thinking / filesystem / git / sentry 等)到指定项目。当用户说"装 MCP"、"安装工具链"、"配置 chrome-devtools"、"把 playwright 装上"、"tool chain 安装"时使用。 +--- + +# 工具链安装器 + +把 MCP 工具链写进项目配置,**不依赖开发机的全局状态** —— 换一台机器 clone 下来就能跑。 + +## 可用工具 + +| 分组 | 工具 | 用途 | 谁用 | +|---|---|---|---| +| `browser` | `chrome-devtools` | 页面导航、截图、无障碍树、控制台、网络、性能追踪 | `dev-debug` | +| `browser` | `playwright` | 跨浏览器自动化、截图、表单填写 | `dev-debug`、QA | +| `context` | `context7` | 拉取框架/库的最新官方文档 | `dev-build` | +| `context` | `sequential-thinking` | 结构化推理,拆解复杂任务 | `dev-plan` | +| `data` | `filesystem` | 限定目录范围内的文件读写 | 通用 | +| `data` | `git` | 查询仓库历史、分支、diff | 通用 | +| `observability` | `sentry` | 线上错误排查(需 `SENTRY_TOKEN`) | `dev-debug` | + +完整清单以 [`catalog/mcp-catalog.json`](catalog/mcp-catalog.json) 为准,脚本会读取它。 + +## 执行 + +```bash +# 查看全部可用工具 +node tool-chain-installer/scripts/install-tools.mjs --list + +# 按分组安装 +node tool-chain-installer/scripts/install-tools.mjs <目标项目目录> --group browser --group context + +# 按名称安装 +node tool-chain-installer/scripts/install-tools.mjs <目标项目目录> --tools chrome-devtools,playwright + +# 全部安装 +node tool-chain-installer/scripts/install-tools.mjs <目标项目目录> --all + +# 先预览 +node tool-chain-installer/scripts/install-tools.mjs <目标项目目录> --all --dry-run +``` + +| 参数 | 说明 | +|---|---| +| `--tools ` | 按名称安装 | +| `--group ` | 按分组安装,可重复 | +| `--all` | 安装全部 | +| `--dry-run` | 只打印将要发生的改动 | +| `--format ` | `both`(默认) \| `mcp-json` \| `opencode` | + +## 写入哪些文件 + +| 文件 | 写入位置 | 用途 | +|---|---|---| +| `.mcp.json` | `mcpServers..{command,args,env}` | Claude Code / 通用 MCP 客户端 | +| `opencode.jsonc` | `mcp..{type,command,enabled,environment}` | opencode 原生格式 | + +脚本会 **合并** 进已有配置,不会覆盖 `skills` 等其他字段;同名工具以本次配置为准。 + +## 密钥处理 + +需要密钥的工具(如 `sentry`)在配置里写占位引用,**不要把真值写进仓库**: + +```json +{ "env": { "SENTRY_TOKEN": "{env:SENTRY_TOKEN}" } } +``` + +开发者自行 `export SENTRY_TOKEN=xxx`。opencode 配置里用 `{env:VAR}`,MCP 的 `env` 字段里同样用 `{env:VAR}`。 + +## 加一个新工具 + +编辑 `catalog/mcp-catalog.json`,在对应分组里加一项: + +```json +{ + "name": "my-tool", + "description": "一句话说明", + "package": "my-mcp@1.2.3", + "command": "npx", + "args": ["-y", "my-mcp@1.2.3"], + "env": {}, + "usedBy": ["dev-build"] +} +``` + +`package` 只是给人看的说明,真正生效的是 `command` + `args`。 + +## 注意 + +- MCP 配置在 opencode **启动时加载,不热更新** —— 装完必须重启 opencode。 +- `npx -y @latest` 每次启动都会检查 registry,离线环境会失败;内网请改用固定版本 + 本地安装。 +- 装完在项目里记一笔:`docs/standards/toolchain.md`,方便交接。 + +## 相关 + +- `agile-team-sdd/` — `dev-debug` 依赖本目录装的 `chrome-devtools` +- `harness-installer/` — 装 MCP 之前应先铺好 `AGENTS.md` 与 `docs/` diff --git a/tool-chain-installer/catalog/mcp-catalog.json b/tool-chain-installer/catalog/mcp-catalog.json new file mode 100644 index 0000000..78414d2 --- /dev/null +++ b/tool-chain-installer/catalog/mcp-catalog.json @@ -0,0 +1,73 @@ +{ + "browser": [ + { + "name": "chrome-devtools", + "description": "Chrome DevTools MCP:页面导航、截图、无障碍树、控制台、网络请求、性能追踪", + "package": "chrome-devtools-mcp@latest", + "command": "npx", + "args": ["-y", "chrome-devtools-mcp@latest"], + "env": {}, + "usedBy": ["dev-debug"] + }, + { + "name": "playwright", + "description": "Playwright MCP:跨浏览器自动化操作、截图、表单填写", + "package": "@playwright/mcp@latest", + "command": "npx", + "args": ["-y", "@playwright/mcp@latest", "--browser", "chromium"], + "env": {}, + "usedBy": ["dev-debug", "qa"] + } + ], + "context": [ + { + "name": "context7", + "description": "Context7:拉取框架/库的最新版官方文档", + "package": "context7-mcp@latest", + "command": "npx", + "args": ["-y", "context7-mcp@latest"], + "env": {}, + "usedBy": ["dev-build"] + }, + { + "name": "sequential-thinking", + "description": "Sequential Thinking MCP:结构化推理,拆解复杂任务", + "package": "@modelcontextprotocol/server-sequential-thinking@latest", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-sequential-thinking@latest"], + "env": {}, + "usedBy": ["dev-plan"] + } + ], + "data": [ + { + "name": "filesystem", + "description": "Filesystem MCP:限定目录范围内的文件读写", + "package": "@modelcontextprotocol/server-filesystem@latest", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem@latest", "."], + "env": {}, + "usedBy": [] + }, + { + "name": "git", + "description": "Git MCP:查询仓库历史、分支、diff", + "package": "mcp-server-git@latest", + "command": "uvx", + "args": ["mcp-server-git", "--repository", "."], + "env": {}, + "usedBy": [] + } + ], + "observability": [ + { + "name": "sentry", + "description": "Sentry MCP:线上错误与性能问题排查(需 SENTRY_TOKEN)", + "package": "mcp-remote", + "command": "npx", + "args": ["-y", "mcp-remote", "https://mcp.sentry.dev/mcp"], + "env": { "SENTRY_TOKEN": "{env:SENTRY_TOKEN}" }, + "usedBy": ["dev-debug"] + } + ] +} diff --git a/tool-chain-installer/scripts/install-tools.mjs b/tool-chain-installer/scripts/install-tools.mjs new file mode 100755 index 0000000..a840f83 --- /dev/null +++ b/tool-chain-installer/scripts/install-tools.mjs @@ -0,0 +1,222 @@ +#!/usr/bin/env node +// 安装 MCP 工具链到指定项目。 +// +// 用法: +// node install-tools.mjs <目标项目目录> [选项] +// +// --tools 安装指定工具(逗号分隔) +// --group 安装某一组(browser / context / data / observability) +// --all 安装全部 +// --dry-run 只打印将要发生的改动 +// --format 写入格式:both(默认) | mcp-json | opencode +// --list 列出所有可用工具并退出 + +import fs from "node:fs" +import path from "node:path" +import { fileURLToPath } from "node:url" + +const HERE = path.dirname(fileURLToPath(import.meta.url)) +const CATALOG_PATH = path.join(HERE, "..", "catalog", "mcp-catalog.json") + +// ── 参数解析 ──────────────────────────────────────────────────────── +const args = process.argv.slice(2) +const opts = { tools: [], groups: [], all: false, dryRun: false, format: "both", list: false } +let target = null + +for (let i = 0; i < args.length; i++) { + const a = args[i] + switch (a) { + case "--tools": opts.tools = (args[++i] || "").split(",").map(s => s.trim()).filter(Boolean); break + case "--group": opts.groups.push(args[++i]); break + case "--all": opts.all = true; break + case "--dry-run": opts.dryRun = true; break + case "--format": opts.format = args[++i] || "both"; break + case "--list": opts.list = true; break + case "-h": case "--help": printUsage(0); break + default: + if (a.startsWith("-")) { console.error(`未知参数: ${a}`); printUsage(1) } + target = a + } +} + +function printUsage(code) { + console.log(fs.readFileSync(fileURLToPath(import.meta.url), "utf8").split("\n").slice(1, 11).map(l => l.replace(/^#\s?/, "")).join("\n")) + process.exit(code) +} + +// ── 目录 ──────────────────────────────────────────────────────────── +const catalog = JSON.parse(fs.readFileSync(CATALOG_PATH, "utf8")) + +if (opts.list) { + for (const [group, items] of Object.entries(catalog)) { + console.log(`\n${group}`) + for (const t of items) { + console.log(` ${t.name.padEnd(20)} ${t.description}`) + console.log(` ${"".padEnd(20)} → ${t.command} ${t.args.join(" ")}`) + } + } + console.log("") + process.exit(0) +} + +if (!target) { + console.error("错误:缺少目标项目目录。") + printUsage(1) +} +if (!fs.existsSync(target)) { + console.error(`错误:目标目录不存在: ${target}`) + process.exit(1) +} + +const PROJECT_ROOT = fs.realpathSync(target) + +// ── 选择工具 ──────────────────────────────────────────────────────── +const selected = [] +if (opts.all) { + for (const items of Object.values(catalog)) selected.push(...items) +} +for (const g of opts.groups) { + const items = catalog[g] + if (!items) { + console.error(`错误:未知分组 "${g}"。可用分组:${Object.keys(catalog).join(", ")}`) + process.exit(1) + } + selected.push(...items) +} +if (opts.tools.length) { + const all = Object.values(catalog).flat() + for (const name of opts.tools) { + const found = all.find(t => t.name === name) + if (!found) { + console.error(`错误:未知工具 "${name}"。用 --list 查看全部。`) + process.exit(1) + } + selected.push(found) + } +} +if (!selected.length) { + console.error("错误:没有指定要安装的工具。用 --tools / --group / --all 指定。") + printUsage(1) +} + +// 去重 +const unique = [...new Map(selected.map(t => [t.name, t])).values()] + +// ── JSONC 容忍解析 / 写回 ────────────────────────────────────────── +function stripJsonComments(text) { + let out = "" + let inString = false + let inLine = false + let inBlock = false + for (let i = 0; i < text.length; i++) { + const c = text[i] + const n = text[i + 1] + if (inLine) { + if (c === "\n") { inLine = false; out += c } + continue + } + if (inBlock) { + if (c === "*" && n === "/") { inBlock = false; i++ } + continue + } + if (inString) { + out += c + if (c === "\\") { out += n ?? ""; i++; continue } + if (c === '"') inString = false + continue + } + if (c === '"') { inString = true; out += c; continue } + if (c === "/" && n === "/") { inLine = true; i++; continue } + if (c === "/" && n === "*") { inBlock = true; i++; continue } + out += c + } + return out +} + +function readJsonc(file) { + if (!fs.existsSync(file)) return null + const raw = fs.readFileSync(file, "utf8") + try { + return JSON.parse(stripJsonComments(raw)) + } catch (e) { + console.error(`错误:无法解析 ${file} —— ${e.message}`) + process.exit(1) + } +} + +function writeJson(file, data) { + fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n", "utf8") +} + +// ── 安装 ──────────────────────────────────────────────────────────── +console.log("MCP 工具链安装器") +console.log(` 目标项目 : ${PROJECT_ROOT}`) +console.log(` 写入格式 : ${opts.format}`) +console.log(` 待安装 : ${unique.map(t => t.name).join(", ")}`) +console.log("") + +const writeMcpJson = opts.format === "both" || opts.format === "mcp-json" +const writeOpencode = opts.format === "both" || opts.format === "opencode" + +const mcpJsonPath = path.join(PROJECT_ROOT, ".mcp.json") +const opencodePath = path.join(PROJECT_ROOT, "opencode.jsonc") + +if (writeMcpJson) { + const existing = readJsonc(mcpJsonPath) || {} + if (!existing.mcpServers) existing.mcpServers = {} + for (const t of unique) { + existing.mcpServers[t.name] = { + command: t.command, + args: t.args, + ...(t.env && Object.keys(t.env).length ? { env: t.env } : {}) + } + } + if (opts.dryRun) { + console.log(` [计划] 写入 ${mcpJsonPath}`) + } else { + writeJson(mcpJsonPath, existing) + console.log(` [写入] ${mcpJsonPath}`) + } +} + +if (writeOpencode) { + const existing = readJsonc(opencodePath) || { $schema: "https://opencode.ai/config.json" } + if (!existing.$schema) existing.$schema = "https://opencode.ai/config.json" + if (!existing.mcp) existing.mcp = {} + for (const t of unique) { + existing.mcp[t.name] = { + type: "local", + command: [t.command, ...t.args], + enabled: true, + ...(t.env && Object.keys(t.env).length ? { environment: t.env } : {}) + } + } + if (opts.dryRun) { + console.log(` [计划] 写入 ${opencodePath}`) + } else { + writeJson(opencodePath, existing) + console.log(` [写入] ${opencodePath}`) + } +} + +// ── 报告 ──────────────────────────────────────────────────────────── +console.log("") +console.log("已配置的工具:") +for (const t of unique) { + const used = t.usedBy?.length ? `(供 ${t.usedBy.join(", ")} 使用)` : "" + console.log(` - ${t.name.padEnd(20)} ${t.description} ${used}`) +} + +const needsEnv = unique.filter(t => t.env && Object.keys(t.env).length) +if (needsEnv.length) { + console.log("") + console.log("需要配置环境变量(不要把密钥写进仓库):") + for (const t of needsEnv) { + for (const [k] of Object.entries(t.env)) { + console.log(` - ${k} (${t.name})`) + } + } +} + +console.log("") +console.log("提示:修改 MCP 配置后需重启 opencode 才会生效。")