From 69cfaea7dc18ca822bc4466992e291335f907e3c Mon Sep 17 00:00:00 2001 From: ning-inspire Date: Thu, 19 Nov 2026 10:05:10 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BC=95=E5=85=A5=20agents-workflow-en?= =?UTF-8?q?gine=20=E4=B8=8E=205=20=E4=B8=AA=20SDD=20skill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 agents-workflow-engine:主会话按泳道图调度子 agent 到提测, 含 schema、preset、CLI、单测,并接入 verify.sh。 agile-team-sdd 新增 5 个模板:ba-write-prototype、ba-requirement-review、 dev-plan-review、dev-plan-amend、pm-start-iteration,已登记 catalog 并同步安装到 example-project;README/AGENTS.md 同步 skill 数量 21→26。 验证:./.agents/verify.sh 全绿(67 项,含 AWE 14 个单测)。 文档同步检查:已更新 README、AGENTS.md、agile-team-sdd/README.md 与 SKILL.md。 --- .../plan/20261118-agents-workflow-engine.md | 312 ++++++++++ .agents/plan/iteration-to-test.html | 442 ++++++++++++++ .agents/verify.sh | 14 + AGENTS.md | 8 +- README.md | 20 +- agents-workflow-engine/README.md | 37 ++ .../agents_workflow_engine/__init__.py | 5 + .../agents_workflow_engine/__main__.py | 4 + .../agents_workflow_engine/cli.py | 153 +++++ .../agents_workflow_engine/errors.py | 9 + .../agents_workflow_engine/load.py | 47 ++ .../agents_workflow_engine/merge.py | 45 ++ .../agents_workflow_engine/render_mermaid.py | 44 ++ .../agents_workflow_engine/runner.py | 248 ++++++++ .../agents_workflow_engine/state.py | 102 ++++ .../agents_workflow_engine/validate.py | 174 ++++++ .../agents_workflow_engine/yaml_lite.py | 549 ++++++++++++++++++ .../presets/iteration-to-test.yaml | 85 +++ .../schema/graph.schema.json | 16 + agents-workflow-engine/scripts/install.sh | 71 +++ agents-workflow-engine/tests/test_units.py | 186 ++++++ agile-team-sdd/README.md | 7 +- agile-team-sdd/SKILL.md | 9 +- agile-team-sdd/catalog.json | 53 ++ .../ba-requirement-review-template/SKILL.md | 24 + .../ba-write-prototype-template/SKILL.md | 23 + .../skills/dev-plan-amend-template/SKILL.md | 23 + .../skills/dev-plan-review-template/SKILL.md | 24 + .../pm-start-iteration-template/SKILL.md | 28 + .../skills/ba-requirement-review/SKILL.md | 20 + .../skills/ba-write-prototype/SKILL.md | 19 + .../.agents/skills/dev-plan-amend/SKILL.md | 19 + .../.agents/skills/dev-plan-review/SKILL.md | 20 + .../skills/pm-start-iteration/SKILL.md | 24 + 34 files changed, 2851 insertions(+), 13 deletions(-) create mode 100644 .agents/plan/20261118-agents-workflow-engine.md create mode 100644 .agents/plan/iteration-to-test.html create mode 100644 agents-workflow-engine/README.md create mode 100644 agents-workflow-engine/agents_workflow_engine/__init__.py create mode 100644 agents-workflow-engine/agents_workflow_engine/__main__.py create mode 100644 agents-workflow-engine/agents_workflow_engine/cli.py create mode 100644 agents-workflow-engine/agents_workflow_engine/errors.py create mode 100644 agents-workflow-engine/agents_workflow_engine/load.py create mode 100644 agents-workflow-engine/agents_workflow_engine/merge.py create mode 100644 agents-workflow-engine/agents_workflow_engine/render_mermaid.py create mode 100644 agents-workflow-engine/agents_workflow_engine/runner.py create mode 100644 agents-workflow-engine/agents_workflow_engine/state.py create mode 100644 agents-workflow-engine/agents_workflow_engine/validate.py create mode 100644 agents-workflow-engine/agents_workflow_engine/yaml_lite.py create mode 100644 agents-workflow-engine/presets/iteration-to-test.yaml create mode 100644 agents-workflow-engine/schema/graph.schema.json create mode 100755 agents-workflow-engine/scripts/install.sh create mode 100644 agents-workflow-engine/tests/test_units.py create mode 100644 agile-team-sdd/skills/ba-requirement-review-template/SKILL.md create mode 100644 agile-team-sdd/skills/ba-write-prototype-template/SKILL.md create mode 100644 agile-team-sdd/skills/dev-plan-amend-template/SKILL.md create mode 100644 agile-team-sdd/skills/dev-plan-review-template/SKILL.md create mode 100644 agile-team-sdd/skills/pm-start-iteration-template/SKILL.md create mode 100644 example-project/.agents/skills/ba-requirement-review/SKILL.md create mode 100644 example-project/.agents/skills/ba-write-prototype/SKILL.md create mode 100644 example-project/.agents/skills/dev-plan-amend/SKILL.md create mode 100644 example-project/.agents/skills/dev-plan-review/SKILL.md create mode 100644 example-project/.agents/skills/pm-start-iteration/SKILL.md diff --git a/.agents/plan/20261118-agents-workflow-engine.md b/.agents/plan/20261118-agents-workflow-engine.md new file mode 100644 index 0000000..e626a7b --- /dev/null +++ b/.agents/plan/20261118-agents-workflow-engine.md @@ -0,0 +1,312 @@ +# Plan:agents-workflow-engine + +> 日期:2026-11-18 +> 状态:**已完成**(图已确认;三期在本 plan 内做完) +> 方向:新模块 + 五个 skill 模板。确认人授权连续实现,不满意再开下一份 plan 调整。 + +主会话 `graph-master` 从版本启动调度到提测。图按三道横向泳道画:人、graph-master、子 agent。人只在输入和决策处动手。skill 全部由子 agent 执行,主会话不直接调用 skill。子 agent 可以绑定不同模型,用来做对抗验证。`dev-plan` 是批量节点,产出一批任务;`dev-build` 按这一批逐条循环。六步写在 `dev-build` 节点里面,不另立节点。同一泳道里前后相连的节点竖排。开发自测通过即到达终点「提测」。QA 仍是以后的扩展,要先有流水线环境,本版不连、不渲染。图是数据,项目可以改自己的图。预览页用 JointJS,见 [iteration-to-test.html](iteration-to-test.html)。 + +本 plan 覆盖第 1、2、3 期,不拆开做。默认:回路上限 `N` / `n` 为 3;plan 质量门和 plan 决策的「不满意」仍不补边(草图没画)。 + +## 图 + +外形:圆角矩形 = 动作,双线矩形 = 门禁,菱形 = 人类决策,平行四边形 = 人类输入。虚线是打回。`N` / `n` 是可重复上限,`1` 是只跑一次。 + +拼写按仓库 skill 名校正:`tl-high-level-design`、`qa-write-cases`。 + +三道横向泳道,时间从左到右。批量只标在节点上:`dev-plan` 是一批任务,`dev-build` 按该批循环。预览:`iteration-to-test.html`。 + +一张同结构的简图: + +```mermaid +flowchart LR + subgraph people [人] + startVersion[/开始版本/] + writeSpec[/编写规格/] + reqDecision{需求决策} + tech[/技术高阶/] + hldDecision{高阶决策} + planConfirm[/plan 确认/] + planDecision{plan 决策} + buildDecision{构建决策} + amendIn[/修订输入/] + end + subgraph master [graph-master] + graphEntry{{/graph 会话启动}} + handoff([提测]) + end + subgraph workers [子 agent] + pmStart(pm-start-iteration) + baSpec(ba-write-spec) + baProto(ba-write-prototype) + reqGate[[需求质量门]] + hld(tl-high-level-design) + devPlan("dev-plan · 一批任务") + planGate[[plan 质量门]] + runner(overnight-runner) + devBuild("dev-build · 按批循环") + amend(dev-plan-amend) + end + graphEntry --> startVersion --> pmStart --> writeSpec --> baSpec --> baProto --> reqGate --> reqDecision + reqGate -.->|不满意| writeSpec + reqDecision -.->|不满意| writeSpec + reqDecision -->|满意| tech --> hld --> hldDecision + hldDecision -.->|不满意| tech + hldDecision -->|满意| devPlan --> planGate --> planConfirm --> planDecision --> runner --> devBuild + devBuild -.->|每条任务| devBuild + devBuild -->|本批结束| buildDecision + buildDecision -->|满意| handoff + buildDecision -->|不满意| amendIn --> amend -.->|回到规划| devPlan +``` + +`dev-build` 框内只作说明,不是图节点:后端 TDD、前端 TDD、构建/Lint、前端 UI review、API 测试、浏览器自测。浏览器自测是本版的结束条件。 + +第三张子图 QA 先只登记、不渲染、不连边。接入条件是流水线环境就绪。预留节点:`/qa-write-cases`、创建 MR / 流水线部署、E2E 测试、人工补测。 + +## 读图后锁定的语义 + +| 种类 | 谁来做 | 运行时行为 | +|---|---|---| +| 动作 | 子 agent | 主会话派一个子 agent 调 skill,写出文件。`sealed: true` 的动作禁止被拆成子节点 | +| 门禁 | 子 agent | 另一个子 agent 调 review skill,只接受「满意 / 不满意」 | +| 人类决策 | 人 | 图停住,人在「满意 / 不满意」里选一条出边。不写业务文档 | +| 人类输入 | 人 | 图停住,人写完一段内容,再沿唯一出边继续 | +| 入口 / 终点 | graph-master | `/graph` 启动主会话;「提测」是主会话的终点,没有出边 | + +泳道只有三道,横向从左到右:`human`(人)、`master`(graph-master 主会话)、`subagent`(子 agent)。不按 BA / TL / DEV / QA 分道。 + +批量: + +| 节点 | 是不是批量 | 含义 | +|---|---|---| +| `dev-plan` | 是 | 一批任务。后面的队列和构建都消费这一批 | +| `dev-build` | 按批循环 | 主会话对 `dev-plan` 的每一条任务调用一次这个子 agent。节点本身不拆开 | +| 其余 skill | 否 | `ba-write-spec` 的 `N`、高阶设计的一次,是重试或只跑一次,不是一批任务 | + +其他规则: + +- 渲染成三道横向泳道。同一 `actor` 上前后相连的节点竖排,用来省横向位置 +- `dev-build` 的内层六步画在该节点内部,仍然不是独立节点,预设图不能给这六步加边 +- 需求质量门后的人类决策:不满意回到编写规格;满意进入「技术高阶」 +- 高阶决策满意后进入 `dev-plan`。终点是「提测」:本批 `dev-build` 结束且构建决策为满意 +- QA 放在 `extensions`,`linked: false`。依赖流水线环境,本版不连到提测之后 +- 打回计数打在回路上:规格回路上限 `N`,高阶回路上限,开发打回上限 `n`。超限后主会话停住,不再自动打回 +- `overnight-runner` 是子 agent 的一个动作,负责排这一批任务的顺序,不取代本引擎 + +## 子 agent 与对抗验证 + +主会话只调度。每个 skill 节点启动一个子 agent。子 agent 的模型单独绑定,不默认等于主会话模型。 + +对抗验证用不同模型:写的人和查的人不是同一个模型。 + +| 产出 | 核对 | 要求 | +|---|---|---| +| `ba-write-spec` | `ba-requirement-review` | 两个子 agent 的 `model` 不同 | +| `dev-plan` | `dev-plan-review` | 两个子 agent 的 `model` 不同 | +| `dev-build` 实现 | skill 内部的自测 / 评审 | 核对模型与实现模型不同。核对仍封在 `dev-build` 里,图上不另加节点 | + +未配置 `model` 时沿用主会话模型,并记一条「未做对抗验证」。配置相同模型时同样记一条,不假装已经对抗过。模型名不写进仓库,用环境变量引用,例如 `{ env: MODEL_WRITER }` 与 `{ env: MODEL_REVIEWER }`。 + +第 1 期保存 `model` 字段并在相同时提示。第 2 期按该字段拉起子 agent。两期都在本 plan 内完成。 + +## 确认记录 + +图已确认,三期一起做。 + +- 回路上限默认 3 +- plan 质量门、plan 决策的「不满意」不补进预设 +- 若图还要改,另开一份 plan + +## 模块边界 + +新目录 `agents-workflow-engine/`,与 `overnight-runner/`、`agile-team-sdd/` 并列。 + +- 不 import 其他模块。skill 名只是字符串 +- Python 3.9+,标准库。YAML 子集在本模块里解析,不装 pip 包 +- 不改 `dev-build` 内部 LOOP +- 不把 QA 子图接进默认可运行图。接入前要有流水线环境 + +## DSL + +一份图一个 YAML。项目文件是预设加上覆盖,解析结果才是被渲染、被执行的图。 + +```yaml +id: iteration-to-test +entry: graph-start +lanes: + - { id: human, title: 人 } + - { id: master, title: graph-master } + - { id: subagent, title: 子 agent } +models: + writer: { env: MODEL_WRITER } + reviewer: { env: MODEL_REVIEWER } +loops: + - id: spec + maxIterations: 3 + backEdges: [req-gate-reject, req-decision-reject] + - id: hld + maxIterations: 3 + backEdges: [hld-reject] + - id: dev + maxIterations: 3 + backEdges: [build-reject] +nodes: + - { id: graph-start, actor: master, kind: entry, title: 会话启动 } + - { id: start-version, actor: human, kind: human_input, title: 开始版本 } + - { id: pm-start-iteration, actor: subagent, kind: action, skill: pm-start-iteration, title: 开始迭代, model: writer } + - { id: write-spec, actor: human, kind: human_input, title: 编写规格 } + - { id: ba-write-spec, actor: subagent, kind: action, skill: ba-write-spec, title: 需求规格, model: writer } + - { id: ba-write-prototype, actor: subagent, kind: action, skill: ba-write-prototype, title: 原型, once: true, model: writer } + - { id: ba-requirement-review, actor: subagent, kind: gate, skill: ba-requirement-review, title: 需求质量门, model: reviewer } + - { id: requirement-decision, actor: human, kind: decision, title: 需求决策, options: [满意, 不满意] } + - { id: tech-brief, actor: human, kind: human_input, title: 技术高阶 } + - { id: tl-high-level-design, actor: subagent, kind: action, skill: tl-high-level-design, title: 技术高阶设计, once: true, model: writer } + - { id: hld-decision, actor: human, kind: decision, title: 高阶决策, options: [满意, 不满意] } + - { id: dev-plan, actor: subagent, kind: action, skill: dev-plan, title: 详细规划, batch: true, model: writer } + - { id: dev-plan-review, actor: subagent, kind: gate, skill: dev-plan-review, title: plan 质量门, model: reviewer } + - { id: plan-confirm, actor: human, kind: human_input, title: plan 确认 } + - { id: plan-decision, actor: human, kind: decision, title: plan 决策, options: [满意, 不满意] } + - { id: overnight-runner, actor: subagent, kind: action, skill: overnight-runner, title: 排本批顺序, model: writer } + - { id: dev-build, actor: subagent, kind: action, skill: dev-build, title: 构建与自测, sealed: true, repeatsBatch: dev-plan, model: writer, + note: [后端 TDD, 前端 TDD, 构建/Lint, 前端 UI review, API 测试, 浏览器自测] } + - { id: build-decision, actor: human, kind: decision, title: 构建决策, options: [满意, 不满意] } + - { id: amend-input, actor: human, kind: human_input, title: 修订输入 } + - { id: dev-plan-amend, actor: subagent, kind: action, skill: dev-plan-amend, title: 规划修订, model: writer } + - { id: handoff, actor: master, kind: end, title: 提测 } +extensions: + - id: qa + title: 测试 + linked: false + requires: pipeline + nodes: + - { id: qa-write-cases, kind: action, title: QA 用例 } + - { id: dev-create-mr, kind: action, title: 创建 MR/流水线部署 } + - { id: qa-run-e2e, kind: action, title: E2E 测试 } + - { id: manual-test, kind: human_input, title: 人工补测 } +edges: + - { id: e0, from: graph-start, to: start-version } + - { id: e1, from: start-version, to: pm-start-iteration } + - { id: e2, from: pm-start-iteration, to: write-spec } + - { id: e3, from: write-spec, to: ba-write-spec } + - { id: e4, from: ba-write-spec, to: ba-write-prototype } + - { id: e5, from: ba-write-spec, to: ba-requirement-review } + - { id: e6, from: ba-write-prototype, to: ba-requirement-review } + - { id: req-pass, from: ba-requirement-review, to: requirement-decision, when: 满意 } + - { id: req-gate-reject, from: ba-requirement-review, to: write-spec, when: 不满意, back: true } + - { id: req-decision-reject, from: requirement-decision, to: write-spec, when: 不满意, back: true } + - { id: e7, from: tech-brief, to: tl-high-level-design } + - { id: e8, from: tl-high-level-design, to: hld-decision } + - { id: req-ok, from: requirement-decision, to: tech-brief, when: 满意 } + - { id: hld-reject, from: hld-decision, to: tech-brief, when: 不满意, back: true } + - { id: hld-ok, from: hld-decision, to: dev-plan, when: 满意 } + - { id: e9, from: dev-plan, to: dev-plan-review } + - { id: plan-pass, from: dev-plan-review, to: plan-confirm, when: 满意 } + - { id: e10, from: plan-confirm, to: plan-decision } + - { id: plan-ok, from: plan-decision, to: overnight-runner, when: 满意 } + - { id: e11, from: overnight-runner, to: dev-build } + - { id: e12, from: dev-build, to: build-decision } + - { id: build-pass, from: build-decision, to: handoff, when: 满意 } + - { id: build-reject, from: build-decision, to: amend-input, when: 不满意, back: true } + - { id: e13, from: amend-input, to: dev-plan-amend } + - { id: e14, from: dev-plan-amend, to: dev-plan, back: true } +``` + +技术高阶的正向入口是需求决策的「满意」。打回仍回到技术高阶。 + +校验至少拒绝: + +- 工作节点 `kind` 不在四种之内。另允许各一个 `entry`(会话启动)和一个无出边的 `end`(提测) +- `actor` 不在 `human` / `master` / `subagent` 之内。skill 节点的 `actor` 必须是 `subagent` +- `batch: true` 的节点没有被某个 `repeatsBatch` 消费 +- 配对的产出节点与门禁节点 `model` 相同(记「未做对抗验证」,不阻断渲染) +- 边指向不存在的节点,或指向 `sealed` 节点的 `note` 项,或指向 `extensions` 里的节点 +- 决策节点的 `when` 不在 `options` 里 +- 门禁、决策的 `when` 不在「满意 / 不满意」里;草图没画的出边不补进预设 +- `linked: false` 的扩展子图出现在默认可运行边里 +- 人类输入多于一条出边 +- 打回边没有 `loops.maxIterations` +- 覆盖文件删掉 `dev-build.sealed`,或往 `note` 里的步骤加边 + +## 项目怎么改自己的图 + +目标项目可选文件:`.agents/workflow/overlay.yaml`。引擎读套件预设,再叠覆盖。 + +允许的操作:`disable` 节点、替换动作的 `skill`、`insert` 节点和边、改门禁的 `when` 目标、改某条打回边和所属 loop 的 `maxIterations`。 + +```yaml +disable: [ba-write-prototype] +replace: + ba-write-spec: { skill: my-write-spec } +loops: + - { id: spec, maxIterations: 2 } +``` + +`disable` 会删掉该节点及其边;若因此断成两条无法汇合的轨道,`validate` 报错并指出节点 id。 + +## 渲染 + +`render` 只读解析后的图,写出 Mermaid。映射固定: + +| kind | Mermaid | +|---|---| +| action | `id(标题)` | +| gate | `id[[标题]]` | +| decision | `id{标题}` | +| human_input | `id[/标题/]` | +| back 边 | `-.->` 并标 `when` | +| sealed | 单节点,`note` 写进标签,不展开成节点 | +| end | `([提测])`,无出边 | +| 整图 | 三道横向泳道。同一泳道内连续节点竖排。`dev-build` 的六步画在节点内 | +| extensions | `linked: false` 时不输出 | + +不引入 BPMN、Camunda、React Flow,也不做可视化编辑器。 + +## 分期 + +三期都在本 plan 内完成。 + +### 第 1 期 + +- 包 `agents_workflow_engine`:`cli` / `yaml_lite` / `load` / `merge` / `validate` / `render_mermaid` +- `schema/graph.schema.json` 与 `presets/iteration-to-test.yaml` +- 子命令:`validate`、`resolve`、`render`。都有 `--help`。`render --dry-run` 只打印 +- 单测:合并、封死节点、扩展不能连边、回路缺上限、Mermaid 外形、模型相同只警告 +- `./.agents/verify.sh` 增加本模块单测 +- 根 `README.md` 模块表加一行;`AGENTS.md` 补拓扑和模块职责 +- `scripts/install.sh <目标> [--dry-run] [--force]` 把预设拷到目标 `.agents/workflow/preset.yaml`,不覆盖已有 `overlay.yaml` + +### 第 2 期 + +- `run`:主会话按图派子 agent。子 agent 读取节点上的 `model` +- 产出 skill 与门禁 skill 的模型不同才算对抗验证;相同则记入 `.agents/workflow/decisions.jsonl` +- `dev-plan` 的一批任务由主会话记下,之后对每一条调用一次 `dev-build` +- 人类输入、人类决策从 `--answers` 读取;缺答案时退出并写明要补哪一项 +- 回路超限后停住,不再沿打回边走 + +### 第 3 期 + +补五个 skill 模板并装进 example:`pm-start-iteration`、`ba-write-prototype`、`ba-requirement-review`、`dev-plan-review`、`dev-plan-amend`。同步 `catalog.json`、套件表格、根 README。 + +## 非目标 + +- 不改 `overnight-runner` 的队列、面板和决策窗口 +- 不把 BA / TL / DEV / QA 做成泳道。泳道只有人、主会话、子 agent +- 不编辑 `dev-build` 内部六步 +- 不把 QA 子图接进默认可运行路径。流水线环境就绪后再扩展 + +## 验证 + +三期: + +```bash +PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine validate +PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine render --dry-run +PYTHONPATH=agents-workflow-engine python agents-workflow-engine/tests/test_units.py +./agents-workflow-engine/scripts/install.sh example-project --dry-run +PATH_MODE=relative ./agile-team-sdd/install.sh example-project --force +./.agents/verify.sh +``` + +## 文档同步检查 + +实现时更新:根 `README.md` 模块表与技能数量、`AGENTS.md` §1 / §3 / §8、本模块 `README.md`、`agile-team-sdd` 的 catalog 与表格。`team-workflow-guide` 不在本轮改。 diff --git a/.agents/plan/iteration-to-test.html b/.agents/plan/iteration-to-test.html new file mode 100644 index 0000000..29f1ef8 --- /dev/null +++ b/.agents/plan/iteration-to-test.html @@ -0,0 +1,442 @@ + + + + + + 版本到提测 + + + +
+

版本到提测

+

+ 人 · 输入 + 人 · 决策 + 子 agent · skill + 子 agent · 门禁 + 批量节点 + 回路 +

+
+
+ + + + + diff --git a/.agents/verify.sh b/.agents/verify.sh index da5f5e5..53bb6c5 100755 --- a/.agents/verify.sh +++ b/.agents/verify.sh @@ -366,6 +366,20 @@ PYEOF if [ $? -eq 0 ]; then PASSED=$((PASSED + 1)); else FAILED=$((FAILED + 1)); fi fi +# ── 12. agents-workflow-engine ──────────────────────────────────── +head_ "12. agents-workflow-engine 测试" +if [ -z "$PY" ]; then + skip "找不到 python" +else + if "$PY" agents-workflow-engine/tests/test_units.py > /tmp/awe-units.log 2>&1 && grep -q '^OK$' /tmp/awe-units.log; then + grep '^Ran ' /tmp/awe-units.log | sed 's/^/ \033[32m✔\033[0m /' + PASSED=$((PASSED + 1)) + else + sed 's/^/ /' /tmp/awe-units.log + bad "单元测试" + fi +fi + # ── 汇总 ─────────────────────────────────────────────────────────── printf '\n\033[1m%s\033[0m\n' "────────────────────────────" if [ "$FAILED" -eq 0 ]; then diff --git a/AGENTS.md b/AGENTS.md index 3aaf921..cc40de5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ |---|---|---| | 文档 | Markdown | skill、指南、规范、模板 | | 脚本 | Bash 3.2+ | 安装脚本(安装器型 skill) | -| 脚本 | Python 3.9+(**零第三方依赖**) | `overnight-runner` 的运行器 | +| 脚本 | Python 3.9+(**零第三方依赖**) | `overnight-runner` 与 `agents-workflow-engine` | | 脚本 | Node.js 18+ | `tool-chain-installer` 的安装器 | | 配置 | YAML | 队列配置、项目配置、skill 清单 | | 配置 | JSON / JSONC | MCP 工具清单、opencode 配置 | @@ -27,10 +27,11 @@ ``` team-harness-suite/ ├── .agents/ # 本仓库自用:verify.sh + plan/ + skills/ -├── agile-team-sdd/ # SDD 技能套件(21 个 skill 模板 + 安装器) +├── agile-team-sdd/ # SDD 技能套件(26 个 skill 模板 + 安装器) ├── harness-installer/ # 初始化目标项目的 AGENTS.md + docs/ 骨架 ├── tool-chain-installer/ # 安装 MCP 工具链到项目配置 ├── overnight-runner/ # 无人值守跑 plan 的分屏面板 + 看门狗 +├── agents-workflow-engine/ # 主会话按泳道图调度子 agent,到提测为止 ├── team-workflow-guide/ # 团队流程与角色手册(纯文档) ├── example-project/ # 全栈参考实现(被这套 harness 管理的样子) └── opencode.jsonc # 注册本仓库的 skills 路径 @@ -129,7 +130,7 @@ agile-team-sdd/skills/dev-plan-template/SKILL.md (frontmatter: name: dev-pla ┌──▼──────────┐ ┌▼───────────┐ ┌▼──────────────────┐ │harness- │ │agile-team- │ │tool-chain- │ │installer/ │ │sdd/ │ │installer/ │ -│AGENTS.md │ │21 个 skill │ │MCP 工具链 │ +│AGENTS.md │ │26 个 skill │ │MCP 工具链 │ │docs/ 骨架 │ │模板 + 安装器│ │ │ └─────────────┘ └┬───────────┘ └──────────────────┘ │ 装进 @@ -245,6 +246,7 @@ agile-team-sdd/skills/dev-plan-template/SKILL.md (frontmatter: name: dev-pla | `harness-installer/` | 铺 `AGENTS.md` + `docs/` 骨架 | 不填 `AGENTS.md` 里的 TODO(那是人填的) | | `tool-chain-installer/` | 装 MCP 工具链 | 不装 npm/pip 依赖 | | `overnight-runner/` | 无人值守跑 plan 的运行时 | 不判断 plan 质量(人的责任) | +| `agents-workflow-engine/` | 主会话按泳道图调度子 agent,跑到提测 | 不执行 QA 流水线,不拆 `dev-build` 内部六步 | | `team-workflow-guide/` | 流程与角色约定 | 不含可执行代码 | | `example-project/` | 参考实现 | 不参与本仓库的验证脚本 | diff --git a/README.md b/README.md index 73b2aeb..258a2fd 100644 --- a/README.md +++ b/README.md @@ -30,11 +30,12 @@ AI4SE 框架构想(框内元素仅为示例,可能会装入更多实践): | 模块 | 目录 | 目的 | 形态 | | ---------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | ----------------- | -| **SDD 技能套件** | [`agile-team-sdd/`](agile-team-sdd/) | 团队统一的开发流程 skill,21 个覆盖 BA→TL→PM→开发→QA→发布→复盘,含无前缀的 `overnight-runner`。模板带占位符,可安装到任意项目,并容易被调整修改 | skill + 安装脚本 | +| **SDD 技能套件** | [`agile-team-sdd/`](agile-team-sdd/) | 团队统一的开发流程 skill,26 个覆盖 BA→TL→PM→开发→QA→发布→复盘,含无前缀的 `overnight-runner`。模板带占位符,可安装到任意项目,并容易被调整修改 | skill + 安装脚本 | | **Harness 初始化器** | [`harness-installer/`](harness-installer/) | 为任意项目铺好工程底座:`AGENTS.md` + `docs/`(含 `architecture/` 高阶意图骨架、features / facts / standards) | skill + 模板 + 脚本 | | **工具链安装器** | [`tool-chain-installer/`](tool-chain-installer/) | 把 MCP 工具链(chrome-devtools、playwright、context7…)写进项目配置,不依赖个人机器的全局状态 | skill + 工具清单 + 脚本 | | **团队工作流指南** | [`团队工作流指南`](https://inspirechina.github.io/ai4se-harness-suite/team-workflow-guide/) | 团队级协作手册(HTML 单页):总览矩阵 + 项目准备 → 迭代前设计 → 迭代中开发;角色、测试归属、闸门 | 文档 | -| **持续运行面板** | [`overnight-runner/`](overnight-runner/) | 把一串 plan 交给 coding agent 跑:左边任务队列、右边 agent 实时输出,看门狗自动重试,**多队列**各自独立,决策全程留痕(白天弹窗问你、夜里自动决策) | skill + Python 实现 | +| **持续运行面板** | [`overnight-runner/`](overnight-runner/) | 把一串 plan 交给 coding agent 跑:左边任务队列、右边 agent 实时输出,看门狗自动重试,多队列各自独立,决策全程留痕 | skill + Python 实现 | +| **工作流引擎** | [`agents-workflow-engine/`](agents-workflow-engine/) | 主会话按泳道图调度子 agent,从版本启动到提测。子 agent 可绑不同模型做对抗验证 | Python 实现 | | **参考实现** | [`example-project/`](example-project/) | 一份完整、可跑、已填满规范的全栈参考项目(Vue 3 + Spring Boot + DDD 四层),用来对照与教学 | 示例项目 | ## 关系图 @@ -46,7 +47,7 @@ AI4SE 框架构想(框内元素仅为示例,可能会装入更多实践): ┌───────────────────────┼───────────────────────┐ │ │ │ harness-installer agile-team-sdd tool-chain-installer - AGENTS.md 规范 21 个 SDD skill MCP 工具链 + AGENTS.md 规范 26 个 SDD skill MCP 工具链 docs/ 含 architecture BA·TL·Dev·QA·PM 全流程 │ │ │ └───────────────────────┼───────────────────────┘ @@ -56,18 +57,22 @@ AI4SE 框架构想(框内元素仅为示例,可能会装入更多实践): (参考实现 · 已装好全套) ``` -## SDD 技能套件(21 个) +## SDD 技能套件(26 个) | 组 | Skill | 作用 | |---|---|---| | **BA** | `ba-grill-me` | 拷问需求,把模糊描述逼成可验收的规格 | | | `ba-write-spec` | 编写需求规格;维护项目级术语表(`docs/architecture/business/glossary.md`) | +| | `ba-write-prototype` | 按 spec 做原型,放到该迭代 prototypes | +| | `ba-requirement-review` | 用另一个模型审查 spec,只回答满意或不满意 | | | `ba-gen-facts` | 从代码生成/校准事实文档:API、库表、领域模型、专题 | | | `ba-arch-sync-back` | 业务侧对齐:术语 / 核心领域 / 产品 ↔ features 与 facts | | **TL** | `tl-arch-plan` | 项目准备写/更新 `docs/architecture/`(C4、ADR 一句话表、与业务侧) | | | `tl-arch-sync-back` | 技术侧对齐:ADR/C4 ↔ 实现与 facts 专题 | | | `tl-high-level-design` | 写迭代高阶技术设计(HLD / TRD),确认前不得开 Plan | | **Dev** | `dev-plan` | 写技术方案(含 DST 自测 + 界面对照基线),等待确认 | +| | `dev-plan-review` | 用另一个模型审查 plan,只回答满意或不满意 | +| | `dev-plan-amend` | 按人的修订意见改 plan | | | `dev-build` | 全栈 LOOP:实现 + 自测/UI 落盘修到绿 + 代码评审 | | | `dev-self-test` | 真实本地环境按 DST 自测并落盘 | | | `dev-code-review` | 代码评审(由 build LOOP 调用,可单跑) | @@ -78,6 +83,7 @@ AI4SE 框架构想(框内元素仅为示例,可能会装入更多实践): | | `qa-run-e2e` | 运行 E2E 用例集并定位失败 | | | `qa-write-manual-plan` | 编写手动测试与冒烟用例计划 | | **PM** | `pm-estimate` | 基于需求分类基线表估算工作量 | +| | `pm-start-iteration` | 按版本名建立迭代目录 | | | `pm-retro` | 复盘并把改进项回写到 harness 本身 | | **Runner** | `overnight-runner` | 队列跑已确认 plan(无角色前缀) | @@ -127,7 +133,7 @@ ba-grill-me → ba-write-spec → pm-estimate ```bash cd example-project cat AGENTS.md # 一份填满的工程规范范本 -ls .agents/skills/ # 已安装的 21 个 SDD skills +ls .agents/skills/ # 已安装的 26 个 SDD skills ``` ### 装到自己的新项目 @@ -169,7 +175,7 @@ node tool-chain-installer/scripts/install-tools.mjs ../my-project --group browse ``` team-harness-suite/ ├── AGENTS.md # 本仓库的架构与工程规范(改代码前先读) -├── agile-team-sdd/ # SDD 技能套件(21 个模板 + catalog.json + 安装脚本) +├── agile-team-sdd/ # SDD 技能套件(26 个模板 + catalog.json + 安装脚本) ├── harness-installer/ # AGENTS.md / docs 骨架初始化 ├── tool-chain-installer/ # MCP 工具链安装 ├── team-workflow-guide/ # 团队流程与角色手册 @@ -195,7 +201,7 @@ team-harness-suite/ | 模块 | 状态 | |---|---| -| `agile-team-sdd/` | ✅ 可用(21 个 skill) | +| `agile-team-sdd/` | ✅ 可用(26 个 skill) | | `harness-installer/` | ✅ 可用(`AGENTS.md` 模板含 TODO,需人工补全) | | `tool-chain-installer/` | ✅ 可用 | | `team-workflow-guide/` | ✅ 可用 | diff --git a/agents-workflow-engine/README.md b/agents-workflow-engine/README.md new file mode 100644 index 0000000..1156a37 --- /dev/null +++ b/agents-workflow-engine/README.md @@ -0,0 +1,37 @@ +# agents-workflow-engine + +一个人用主会话把一条迭代从启动调度到提测。图是 YAML。人、graph-master、子 agent 分三道泳道。子 agent 调用 skill,并且可以绑不同模型做对抗验证。 + +## 用法 + +在仓库根目录: + +```bash +PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine validate +PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine render --dry-run +PYTHONPATH=agents-workflow-engine python -m agents_workflow_engine run \ + --project <目标项目> --answers answers.yaml --agent '你的子 agent 命令' +``` + +`answers.yaml` 里,人的节点对应一段文字或「满意 / 不满意」。同一节点要答多次时写成列表。 + +子 agent 命令会额外收到 `--skill`、`--node`、`--model`。批量构建还会收到 `--task`。环境变量 `WORKFLOW_TASK` 是同一条任务。门禁要在标准输出单独一行打印 `满意` 或 `不满意`。`dev-plan` 用 `TASK: ` 宣布一批任务。 + +模型用环境变量,不写进仓库:`MODEL_WRITER`、`MODEL_REVIEWER`。两个值相同,或没设,会在 `.agents/workflow/decisions.jsonl` 记下「未做对抗验证」。 + +## 安装预设 + +```bash +./agents-workflow-engine/scripts/install.sh <目标项目> --dry-run +./agents-workflow-engine/scripts/install.sh <目标项目> +``` + +只写 `.agents/workflow/preset.yaml`。已存在则跳过,`--force` 才覆盖。不碰 `overlay.yaml`。 + +## 项目怎么改图 + +在目标项目放 `.agents/workflow/overlay.yaml`,可以 `disable` 节点、`replace` skill、改回路的 `maxIterations`。 + +## 维护 + +预设在 `presets/iteration-to-test.yaml`。形状说明在 `schema/graph.schema.json`。泳道预览在仓库 `.agents/plan/iteration-to-test.html`。 diff --git a/agents-workflow-engine/agents_workflow_engine/__init__.py b/agents-workflow-engine/agents_workflow_engine/__init__.py new file mode 100644 index 0000000..a73001c --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/__init__.py @@ -0,0 +1,5 @@ +"""agents-workflow-engine。""" + +from .cli import main + +__all__ = ["main"] diff --git a/agents-workflow-engine/agents_workflow_engine/__main__.py b/agents-workflow-engine/agents_workflow_engine/__main__.py new file mode 100644 index 0000000..bfdcd0c --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/__main__.py @@ -0,0 +1,4 @@ +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/agents-workflow-engine/agents_workflow_engine/cli.py b/agents-workflow-engine/agents_workflow_engine/cli.py new file mode 100644 index 0000000..8c27d3c --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/cli.py @@ -0,0 +1,153 @@ +"""命令行:validate / resolve / render / run。""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +from .errors import GraphError +from .load import load_overlay +from .load import load_preset +from .load import load_yaml +from .merge import merge +from .render_mermaid import render +from .runner import Runner +from .runner import spawn_agent +from .validate import validate +from .yaml_lite import loads + + +def _graph_from(args: argparse.Namespace) -> dict: + base = load_yaml(args.graph) if args.graph else load_preset() + overlay = load_overlay(args.project) + return merge(base, overlay) + + +def _print_warnings(warnings: list) -> None: + for warning in warnings: + print(warning, file=sys.stderr) + + +def cmd_validate(args: argparse.Namespace) -> int: + graph = _graph_from(args) + errors, warnings = validate(graph) + _print_warnings(warnings) + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + print("图有效:%s 个节点,%s 个警告" % (len(graph["nodes"]), len(warnings))) + return 0 + + +def cmd_resolve(args: argparse.Namespace) -> int: + graph = _graph_from(args) + errors, warnings = validate(graph) + _print_warnings(warnings) + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + print(json.dumps(graph, ensure_ascii=False, indent=2)) + return 0 + + +def cmd_render(args: argparse.Namespace) -> int: + graph = _graph_from(args) + errors, warnings = validate(graph) + _print_warnings(warnings) + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + text = render(graph) + if args.dry_run or not args.output: + sys.stdout.write(text) + return 0 + with open(args.output, "w", encoding="utf-8") as handle: + handle.write(text) + print("已写入 %s" % args.output) + return 0 + + +def _load_answers(path: str) -> dict: + if not path: + return {} + with open(path, "r", encoding="utf-8") as handle: + data = loads(handle.read()) + if not isinstance(data, dict): + raise GraphError("answers 文件的根必须是映射") + answers = {} + for key, value in data.items(): + if isinstance(value, list): + answers[key] = [str(item) for item in value] + else: + answers[key] = [str(value)] + return answers + + +def cmd_run(args: argparse.Namespace) -> int: + graph = _graph_from(args) + errors, warnings = validate(graph) + _print_warnings(warnings) + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + answers = _load_answers(args.answers) if args.answers else {} + log = [] # type: list + + def agent(node, model, task): + return spawn_agent(args.agent, node, model, task) + + runner = Runner(graph, answers, agent, args.master_model, log) + end = runner.run() + out_dir = os.path.join(args.project, ".agents", "workflow") + os.makedirs(out_dir, exist_ok=True) + path = os.path.join(out_dir, "decisions.jsonl") + with open(path, "a", encoding="utf-8") as handle: + for item in log: + handle.write(json.dumps(item, ensure_ascii=False) + "\n") + print("到达 %s,记录写在 %s" % (end, path)) + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="agents_workflow_engine", description="按项目的工作流图调度子 agent") + parser.add_argument("--project", default=".", help="目标项目目录,默认当前目录") + parser.add_argument("--graph", default="", help="图 YAML。缺省用套件预设") + sub = parser.add_subparsers(dest="command", required=True) + + validate_cmd = sub.add_parser("validate", help="校验预设叠覆盖之后的图") + validate_cmd.set_defaults(func=cmd_validate) + + resolve_cmd = sub.add_parser("resolve", help="打印合并后的图") + resolve_cmd.set_defaults(func=cmd_resolve) + + render_cmd = sub.add_parser("render", help="把图渲成 Mermaid") + render_cmd.add_argument("--dry-run", action="store_true", help="只打印,不写文件") + render_cmd.add_argument("--output", default="", help="写入的文件。缺省打印到标准输出") + render_cmd.set_defaults(func=cmd_render) + + run_cmd = sub.add_parser("run", help="主会话按图执行到提测") + run_cmd.add_argument("--answers", default="", help="人的答案 YAML") + run_cmd.add_argument("--agent", default="", help="子 agent 命令") + run_cmd.add_argument("--master-model", default=os.environ.get("MODEL_MASTER", "master"), help="主会话模型,子 agent 未配置时沿用") + run_cmd.set_defaults(func=cmd_run) + return parser + + +def main(argv: list = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + try: + return args.func(args) + except GraphError as exc: + print(str(exc), file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/agents-workflow-engine/agents_workflow_engine/errors.py b/agents-workflow-engine/agents_workflow_engine/errors.py new file mode 100644 index 0000000..830796e --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/errors.py @@ -0,0 +1,9 @@ +"""图的加载、合并、校验、渲染与运行共用的错误。""" + + +class GraphError(Exception): + """图不合法或跑不下去。消息里写明节点、原因和下一步。""" + + +class NeedInput(GraphError): + """图停在人的节点上,进度已记下。""" diff --git a/agents-workflow-engine/agents_workflow_engine/load.py b/agents-workflow-engine/agents_workflow_engine/load.py new file mode 100644 index 0000000..58440fb --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/load.py @@ -0,0 +1,47 @@ +"""读取预设图与覆盖文件。""" + +from __future__ import annotations + +import os +from typing import Any +from typing import Optional + +from .errors import GraphError +from .yaml_lite import YamlError +from .yaml_lite import loads + +PRESET_NAME = "iteration-to-test.yaml" + + +def package_root() -> str: + return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def preset_path() -> str: + return os.path.join(package_root(), "presets", PRESET_NAME) + + +def load_yaml(path: str) -> Any: + try: + with open(path, "r", encoding="utf-8") as handle: + text = handle.read() + except OSError as exc: + raise GraphError("读不到图文件 %s:%s" % (path, exc)) from exc + try: + data = loads(text) + except YamlError as exc: + raise GraphError("图文件 %s 不是合法 YAML:%s" % (path, exc)) from exc + if not isinstance(data, dict): + raise GraphError("图文件 %s 的根必须是映射" % path) + return data + + +def load_preset() -> dict: + return load_yaml(preset_path()) + + +def load_overlay(project: str) -> Optional[dict]: + path = os.path.join(project, ".agents", "workflow", "overlay.yaml") + if not os.path.isfile(path): + return None + return load_yaml(path) diff --git a/agents-workflow-engine/agents_workflow_engine/merge.py b/agents-workflow-engine/agents_workflow_engine/merge.py new file mode 100644 index 0000000..ae86193 --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/merge.py @@ -0,0 +1,45 @@ +"""把项目覆盖叠到预设图上。""" + +from __future__ import annotations + +import copy +from typing import Optional + +from .errors import GraphError + + +def merge(base: dict, overlay: Optional[dict]) -> dict: + graph = copy.deepcopy(base) + if not overlay: + return graph + disabled = set(overlay.get("disable") or []) + unknown = disabled - {node["id"] for node in graph.get("nodes") or []} + if unknown: + raise GraphError("覆盖要禁用的节点不存在:%s" % "、".join(sorted(unknown))) + graph["nodes"] = [node for node in graph["nodes"] if node["id"] not in disabled] + graph["edges"] = [ + edge for edge in graph.get("edges") or [] + if edge.get("from") not in disabled and edge.get("to") not in disabled + ] + by_id = {node["id"]: node for node in graph["nodes"]} + for node_id, fields in (overlay.get("replace") or {}).items(): + if node_id not in by_id: + raise GraphError("覆盖要替换的节点不存在:%s" % node_id) + if not isinstance(fields, dict): + raise GraphError("节点 %s 的替换内容必须是映射" % node_id) + by_id[node_id].update(fields) + loops_by_id = {loop["id"]: loop for loop in graph.get("loops") or []} + for loop in overlay.get("loops") or []: + if loop.get("id") not in loops_by_id: + raise GraphError("覆盖要改的回路不存在:%s" % loop.get("id")) + loops_by_id[loop["id"]].update(loop) + edges_by_id = {edge["id"]: edge for edge in graph["edges"]} + for edge in overlay.get("edges") or []: + if "id" not in edge: + raise GraphError("覆盖里的边必须有 id") + if edge["id"] in edges_by_id: + edges_by_id[edge["id"]].update(edge) + else: + graph["edges"].append(edge) + edges_by_id[edge["id"]] = edge + return graph diff --git a/agents-workflow-engine/agents_workflow_engine/render_mermaid.py b/agents-workflow-engine/agents_workflow_engine/render_mermaid.py new file mode 100644 index 0000000..8544fde --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/render_mermaid.py @@ -0,0 +1,44 @@ +"""把解析后的图写成 Mermaid。扩展节点不输出。""" + +from __future__ import annotations + + +def _shape(node: dict) -> str: + title = node.get("title") or node["id"] + if node.get("batch"): + title += " · 一批任务" + if node.get("repeatsBatch"): + title += " · 按批循环" + if node.get("sealed") and node.get("note"): + title += " / " + "、".join(node["note"]) + node_id = node["id"] + kind = node.get("kind") + if kind == "action": + return "%s(%s)" % (node_id, title) + if kind == "gate": + return "%s[[%s]]" % (node_id, title) + if kind == "decision": + return "%s{%s}" % (node_id, title) + if kind == "human_input": + return "%s[/%s/]" % (node_id, title) + if kind == "end": + return "%s([%s])" % (node_id, title) + if kind == "entry": + return "%s{{%s}}" % (node_id, title) + return "%s[%s]" % (node_id, title) + + +def render(graph: dict) -> str: + lines = ["flowchart LR"] + titles = (("human", "人"), ("master", "graph-master"), ("subagent", "子 agent")) + for actor, title in titles: + lines.append(" subgraph %s [%s]" % (actor, title)) + for node in graph.get("nodes") or []: + if node.get("actor") == actor: + lines.append(" " + _shape(node)) + lines.append(" end") + for edge in graph.get("edges") or []: + arrow = "-.->" if edge.get("back") else "-->" + label = "|%s|" % edge["when"] if edge.get("when") else "" + lines.append(" %s %s%s %s" % (edge["from"], arrow, label, edge["to"])) + return "\n".join(lines) + "\n" diff --git a/agents-workflow-engine/agents_workflow_engine/runner.py b/agents-workflow-engine/agents_workflow_engine/runner.py new file mode 100644 index 0000000..d6abe8c --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/runner.py @@ -0,0 +1,248 @@ +"""按图往下走:人答题,子 agent 执行 skill,主会话只调度。""" + +from __future__ import annotations + +import os +import shlex +import subprocess +from typing import Callable +from typing import Dict +from typing import List +from typing import Optional + +from .errors import GraphError +from .errors import NeedInput +from .validate import REVIEW_PAIRS +from .validate import node_map + + +def _plain_edges(edges: List[dict], node_id: str) -> List[dict]: + outgoing = [ + edge for edge in edges + if edge.get("from") == node_id and not edge.get("when") + ] + drop = set() + for edge in outgoing: + others = [item["to"] for item in outgoing if item is not edge] + for other in others: + if _can_reach(other, edge["to"], edges): + drop.add(edge["id"]) + return [edge for edge in outgoing if edge["id"] not in drop] + + +def _can_reach(start: str, target: str, edges: List[dict]) -> bool: + seen = set() + stack = [start] + while stack: + current = stack.pop() + if current == target: + return True + if current in seen: + continue + seen.add(current) + for edge in edges: + if edge.get("from") != current or edge.get("back") or edge.get("when"): + continue + stack.append(edge["to"]) + return False + + +def _when_edge(edges: List[dict], node_id: str, answer: str) -> dict: + for edge in edges: + if edge.get("from") == node_id and edge.get("when") == answer: + return edge + raise GraphError("节点 %s 没有「%s」这条出边" % (node_id, answer)) + + +def _loop_for(graph: dict, edge_id: str) -> Optional[dict]: + for loop in graph.get("loops") or []: + if edge_id in (loop.get("backEdges") or []): + return loop + return None + + +def _take_answer(answers: Dict[str, List[str]], node_id: str) -> str: + queue = answers.get(node_id) or [] + if not queue: + raise NeedInput( + "节点 %s 需要人的输入。进度已记下。补上 answers 后用同一个 --iteration 再执行 run" + % node_id + ) + return str(queue.pop(0)) + + +def _resolve_model(graph: dict, node: dict, master_model: str) -> str: + key = node.get("model") + models = graph.get("models") or {} + if not key or key not in models: + return master_model + spec = models[key] + if isinstance(spec, dict) and spec.get("env"): + return os.environ.get(str(spec["env"]), "") or master_model + return str(spec) or master_model + + +def _verdict(text: str) -> str: + for line in reversed(text.splitlines()): + line = line.strip() + if line in ("满意", "不满意"): + return line + if "不满意" in text: + return "不满意" + if "满意" in text: + return "满意" + raise GraphError("子 agent 没有给出「满意」或「不满意」。输出是:%s" % text.strip()[:200]) + + +def _tasks(text: str) -> List[str]: + found = [] + for line in text.splitlines(): + line = line.strip() + if line.startswith("TASK:"): + task = line[5:].strip() + if task: + found.append(task) + return found or ["task-1"] + + +class Runner: + def __init__(self, graph: dict, answers: Dict[str, List[str]], agent: Callable, master_model: str, log: List[dict], current: str = "", visits: Dict[str, int] = None, loop_counts: Dict[str, int] = None, tasks: List[str] = None, task_index: int = 0) -> None: + self.graph = graph + self.answers = answers + self.agent = agent + self.master_model = master_model + self.log = log + self.nodes = node_map(graph) + self.edges = graph.get("edges") or [] + self.current = current or graph["entry"] + self.visits = visits or {} + self.loop_counts = loop_counts or {} + self.tasks = list(tasks or []) + self.task_index = task_index + + def run(self) -> str: + current = self.current + guard = 0 + while guard < 500: + guard += 1 + self.current = current + node = self.nodes[current] + kind = node.get("kind") + if kind == "end": + self.log.append({"node": current, "event": "end", "title": node.get("title")}) + return current + if kind == "entry": + current = self._only(current) + continue + if kind == "human_input": + text = _take_answer(self.answers, current) + self.log.append({"node": current, "event": "human_input", "text": text}) + current = self._only(current) + continue + if kind == "decision": + choice = _take_answer(self.answers, current) + self.log.append({"node": current, "event": "decision", "choice": choice}) + current = self._follow_when(current, choice) + continue + if kind == "gate": + self._warn_pair(node) + result = self._call(node, None) + verdict = _verdict(result) + self.log.append({"node": current, "event": "gate", "verdict": verdict, "model": _resolve_model(self.graph, node, self.master_model)}) + current = self._follow_when(current, verdict) + continue + if kind == "action": + current = self._run_action(node) + continue + raise GraphError("节点 %s 的 kind 无法执行:%s" % (current, kind)) + raise GraphError("走了 500 步还没到终点,图里可能有死循环") + + def _run_action(self, node: dict) -> str: + node_id = node["id"] + if node.get("once") and self.visits.get(node_id): + return self._only(node_id) + if node.get("repeatsBatch"): + if self.task_index >= len(self.tasks): + return self._only(node_id) + task = self.tasks[self.task_index] + result = self._call(node, task) + self.visits[node_id] = self.visits.get(node_id, 0) + 1 + self.task_index += 1 + self.log.append({"node": node_id, "event": "batch-step", "task": task, "output": result}) + if self.task_index < len(self.tasks): + return node_id + return self._only(node_id) + result = self._call(node, None) + self.visits[node_id] = self.visits.get(node_id, 0) + 1 + self.log.append({"node": node_id, "event": "action", "output": result, "model": _resolve_model(self.graph, node, self.master_model)}) + if node.get("batch"): + self.tasks = _tasks(result) + self.task_index = 0 + self.log.append({"node": node_id, "event": "batch", "tasks": list(self.tasks)}) + return self._only(node_id) + + def _call(self, node: dict, task: Optional[str]) -> str: + model = _resolve_model(self.graph, node, self.master_model) + return self.agent(node, model, task) + + def _warn_pair(self, reviewer: dict) -> None: + for writer_id, reviewer_id in REVIEW_PAIRS: + if reviewer["id"] != reviewer_id: + continue + writer = self.nodes.get(writer_id) + if not writer: + return + left = _resolve_model(self.graph, writer, self.master_model) + right = _resolve_model(self.graph, reviewer, self.master_model) + if not left or not right or left == right: + self.log.append({ + "node": reviewer["id"], + "event": "model-check", + "warning": "未做对抗验证", + "writer": writer_id, + "writerModel": left, + "reviewerModel": right, + }) + + def _follow_when(self, node_id: str, answer: str) -> str: + edge = _when_edge(self.edges, node_id, answer) + if edge.get("back"): + loop = _loop_for(self.graph, edge["id"]) + if loop is None: + raise GraphError("打回边 %s 没有上限" % edge["id"]) + count = self.loop_counts.get(loop["id"], 0) + 1 + self.loop_counts[loop["id"]] = count + if count > int(loop["maxIterations"]): + raise GraphError( + "回路 %s 已打回 %s 次,达到上限 %s。请人工处理节点 %s 后再继续" + % (loop["id"], count - 1, loop["maxIterations"], node_id) + ) + return edge["to"] + + def _only(self, node_id: str) -> str: + chosen = _plain_edges(self.edges, node_id) + if len(chosen) != 1: + raise GraphError("节点 %s 有 %s 条向前的边,调度不知道走哪条" % (node_id, len(chosen))) + return chosen[0]["to"] + + +def spawn_agent(command: str, node: dict, model: str, task: Optional[str]) -> str: + if not command.strip(): + raise GraphError("没有配置子 agent 命令。run 时加上 --agent,例如 --agent 'opencode run'") + env = os.environ.copy() + env["WORKFLOW_SKILL"] = str(node.get("skill") or "") + env["WORKFLOW_NODE"] = node["id"] + env["WORKFLOW_MODEL"] = model + env["WORKFLOW_TASK"] = task or "" + argv = shlex.split(command) + ["--skill", str(node.get("skill") or ""), "--node", node["id"], "--model", model] + if task: + argv.extend(["--task", task]) + try: + completed = subprocess.run(argv, env=env, text=True, capture_output=True, check=False) + except OSError as exc: + raise GraphError("启动子 agent 失败:%s。命令是:%s" % (exc, command)) from exc + if completed.returncode != 0: + raise GraphError( + "子 agent 退出码 %s,节点 %s。stderr:%s" % (completed.returncode, node["id"], completed.stderr.strip()[:400]) + ) + return completed.stdout diff --git a/agents-workflow-engine/agents_workflow_engine/state.py b/agents-workflow-engine/agents_workflow_engine/state.py new file mode 100644 index 0000000..64f1ff6 --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/state.py @@ -0,0 +1,102 @@ +"""一个迭代一条 workflow,进度落在 state.json。""" + +from __future__ import annotations + +import json +import os +import re + +from .errors import GraphError + +_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") + + +def check_iteration(name: str) -> str: + if not name or not _NAME.match(name): + raise GraphError("迭代名不合法:%s。只用字母、数字、点、下划线和连字符" % name) + return name + + +def instance_dir(project: str, iteration: str) -> str: + return os.path.join(project, ".agents", "workflow", "iterations", check_iteration(iteration)) + + +def state_path(project: str, iteration: str) -> str: + return os.path.join(instance_dir(project, iteration), "state.json") + + +def decisions_path(project: str, iteration: str) -> str: + return os.path.join(instance_dir(project, iteration), "decisions.jsonl") + + +def load_state(project: str, iteration: str) -> dict: + path = state_path(project, iteration) + if not os.path.isfile(path): + return {} + with open(path, "r", encoding="utf-8") as handle: + data = json.load(handle) + if not isinstance(data, dict): + raise GraphError("进度文件损坏:%s" % path) + return data + + +def save_state(project: str, iteration: str, state: dict) -> str: + path = state_path(project, iteration) + os.makedirs(os.path.dirname(path), exist_ok=True) + temporary = path + ".tmp" + with open(temporary, "w", encoding="utf-8") as handle: + json.dump(state, handle, ensure_ascii=False, indent=2) + handle.write("\n") + os.replace(temporary, path) + logged = int(state.get("logged") or 0) + progress = state.get("progress") or [] + fresh = progress[logged:] + if fresh: + with open(decisions_path(project, iteration), "a", encoding="utf-8") as handle: + for item in fresh: + handle.write(json.dumps(item, ensure_ascii=False) + "\n") + state["logged"] = len(progress) + with open(temporary, "w", encoding="utf-8") as handle: + json.dump(state, handle, ensure_ascii=False, indent=2) + handle.write("\n") + os.replace(temporary, path) + return path + + +def list_states(project: str) -> list: + root = os.path.join(project, ".agents", "workflow", "iterations") + if not os.path.isdir(root): + return [] + found = [] + for name in sorted(os.listdir(root)): + path = os.path.join(root, name, "state.json") + if os.path.isfile(path): + with open(path, "r", encoding="utf-8") as handle: + found.append(json.load(handle)) + return found + + +def open_instance(project: str, iteration: str, entry: str) -> dict: + """没有记录就创建。已有记录就返回它,用来接着跑。已到提测则拒绝再开一条。""" + check_iteration(iteration) + existing = load_state(project, iteration) + if not existing: + state = { + "iteration": iteration, + "status": "running", + "current": entry, + "visits": {}, + "loopCounts": {}, + "tasks": [], + "taskIndex": 0, + "progress": [], + "logged": 0, + } + save_state(project, iteration, state) + return state + if existing.get("status") == "completed": + raise GraphError( + "迭代 %s 已经有一条 workflow,并且已经到提测。不能再创建一条。用 status --iteration %s 查看" + % (iteration, iteration) + ) + return existing diff --git a/agents-workflow-engine/agents_workflow_engine/validate.py b/agents-workflow-engine/agents_workflow_engine/validate.py new file mode 100644 index 0000000..3a87f07 --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/validate.py @@ -0,0 +1,174 @@ +"""校验解析后的图。错误阻断,模型未拉开只警告。""" + +from __future__ import annotations + +import os +from typing import Any + +WORK_KINDS = ("action", "gate", "decision", "human_input") +ACTORS = ("human", "master", "subagent") +REVIEW_PAIRS = ( + ("ba-write-spec", "ba-requirement-review"), + ("dev-plan", "dev-plan-review"), +) + + +def node_map(graph: dict) -> dict: + return {node["id"]: node for node in graph.get("nodes") or []} + + +def extension_ids(graph: dict) -> set: + found = set() + for ext in graph.get("extensions") or []: + for node in ext.get("nodes") or []: + if "id" in node: + found.add(node["id"]) + return found + + +def _model_value(graph: dict, node: dict) -> str: + key = node.get("model") + models = graph.get("models") or {} + if not key or key not in models: + return "" + spec = models[key] + if isinstance(spec, dict) and spec.get("env"): + return os.environ.get(str(spec["env"]), "") + return str(spec) + + +def validate(graph: dict) -> tuple: + """返回 (errors, warnings)。errors 非空时图不能跑。""" + errors = [] + warnings = [] + nodes = graph.get("nodes") or [] + edges = graph.get("edges") or [] + ids = [node.get("id") for node in nodes] + if len(ids) != len(set(ids)): + errors.append("节点 id 有重复") + by_id = {} + for node in nodes: + node_id = node.get("id") + if not node_id: + errors.append("有节点缺少 id") + continue + by_id[node_id] = node + kind = node.get("kind") + actor = node.get("actor") + if kind not in WORK_KINDS and kind not in ("entry", "end"): + errors.append("节点 %s 的 kind 不合法:%s" % (node_id, kind)) + if actor not in ACTORS: + errors.append("节点 %s 的 actor 必须是 human、master 或 subagent" % node_id) + if node.get("skill") and actor != "subagent": + errors.append("节点 %s 调用了 skill,actor 必须是 subagent" % node_id) + if kind == "end" and _outgoing(edges, node_id): + errors.append("终点 %s 不能有出边" % node_id) + if kind == "human_input" and len(_outgoing(edges, node_id)) > 1: + errors.append("人类输入 %s 只能有一条出边" % node_id) + if kind == "decision": + options = set(node.get("options") or []) + for edge in _outgoing(edges, node_id): + if edge.get("when") not in options: + errors.append("决策 %s 的出边 %s 不在选项里" % (node_id, edge.get("id"))) + if kind == "gate": + for edge in _outgoing(edges, node_id): + if edge.get("when") not in ("满意", "不满意"): + errors.append("门禁 %s 的出边 %s 只能是满意或不满意" % (node_id, edge.get("id"))) + + entries = [node["id"] for node in nodes if node.get("kind") == "entry"] + ends = [node["id"] for node in nodes if node.get("kind") == "end"] + if entries != [graph.get("entry")]: + errors.append("入口必须恰好是 entry 节点 %s" % graph.get("entry")) + if len(ends) != 1: + errors.append("必须恰好有一个终点") + + ext = extension_ids(graph) + notes = set() + for node in nodes: + if node.get("sealed"): + for item in node.get("note") or []: + notes.add(item) + known = set(by_id) | ext | notes + loops = graph.get("loops") or [] + back_to_loop = {} + for loop in loops: + if "maxIterations" not in loop: + errors.append("回路 %s 缺少 maxIterations" % loop.get("id")) + for edge_id in loop.get("backEdges") or []: + back_to_loop[edge_id] = loop + + for edge in edges: + edge_id = edge.get("id") + src = edge.get("from") + dst = edge.get("to") + if src not in by_id: + errors.append("边 %s 的起点不存在:%s" % (edge_id, src)) + if dst in notes: + errors.append("边 %s 指向了封死节点内部的步骤 %s,不能加边" % (edge_id, dst)) + elif dst in ext: + errors.append("边 %s 指向了未接入的扩展节点 %s" % (edge_id, dst)) + elif dst not in by_id: + errors.append("边 %s 的终点不存在:%s" % (edge_id, dst)) + if edge.get("back") and edge.get("when") and edge_id not in back_to_loop: + errors.append("打回边 %s 没有写入任何回路的上限" % edge_id) + if src in by_id and by_id[src].get("kind") in ("decision", "gate"): + if edge.get("when") not in ("满意", "不满意"): + errors.append("边 %s 从门禁或决策出发,when 只能是满意或不满意" % edge_id) + + batches = {node["id"] for node in nodes if node.get("batch")} + consumed = {node.get("repeatsBatch") for node in nodes if node.get("repeatsBatch")} + missing = batches - consumed + if missing: + errors.append("批量节点没有被消费:%s" % "、".join(sorted(missing))) + for node in nodes: + target = node.get("repeatsBatch") + if target and target not in by_id: + errors.append("节点 %s 要循环的批量节点不存在:%s" % (node["id"], target)) + + if graph.get("entry") in by_id and not errors: + reached = _reachable(graph["entry"], edges) + stranded = [node_id for node_id in by_id if node_id not in reached] + if stranded: + errors.append("这些节点从入口走不到:%s。覆盖可能把图切断了" % "、".join(stranded)) + + for writer_id, reviewer_id in REVIEW_PAIRS: + writer = by_id.get(writer_id) + reviewer = by_id.get(reviewer_id) + if not writer or not reviewer: + continue + left = _model_value(graph, writer) + right = _model_value(graph, reviewer) + if not left or not right: + warnings.append("未配置对抗模型:%s 与 %s 将沿用主会话模型" % (writer_id, reviewer_id)) + elif left == right: + warnings.append("未做对抗验证:%s 与 %s 使用了同一个模型" % (writer_id, reviewer_id)) + return errors, warnings + + +def _outgoing(edges: list, node_id: str) -> list: + return [edge for edge in edges if edge.get("from") == node_id] + + +def _reachable(entry: str, edges: list) -> set: + seen = set() + stack = [entry] + while stack: + current = stack.pop() + if current in seen: + continue + seen.add(current) + for edge in edges: + if edge.get("from") == current: + stack.append(edge.get("to")) + return seen + + +def _model_value(graph: dict, node: dict) -> str: + key = node.get("model") + models = graph.get("models") or {} + if not key or key not in models: + return "" + spec: Any = models[key] + if isinstance(spec, dict) and spec.get("env"): + return os.environ.get(str(spec["env"]), "") + return str(spec) diff --git a/agents-workflow-engine/agents_workflow_engine/yaml_lite.py b/agents-workflow-engine/agents_workflow_engine/yaml_lite.py new file mode 100644 index 0000000..2e0f736 --- /dev/null +++ b/agents-workflow-engine/agents_workflow_engine/yaml_lite.py @@ -0,0 +1,549 @@ +"""本模块自带的 YAML 子集解析器。 + +与 overnight-runner 的实现相同,但是一份拷贝:两个模块不许互相 import。 +零第三方依赖,Python 3.9+。 +""" + +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/agents-workflow-engine/presets/iteration-to-test.yaml b/agents-workflow-engine/presets/iteration-to-test.yaml new file mode 100644 index 0000000..5a61d87 --- /dev/null +++ b/agents-workflow-engine/presets/iteration-to-test.yaml @@ -0,0 +1,85 @@ +id: iteration-to-test +entry: graph-start +lanes: + - { id: human, title: 人 } + - { id: master, title: graph-master } + - { id: subagent, title: 子 agent } +models: + writer: { env: MODEL_WRITER } + reviewer: { env: MODEL_REVIEWER } +loops: + - id: spec + maxIterations: 3 + backEdges: [req-gate-reject, req-decision-reject] + - id: hld + maxIterations: 3 + backEdges: [hld-reject] + - id: dev + maxIterations: 3 + backEdges: [build-reject] +nodes: + - { id: graph-start, actor: master, kind: entry, title: 会话启动 } + - { id: start-version, actor: human, kind: human_input, title: 开始版本 } + - { id: pm-start-iteration, actor: subagent, kind: action, skill: pm-start-iteration, title: 开始迭代, model: writer } + - { id: write-spec, actor: human, kind: human_input, title: 编写规格 } + - { id: ba-write-spec, actor: subagent, kind: action, skill: ba-write-spec, title: 需求规格, model: writer } + - { id: ba-write-prototype, actor: subagent, kind: action, skill: ba-write-prototype, title: 原型, once: true, model: writer } + - { id: ba-requirement-review, actor: subagent, kind: gate, skill: ba-requirement-review, title: 需求质量门, model: reviewer } + - { id: requirement-decision, actor: human, kind: decision, title: 需求决策, options: [满意, 不满意] } + - { id: tech-brief, actor: human, kind: human_input, title: 技术高阶 } + - { id: tl-high-level-design, actor: subagent, kind: action, skill: tl-high-level-design, title: 技术高阶设计, once: true, model: writer } + - { id: hld-decision, actor: human, kind: decision, title: 高阶决策, options: [满意, 不满意] } + - { id: dev-plan, actor: subagent, kind: action, skill: dev-plan, title: 详细规划, batch: true, model: writer } + - { id: dev-plan-review, actor: subagent, kind: gate, skill: dev-plan-review, title: plan 质量门, model: reviewer } + - { id: plan-confirm, actor: human, kind: human_input, title: plan 确认 } + - { id: plan-decision, actor: human, kind: decision, title: plan 决策, options: [满意, 不满意] } + - { id: overnight-runner, actor: subagent, kind: action, skill: overnight-runner, title: 排本批顺序, model: writer } + - id: dev-build + actor: subagent + kind: action + skill: dev-build + title: 构建与自测 + sealed: true + repeatsBatch: dev-plan + model: writer + note: [后端 TDD, 前端 TDD, 构建/Lint, 前端 UI review, API 测试, 浏览器自测] + - { id: build-decision, actor: human, kind: decision, title: 构建决策, options: [满意, 不满意] } + - { id: amend-input, actor: human, kind: human_input, title: 修订输入 } + - { id: dev-plan-amend, actor: subagent, kind: action, skill: dev-plan-amend, title: 规划修订, model: writer } + - { id: handoff, actor: master, kind: end, title: 提测 } +extensions: + - id: qa + title: 测试 + linked: false + requires: pipeline + nodes: + - { id: qa-write-cases, kind: action, title: QA 用例 } + - { id: dev-create-mr, kind: action, title: 创建 MR/流水线部署 } + - { id: qa-run-e2e, kind: action, title: E2E 测试 } + - { id: manual-test, kind: human_input, title: 人工补测 } +edges: + - { id: e0, from: graph-start, to: start-version } + - { id: e1, from: start-version, to: pm-start-iteration } + - { id: e2, from: pm-start-iteration, to: write-spec } + - { id: e3, from: write-spec, to: ba-write-spec } + - { id: e4, from: ba-write-spec, to: ba-write-prototype } + - { id: e5, from: ba-write-spec, to: ba-requirement-review } + - { id: e6, from: ba-write-prototype, to: ba-requirement-review } + - { id: req-pass, from: ba-requirement-review, to: requirement-decision, when: 满意 } + - { id: req-gate-reject, from: ba-requirement-review, to: write-spec, when: 不满意, back: true } + - { id: req-decision-reject, from: requirement-decision, to: write-spec, when: 不满意, back: true } + - { id: e7, from: tech-brief, to: tl-high-level-design } + - { id: e8, from: tl-high-level-design, to: hld-decision } + - { id: req-ok, from: requirement-decision, to: tech-brief, when: 满意 } + - { id: hld-reject, from: hld-decision, to: tech-brief, when: 不满意, back: true } + - { id: hld-ok, from: hld-decision, to: dev-plan, when: 满意 } + - { id: e9, from: dev-plan, to: dev-plan-review } + - { id: plan-pass, from: dev-plan-review, to: plan-confirm, when: 满意 } + - { id: e10, from: plan-confirm, to: plan-decision } + - { id: plan-ok, from: plan-decision, to: overnight-runner, when: 满意 } + - { id: e11, from: overnight-runner, to: dev-build } + - { id: e12, from: dev-build, to: build-decision } + - { id: build-pass, from: build-decision, to: handoff, when: 满意 } + - { id: build-reject, from: build-decision, to: amend-input, when: 不满意, back: true } + - { id: e13, from: amend-input, to: dev-plan-amend } + - { id: e14, from: dev-plan-amend, to: dev-plan, back: true } diff --git a/agents-workflow-engine/schema/graph.schema.json b/agents-workflow-engine/schema/graph.schema.json new file mode 100644 index 0000000..4184753 --- /dev/null +++ b/agents-workflow-engine/schema/graph.schema.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "agents workflow graph", + "type": "object", + "required": ["id", "entry", "lanes", "nodes", "edges"], + "properties": { + "id": { "type": "string" }, + "entry": { "type": "string" }, + "lanes": { "type": "array" }, + "models": { "type": "object" }, + "loops": { "type": "array" }, + "nodes": { "type": "array" }, + "edges": { "type": "array" }, + "extensions": { "type": "array" } + } +} diff --git a/agents-workflow-engine/scripts/install.sh b/agents-workflow-engine/scripts/install.sh new file mode 100755 index 0000000..13606dc --- /dev/null +++ b/agents-workflow-engine/scripts/install.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# 把工作流预设安装到目标项目的 .agents/workflow/preset.yaml。 +# 不覆盖已有 overlay.yaml。 +# +# 用法: +# ./install.sh <目标项目目录> [--dry-run] [--force] +# +# --dry-run 只打印将要写的文件 +# --force 覆盖已有 preset.yaml + +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +PRESET="$ROOT/presets/iteration-to-test.yaml" +DRY_RUN=0 +FORCE=0 +TARGET="" + +usage() { + sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//' + exit "${1:-0}" +} + +while [ $# -gt 0 ]; do + case "$1" in + --dry-run) DRY_RUN=1 ;; + --force) FORCE=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="$(cd "$TARGET" && pwd)" +DEST="$PROJECT/.agents/workflow" +FILE="$DEST/preset.yaml" + +echo "agents-workflow-engine 安装器" +echo " 预设: $PRESET" +echo " 目标: $FILE" + +if [ "$DRY_RUN" -eq 1 ]; then + if [ -f "$FILE" ] && [ "$FORCE" -eq 0 ]; then + echo " 跳过: 已存在 preset.yaml(没有 --force)" + else + echo " 将写入 preset.yaml" + fi + echo " 不碰 overlay.yaml" + exit 0 +fi + +mkdir -p "$DEST" +if [ -f "$FILE" ] && [ "$FORCE" -eq 0 ]; then + echo " 跳过: 已存在 $FILE" + exit 0 +fi +tmp="$FILE.tmp.$$" +cp "$PRESET" "$tmp" +mv "$tmp" "$FILE" +echo " 已写入 $FILE" +echo " 未修改 overlay.yaml" diff --git a/agents-workflow-engine/tests/test_units.py b/agents-workflow-engine/tests/test_units.py new file mode 100644 index 0000000..f97fafd --- /dev/null +++ b/agents-workflow-engine/tests/test_units.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""agents-workflow-engine 单元测试。""" + +from __future__ import annotations + +import os +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from agents_workflow_engine.errors import GraphError # noqa: E402 +from agents_workflow_engine.load import load_preset # noqa: E402 +from agents_workflow_engine.merge import merge # noqa: E402 +from agents_workflow_engine.render_mermaid import render # noqa: E402 +from agents_workflow_engine.runner import Runner # noqa: E402 +from agents_workflow_engine.validate import validate # noqa: E402 +from agents_workflow_engine.yaml_lite import loads # noqa: E402 + + +def happy_answers(): + return { + "start-version": ["iteration1"], + "write-spec": ["登录"], + "requirement-decision": ["满意"], + "tech-brief": ["账号"], + "hld-decision": ["满意"], + "plan-confirm": ["确认"], + "plan-decision": ["满意"], + "build-decision": ["满意"], + } + + +def fake_agent(calls): + def run(node, model, task): + calls.append((node["id"], model, task)) + skill = node.get("skill") + if skill == "dev-plan": + return "TASK: a\nTASK: b\n" + if skill in ("ba-requirement-review", "dev-plan-review"): + return "满意\n" + return "ok\n" + return run + + +class PresetTest(unittest.TestCase): + def test_preset_valid_and_warns_when_model_unset(self): + graph = load_preset() + errors, warnings = validate(graph) + self.assertEqual(errors, []) + self.assertTrue(any("未配置对抗模型" in item for item in warnings)) + + def test_distinct_models_have_no_same_model_warning(self): + os.environ["MODEL_WRITER"] = "writer-a" + os.environ["MODEL_REVIEWER"] = "reviewer-b" + try: + errors, warnings = validate(load_preset()) + finally: + del os.environ["MODEL_WRITER"] + del os.environ["MODEL_REVIEWER"] + self.assertEqual(errors, []) + self.assertFalse(any("未做对抗验证" in item for item in warnings)) + self.assertFalse(any("未配置对抗模型" in item for item in warnings)) + + def test_render_shapes_and_hides_extensions(self): + text = render(load_preset()) + self.assertIn("flowchart LR", text) + self.assertIn("dev-plan(详细规划 · 一批任务)", text) + self.assertIn("ba-requirement-review[[需求质量门]]", text) + self.assertIn("start-version[/开始版本/]", text) + self.assertIn("requirement-decision{需求决策}", text) + self.assertIn("handoff([提测])", text) + self.assertIn("graph-start{{会话启动}}", text) + self.assertIn("后端 TDD", text) + self.assertNotIn("qa-write-cases", text) + self.assertIn("-.->|不满意|", text) + + def test_disable_prototype_still_reaches_end(self): + graph = merge(load_preset(), {"disable": ["ba-write-prototype"]}) + errors, _warnings = validate(graph) + self.assertEqual(errors, []) + self.assertNotIn("ba-write-prototype", {node["id"] for node in graph["nodes"]}) + + def test_edge_into_sealed_step_fails(self): + graph = load_preset() + graph["edges"].append({"id": "bad", "from": "dev-build", "to": "后端 TDD"}) + errors, _warnings = validate(graph) + self.assertTrue(any("封死" in item for item in errors)) + + def test_edge_into_extension_fails(self): + graph = load_preset() + graph["edges"].append({"id": "bad", "from": "handoff", "to": "qa-write-cases"}) + errors, _warnings = validate(graph) + self.assertTrue(any("扩展" in item for item in errors)) + + def test_back_edge_without_loop_fails(self): + graph = load_preset() + graph["loops"] = [loop for loop in graph["loops"] if loop["id"] != "spec"] + errors, _warnings = validate(graph) + self.assertTrue(any("没有写入任何回路" in item for item in errors)) + + def test_replace_skill(self): + graph = merge(load_preset(), {"replace": {"ba-write-spec": {"skill": "my-write-spec"}}}) + node = [item for item in graph["nodes"] if item["id"] == "ba-write-spec"][0] + self.assertEqual(node["skill"], "my-write-spec") + + +class RunTest(unittest.TestCase): + def test_happy_path_runs_build_once_per_task(self): + calls = [] + log = [] + end = Runner(load_preset(), happy_answers(), fake_agent(calls), "master", log).run() + self.assertEqual(end, "handoff") + build_calls = [item for item in calls if item[0] == "dev-build"] + self.assertEqual([item[2] for item in build_calls], ["a", "b"]) + self.assertTrue(any(item.get("event") == "batch" for item in log)) + + def test_spec_reject_then_pass(self): + calls = [] + answers = happy_answers() + answers["write-spec"] = ["第一稿", "第二稿"] + answers["requirement-decision"] = ["不满意", "满意"] + end = Runner(load_preset(), answers, fake_agent(calls), "master", []).run() + self.assertEqual(end, "handoff") + self.assertEqual(sum(1 for item in calls if item[0] == "ba-write-spec"), 2) + self.assertEqual(sum(1 for item in calls if item[0] == "ba-write-prototype"), 1) + + def test_loop_cap_stops(self): + answers = happy_answers() + answers["write-spec"] = ["a", "b", "c", "d"] + answers["requirement-decision"] = ["不满意", "不满意", "不满意", "不满意"] + with self.assertRaises(GraphError) as caught: + Runner(load_preset(), answers, fake_agent([]), "master", []).run() + self.assertIn("达到上限", str(caught.exception)) + + def test_missing_answer_names_the_node(self): + with self.assertRaises(GraphError) as caught: + Runner(load_preset(), {}, fake_agent([]), "master", []).run() + self.assertIn("start-version", str(caught.exception)) + + def test_same_model_is_logged(self): + os.environ["MODEL_WRITER"] = "same" + os.environ["MODEL_REVIEWER"] = "same" + log = [] + try: + Runner(load_preset(), happy_answers(), fake_agent([]), "master", log).run() + finally: + del os.environ["MODEL_WRITER"] + del os.environ["MODEL_REVIEWER"] + self.assertTrue(any(item.get("warning") == "未做对抗验证" for item in log)) + + def test_cli_run_writes_jsonl(self): + from agents_workflow_engine.cli import main + + with tempfile.TemporaryDirectory() as folder: + answers = os.path.join(folder, "answers.yaml") + with open(answers, "w", encoding="utf-8") as handle: + handle.write(loads and "") + text = "\n".join("%s: %s" % (key, value[0]) for key, value in happy_answers().items()) + "\n" + with open(answers, "w", encoding="utf-8") as handle: + handle.write(text) + agent = os.path.join(folder, "agent.sh") + with open(agent, "w", encoding="utf-8") as handle: + handle.write( + "#!/bin/sh\n" + "case \"$2\" in\n" + " dev-plan) printf 'TASK: a\\nTASK: b\\n' ;;\n" + " ba-requirement-review|dev-plan-review) printf '满意\\n' ;;\n" + " *) printf 'ok\\n' ;;\n" + "esac\n" + ) + os.chmod(agent, 0o755) + code = main(["--project", folder, "run", "--answers", answers, "--agent", agent]) + self.assertEqual(code, 0) + record = os.path.join(folder, ".agents", "workflow", "decisions.jsonl") + self.assertTrue(os.path.isfile(record)) + with open(record, encoding="utf-8") as handle: + body = handle.read() + self.assertIn("handoff", body) + self.assertIn('"task": "b"', body) + + +if __name__ == "__main__": + unittest.main() diff --git a/agile-team-sdd/README.md b/agile-team-sdd/README.md index 148f5be..7248bca 100644 --- a/agile-team-sdd/README.md +++ b/agile-team-sdd/README.md @@ -1,7 +1,7 @@ # agile-team-sdd SDD(Spec-Driven Development)技能套件的 **模板源**,覆盖 **BA → TL → PM → 开发 → QA → 发布 → 复盘** 全流程, -共 21 个 skill。 +共 26 个 skill。 ``` agile-team-sdd/ @@ -38,12 +38,16 @@ agile-team-sdd/ |---|---|---| | **BA** | `ba-grill-me` | 拷问需求,把模糊描述逼成可验收的规格 | | | `ba-write-spec` | 编写需求规格:字段表、业务规则、权限矩阵、验收标准;维护项目级术语表 | +| | `ba-write-prototype` | 按 spec 做原型 | +| | `ba-requirement-review` | 用另一个模型审查 spec,只回答满意或不满意 | | | `ba-gen-facts` | 从代码生成/校准事实文档:API、库表、领域模型、专题 | | | `ba-arch-sync-back` | 业务侧对齐术语/领域意图/产品 ↔ features 与 facts | | **TL** | `tl-arch-plan` | 写/更新项目级 `docs/architecture/`(C4、ADR) | | | `tl-arch-sync-back` | 技术侧对齐 ADR/C4 ↔ 实现与 facts 专题 | | | `tl-high-level-design` | 写迭代高阶技术设计(HLD / TRD),确认前不得开 Plan | | **Dev** | `dev-plan` | 实现前写技术方案(含 DST 自测用例与界面对照基线),等待人工确认 | +| | `dev-plan-review` | 用另一个模型审查 plan,只回答满意或不满意 | +| | `dev-plan-amend` | 按人的修订意见改 plan | | | `dev-build` | 全栈 LOOP:实现 + 自测/UI 落盘修到绿 + 代码评审 | | | `dev-self-test` | 真实本地环境按 DST 自测并落盘(由 build LOOP 调用,可单跑) | | | `dev-code-review` | 代码评审(由 build LOOP 调用,可单跑) | @@ -54,6 +58,7 @@ agile-team-sdd/ | | `qa-run-e2e` | 运行 E2E 用例集并定位失败 | | | `qa-write-manual-plan` | 编写手动测试与冒烟用例计划 | | **PM** | `pm-estimate` | 基于需求分类基线表估算工作量 | +| | `pm-start-iteration` | 按版本名建立迭代目录 | | | `pm-retro` | 复盘并把改进项回写到 harness | | **Runner** | `overnight-runner` | 队列跑已确认 plan(多队列、看门狗、决策留痕;无角色前缀) | diff --git a/agile-team-sdd/SKILL.md b/agile-team-sdd/SKILL.md index 3059ba1..ef90a69 100644 --- a/agile-team-sdd/SKILL.md +++ b/agile-team-sdd/SKILL.md @@ -1,6 +1,6 @@ --- name: agile-team-sdd -description: 安装 Agile Team SDD 技能套件(21 个 skill,覆盖 BA/TL/开发/QA/PM/runner)到指定项目。当用户说"安装 skills 到某个项目"、"把 SDD 流程装到 X 仓库"、"agile team sdd 安装"时使用。 +description: 安装 Agile Team SDD 技能套件(26 个 skill,覆盖 BA/TL/开发/QA/PM/runner)到指定项目。当用户说"安装 skills 到某个项目"、"把 SDD 流程装到 X 仓库"、"agile team sdd 安装"时使用。 --- # Agile Team SDD:安装技能套件 @@ -8,7 +8,7 @@ description: 安装 Agile Team SDD 技能套件(21 个 skill,覆盖 BA/TL/ 本目录是 **SDD(Spec-Driven Development)技能套件的模板源**。 `skills/` 下每个子目录是一份带占位符的 `SKILL.md`,需要先渲染成目标项目的真实路径,再安装过去。 -## 技能清单(21 个) +## 技能清单(26 个) 完整元数据见 [`catalog.json`](catalog.json)。 @@ -18,6 +18,8 @@ description: 安装 Agile Team SDD 技能套件(21 个 skill,覆盖 BA/TL/ |---|---|---| | `ba-grill-me` | 拷问需求,把模糊描述逼成可验收的规格 | 需求含糊、有多种理解时,写规格之前 | | `ba-write-spec` | 编写需求规格(字段表、业务规则、权限、验收标准),维护项目级术语表 | 需求已澄清,落成 `docs/features/<迭代>/-/spec.md`;术语写入 `docs/architecture/business/glossary.md` | +| `ba-write-prototype` | 按 spec 做一版原型 | 规格写完、需求质量门之前 | +| `ba-requirement-review` | 用另一个模型审查 spec,只回答满意或不满意 | 规格写完、人做需求决策之前 | | `ba-gen-facts` | 从代码生成/校准事实文档(API、库表、领域模型) | 实现变了,`docs/facts/` 与代码不一致 | | `ba-arch-sync-back` | 业务侧回写对齐术语/领域意图/产品 ↔ features 与 facts | 统一语言或领域结构相对 architecture 漂移时 | @@ -26,6 +28,8 @@ description: 安装 Agile Team SDD 技能套件(21 个 skill,覆盖 BA/TL/ | Skill | 作用 | 触发时机 | |---|---|---| | `dev-plan` | 写 `plan.md`(粗步骤 + **DST 自测用例** + 有 UI 时界面对照基线) | 新功能 / 重构 / 非简单变更 | +| `dev-plan-review` | 用另一个模型审查 plan,只回答满意或不满意 | plan 写成一批任务之后 | +| `dev-plan-amend` | 按人的修订意见改 plan | 构建决策不满意之后 | | `dev-build` | 全栈 LOOP:实现 → 自测/UI(**落盘记录修到绿**)→ 代码评审 | Plan 已确认,进入实现 | | `dev-self-test` | **真实本地环境** + 按 DST 执行并写 `*-self-test.md` | 实现后 / build LOOP 中 | | `dev-code-review` | 按项目规范做代码评审(build LOOP 调用,也可单跑) | build LOOP 中 / 审他人 MR | @@ -54,6 +58,7 @@ description: 安装 Agile Team SDD 技能套件(21 个 skill,覆盖 BA/TL/ | Skill | 作用 | 触发时机 | |---|---|---| | `pm-estimate` | 基于需求分类基线表估算工作量 | 需求进迭代前 | +| `pm-start-iteration` | 按版本名建立迭代目录 | 主会话拿到版本名之后 | | `pm-retro` | 复盘并把改进项回写到 harness 本身 | 迭代结束,或流程反复出问题 | ### Runner(无角色前缀) diff --git a/agile-team-sdd/catalog.json b/agile-team-sdd/catalog.json index 1d18755..2be5717 100644 --- a/agile-team-sdd/catalog.json +++ b/agile-team-sdd/catalog.json @@ -21,6 +21,28 @@ "ba-grill-me" ] }, + { + "name": "ba-write-prototype", + "description": "按 spec 做一版可点击原型,放到该迭代的 prototypes 目录", + "when": "规格写完、需求质量门之前,需要一版可对照的原型时", + "produces": [ + "docs/features/<迭代>/prototypes/" + ], + "dependsOn": [ + "ba-write-spec" + ] + }, + { + "name": "ba-requirement-review", + "description": "用与写规格不同的模型审查 spec,只回答满意或不满意", + "when": "规格和原型已写完,人做需求决策之前", + "produces": [ + "满意或不满意" + ], + "dependsOn": [ + "ba-write-spec" + ] + }, { "name": "ba-gen-facts", "description": "从代码与文档生成/校准事实文档(API、库表、领域模型、专题)", @@ -51,6 +73,28 @@ ], "dependsOn": [] }, + { + "name": "dev-plan-review", + "description": "用与写 plan 不同的模型审查技术方案,只回答满意或不满意", + "when": "dev-plan 写出一批任务之后、人确认 plan 之前", + "produces": [ + "满意或不满意" + ], + "dependsOn": [ + "dev-plan" + ] + }, + { + "name": "dev-plan-amend", + "description": "按人的修订意见改 plan,让它重新成为一批可执行任务", + "when": "构建决策不满意、人写完修订输入之后", + "produces": [ + "docs/features/<迭代>/-/plan.md" + ], + "dependsOn": [ + "dev-plan" + ] + }, { "name": "dev-debug", "description": "用 chrome-devtools-mcp 调试前端与后端问题", @@ -172,6 +216,15 @@ ], "dependsOn": [] }, + { + "name": "pm-start-iteration", + "description": "按人给出的版本名建立迭代目录", + "when": "主会话拿到版本名、编写规格之前", + "produces": [ + "docs/features/<版本名>/iteration.md" + ], + "dependsOn": [] + }, { "name": "pm-retro", "description": "复盘并把改进项回写到 harness 本身", diff --git a/agile-team-sdd/skills/ba-requirement-review-template/SKILL.md b/agile-team-sdd/skills/ba-requirement-review-template/SKILL.md new file mode 100644 index 0000000..6779d91 --- /dev/null +++ b/agile-team-sdd/skills/ba-requirement-review-template/SKILL.md @@ -0,0 +1,24 @@ +--- +name: ba-requirement-review-template +description: 用与写规格不同的模型审查 spec,只回答满意或不满意。需求规格和原型写完之后、人做需求决策之前使用。 +--- + + +> **这是模板文件。** 路径由 `{{PLACEHOLDER}}` 占位符标记,执行 `agile-team-sdd/install.sh` 时会被替换为目标项目的真实路径。 + + +# 需求质量门 + +读 `{{FEATURES_DIR}}/<迭代>/-/spec.md`。这是对抗验证,不要沿用写规格时的模型。 + +## 检查 + +- 验收标准能不能单独拿去测 +- 字段、角色、错误情况是否写全 +- 术语是否指向 `{{GLOSSARY_FILE}}` + +## 输出 + +最后一行只能是 `满意` 或 `不满意`。 + +不满意时,在前面用短句列出要改的点。不要改 spec 本身。 diff --git a/agile-team-sdd/skills/ba-write-prototype-template/SKILL.md b/agile-team-sdd/skills/ba-write-prototype-template/SKILL.md new file mode 100644 index 0000000..e919131 --- /dev/null +++ b/agile-team-sdd/skills/ba-write-prototype-template/SKILL.md @@ -0,0 +1,23 @@ +--- +name: ba-write-prototype-template +description: 按已写好的需求规格做一版可点击原型,放到该迭代的 prototypes 目录。规格写完、需求质量门之前使用。只做一次。 +--- + + +> **这是模板文件。** 路径由 `{{PLACEHOLDER}}` 占位符标记,执行 `agile-team-sdd/install.sh` 时会被替换为目标项目的真实路径。 + + +# 编写原型 + +对照 `{{FEATURES_DIR}}/<迭代>/-/spec.md` 的字段和页面,做一版原型。 + +## 输出 + +- 原型放在 `{{FEATURES_DIR}}/<迭代>/prototypes/` +- 在原型目录的 README 里写清怎么启动、端口、对应哪份 spec + +## 硬性约束 + +- 没有 spec 就停止 +- 不改后端实现 +- 同一份 spec 已经有原型时,只补缺的页面,不另起一套 diff --git a/agile-team-sdd/skills/dev-plan-amend-template/SKILL.md b/agile-team-sdd/skills/dev-plan-amend-template/SKILL.md new file mode 100644 index 0000000..8e6c588 --- /dev/null +++ b/agile-team-sdd/skills/dev-plan-amend-template/SKILL.md @@ -0,0 +1,23 @@ +--- +name: dev-plan-amend-template +description: 按人给出的修订意见改已有 plan,让它重新成为一批可执行任务。构建决策不满意、人写完修订输入之后使用。 +--- + + +> **这是模板文件。** 路径由 `{{PLACEHOLDER}}` 占位符标记,执行 `agile-team-sdd/install.sh` 时会被替换为目标项目的真实路径。 + + +# 修订规划 + +读人刚刚写的修订意见,改对应的 `plan.md`。 + +## 做法 + +1. 只改意见点到的任务,不要整篇重写 +2. 改完的结果仍然是一批任务,每条都能单独交给 `dev-build` +3. 受影响的 DST 一起改 + +## 硬性约束 + +- 没有人的修订意见就停止 +- 不直接改实现代码 diff --git a/agile-team-sdd/skills/dev-plan-review-template/SKILL.md b/agile-team-sdd/skills/dev-plan-review-template/SKILL.md new file mode 100644 index 0000000..3a2f4c3 --- /dev/null +++ b/agile-team-sdd/skills/dev-plan-review-template/SKILL.md @@ -0,0 +1,24 @@ +--- +name: dev-plan-review-template +description: 用与写 plan 不同的模型审查技术方案,只回答满意或不满意。dev-plan 写出一批任务之后、人确认 plan 之前使用。 +--- + + +> **这是模板文件。** 路径由 `{{PLACEHOLDER}}` 占位符标记,执行 `agile-team-sdd/install.sh` 时会被替换为目标项目的真实路径。 + + +# plan 质量门 + +读对应的 `plan.md`。这是对抗验证,不要沿用写 plan 时的模型。 + +## 检查 + +- 是不是一批可分开执行的任务,而不是一整段叙述 +- DST 自测是否可执行,有界面时是否有对照基线 +- 有没有把实现细节写成无法验证的愿望 + +## 输出 + +最后一行只能是 `满意` 或 `不满意`。 + +不满意时列出要改的任务。不要直接改 plan。 diff --git a/agile-team-sdd/skills/pm-start-iteration-template/SKILL.md b/agile-team-sdd/skills/pm-start-iteration-template/SKILL.md new file mode 100644 index 0000000..9450180 --- /dev/null +++ b/agile-team-sdd/skills/pm-start-iteration-template/SKILL.md @@ -0,0 +1,28 @@ +--- +name: pm-start-iteration-template +description: 根据人给出的版本名启动一次迭代,建立 docs/features 下的迭代目录。当 graph 主会话进入「开始版本」之后、编写规格之前使用。 +--- + + +> **这是模板文件。** 路径由 `{{PLACEHOLDER}}` 占位符标记,执行 `agile-team-sdd/install.sh` 时会被替换为目标项目的真实路径。 + + +# 启动迭代 + +主会话已经问过人「开始版本」。本 skill 只负责把这次迭代的目录落下来。 + +## 输入 + +- 版本名,例如 `iteration1` +- 一句话范围 + +## 做法 + +1. 在 `{{FEATURES_DIR}}/<版本名>/` 建立目录(已存在则不覆盖里面的规格) +2. 写 `{{FEATURES_DIR}}/<版本名>/iteration.md`:版本名、范围、日期 +3. 不要写 spec,不要写 plan + +## 硬性约束 + +- 版本名只含字母、数字、连字符 +- 不创建 feature 子目录;那是 `ba-write-spec` 的事 diff --git a/example-project/.agents/skills/ba-requirement-review/SKILL.md b/example-project/.agents/skills/ba-requirement-review/SKILL.md new file mode 100644 index 0000000..306330e --- /dev/null +++ b/example-project/.agents/skills/ba-requirement-review/SKILL.md @@ -0,0 +1,20 @@ +--- +name: ba-requirement-review +description: 用与写规格不同的模型审查 spec,只回答满意或不满意。需求规格和原型写完之后、人做需求决策之前使用。 +--- + +# 需求质量门 + +读 `docs/features/<迭代>/-/spec.md`。这是对抗验证,不要沿用写规格时的模型。 + +## 检查 + +- 验收标准能不能单独拿去测 +- 字段、角色、错误情况是否写全 +- 术语是否指向 `docs/architecture/business/glossary.md` + +## 输出 + +最后一行只能是 `满意` 或 `不满意`。 + +不满意时,在前面用短句列出要改的点。不要改 spec 本身。 diff --git a/example-project/.agents/skills/ba-write-prototype/SKILL.md b/example-project/.agents/skills/ba-write-prototype/SKILL.md new file mode 100644 index 0000000..12a822e --- /dev/null +++ b/example-project/.agents/skills/ba-write-prototype/SKILL.md @@ -0,0 +1,19 @@ +--- +name: ba-write-prototype +description: 按已写好的需求规格做一版可点击原型,放到该迭代的 prototypes 目录。规格写完、需求质量门之前使用。只做一次。 +--- + +# 编写原型 + +对照 `docs/features/<迭代>/-/spec.md` 的字段和页面,做一版原型。 + +## 输出 + +- 原型放在 `docs/features/<迭代>/prototypes/` +- 在原型目录的 README 里写清怎么启动、端口、对应哪份 spec + +## 硬性约束 + +- 没有 spec 就停止 +- 不改后端实现 +- 同一份 spec 已经有原型时,只补缺的页面,不另起一套 diff --git a/example-project/.agents/skills/dev-plan-amend/SKILL.md b/example-project/.agents/skills/dev-plan-amend/SKILL.md new file mode 100644 index 0000000..2e6f9cc --- /dev/null +++ b/example-project/.agents/skills/dev-plan-amend/SKILL.md @@ -0,0 +1,19 @@ +--- +name: dev-plan-amend +description: 按人给出的修订意见改已有 plan,让它重新成为一批可执行任务。构建决策不满意、人写完修订输入之后使用。 +--- + +# 修订规划 + +读人刚刚写的修订意见,改对应的 `plan.md`。 + +## 做法 + +1. 只改意见点到的任务,不要整篇重写 +2. 改完的结果仍然是一批任务,每条都能单独交给 `dev-build` +3. 受影响的 DST 一起改 + +## 硬性约束 + +- 没有人的修订意见就停止 +- 不直接改实现代码 diff --git a/example-project/.agents/skills/dev-plan-review/SKILL.md b/example-project/.agents/skills/dev-plan-review/SKILL.md new file mode 100644 index 0000000..76d8975 --- /dev/null +++ b/example-project/.agents/skills/dev-plan-review/SKILL.md @@ -0,0 +1,20 @@ +--- +name: dev-plan-review +description: 用与写 plan 不同的模型审查技术方案,只回答满意或不满意。dev-plan 写出一批任务之后、人确认 plan 之前使用。 +--- + +# plan 质量门 + +读对应的 `plan.md`。这是对抗验证,不要沿用写 plan 时的模型。 + +## 检查 + +- 是不是一批可分开执行的任务,而不是一整段叙述 +- DST 自测是否可执行,有界面时是否有对照基线 +- 有没有把实现细节写成无法验证的愿望 + +## 输出 + +最后一行只能是 `满意` 或 `不满意`。 + +不满意时列出要改的任务。不要直接改 plan。 diff --git a/example-project/.agents/skills/pm-start-iteration/SKILL.md b/example-project/.agents/skills/pm-start-iteration/SKILL.md new file mode 100644 index 0000000..068f12f --- /dev/null +++ b/example-project/.agents/skills/pm-start-iteration/SKILL.md @@ -0,0 +1,24 @@ +--- +name: pm-start-iteration +description: 根据人给出的版本名启动一次迭代,建立 docs/features 下的迭代目录。当 graph 主会话进入「开始版本」之后、编写规格之前使用。 +--- + +# 启动迭代 + +主会话已经问过人「开始版本」。本 skill 只负责把这次迭代的目录落下来。 + +## 输入 + +- 版本名,例如 `iteration1` +- 一句话范围 + +## 做法 + +1. 在 `docs/features/<版本名>/` 建立目录(已存在则不覆盖里面的规格) +2. 写 `docs/features/<版本名>/iteration.md`:版本名、范围、日期 +3. 不要写 spec,不要写 plan + +## 硬性约束 + +- 版本名只含字母、数字、连字符 +- 不创建 feature 子目录;那是 `ba-write-spec` 的事