Commit bd1636b34dd90e5c03aa2e6c12289fa3f656a2b8

Authored by yibo
1 parent e1f71cf1

feat(devloop): P1 Docs MVP — PM + Architect produce full PRD/SDD site via mock mode

Implements the §P1 acceptance gate from plan-migration.md: a single
POST /api/devloop/projects produces a runnable todo-demo project with
multi-page PRD/SDD sites, units.json, integration spec, agent-state,
and history snapshots — all via mock agents (no real Claude CLI cost).

Code additions:
- packages/acp-core/protocol/ClaudeCliProtocol.js
  * mock mode now emits an extra `mock/files` acp_event when the fixture
    contains a files[] array. LoopController applies it to the project
    root, letting mock agents produce real outputs.
- server/src/core/devloop/loop-controller.js (now ~280 lines)
  * callAgent(pid, agentName, prompt, opts) — single-agent invocation:
    reads system/templates/{agent}/prompt.md, runs mock protocol,
    applies fixture files[], timeline-logs, auto-commits.
  * runDocsPhase(pid, requirement) — orchestrates PM → Architect with
    `docs.complete` timeline marker.
  * getProjectState(pid) — returns project.json + units + prd_rev/sdd_rev
    + timeline tail for the GET /state endpoint.
- server/routes/devloop.js (new)
  * POST /api/devloop/projects — createProject + runDocsPhase
  * GET  /api/devloop/projects
  * GET  /api/devloop/projects/:pid/state
- server/index.js / server/agent-server.js — mount /api/devloop.

Mock fixtures (drive the full acceptance file tree):
- fixtures/devloop-mock/devloop-pm.json
  * 14 files: prd/{index,reading-guide,product/*,feature/*,flow/*,prototype/*}.html,
    prd/assets/{shell.css,shell.js,search-index.json},
    agent-state/{pm.json,pm-todo.json}, history/prd-rev-001.html.
- fixtures/devloop-mock/devloop-architect.json
  * 13 files: sdd/{index,mvcp/*}.html, sdd/assets/*,
    units.json (3 units, DAG), integration/spec.json,
    agent-state/{architect.json,architect-todo.json}, history/sdd-rev-001.html.

Acceptance:
- scripts/phase1-verify.js — spins ephemeral express app, POSTs the
  todo-demo project, asserts 23 expected paths exist + 3 units with
  l2_rounds/l2_budget + git ≥4 commits + timeline events.

Tests (12 new cases):
- server/tests/devloop/loop-controller.test.js (7) — callAgent +
  runDocsPhase + state.
- server/tests/devloop/routes.test.js (5) — POST validation, full
  POST, GET state, 404 on unknown pid.

Results:
- phase0-verify: 8/8
- phase0-test-call: 7/7
- phase1-verify: 7/7
- vitest devloop+acp-core: 174/174 (was 162 → +12)

Specs: docs/prd/newfunction/_spec/plan-migration.md · P1 Docs MVP

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
fixtures/devloop-mock/devloop-architect.json 0 → 100644
  1 +{
  2 + "_doc": "Mock fixture for Architect Agent — drives P1 acceptance (todo-demo project). Produces SDD multi-page site + units.json (3 units) + integration/spec.json + architect agent-state + history snapshot.",
  3 + "chunks": [
  4 + "## 第 1 步: 读 PRD\n",
  5 + "已读 prd/feature/feature-tree.html — 3 个 Unit。\n",
  6 + "\n## 第 2 步: 写 sdd/mvcp/\n",
  7 + "model · view · control · process\n",
  8 + "\n## 第 3 步: 写 units.json + integration/spec.json\n",
  9 + "todo-be / todo-fe / todo-db,DAG 无环。\n",
  10 + "\n## 完成\n",
  11 + "SDD v1 已交付,units.json l2_rounds 初值 0/3。\n"
  12 + ],
  13 + "result": "mock-ok devloop-architect: SDD v1 + 3 units + 1 integration case",
  14 + "files": [
  15 + {
  16 + "path": "sdd/index.html",
  17 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>SDD · todo-demo</title><link rel=\"stylesheet\" href=\"assets/shell.css\"></head><body data-page=\"index.html\"><article data-doc=\"sdd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"system@2026-05-13T10:01:00.000Z\"><h3>SDD 首页</h3><p>todo-demo · M/V/C/P 设计</p><table><tr><th>层</th><th>页</th></tr><tr><td>M</td><td>mvcp/model.html</td></tr></table><pre>M -> V -> C -> P</pre><svg width=\"100\" height=\"20\"><line x1=\"0\" y1=\"10\" x2=\"100\" y2=\"10\" marker-end=\"url(#a)\"/></svg><div class=\"card\">导航</div></section></article><script src=\"assets/shell.js\"></script></body></html>"
  18 + },
  19 + {
  20 + "path": "sdd/mvcp/model.html",
  21 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>Model</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"mvcp/model.html\"><article data-doc=\"sdd\" data-rev=\"1\"><section data-rev=\"1\" data-unit-id=\"todo-be\"><h3>M-1 Todo Entity</h3><p>{ id:int, text:str, done:bool, created_at:ISO }</p><table><tr><th>field</th><th>type</th></tr><tr><td>id</td><td>integer</td></tr><tr><td>text</td><td>string</td></tr></table><pre>schema: id PK · text NOT NULL</pre><svg width=\"80\" height=\"20\"><rect width=\"80\" height=\"20\" fill=\"#eef\"/></svg><div class=\"card\">model</div></section><section data-rev=\"1\" data-unit-id=\"todo-fe\"><h3>M-2 FE State</h3><p>list: Todo[]; loading: bool</p><table><tr><td>list</td><td>Todo[]</td></tr></table><pre>vue ref</pre><svg width=\"40\" height=\"20\"><line x1=\"0\" y1=\"10\" x2=\"40\" y2=\"10\"/></svg><div class=\"card\">fe</div></section><section data-rev=\"1\" data-unit-id=\"todo-db\"><h3>M-3 DB Schema</h3><p>CREATE TABLE todos(id INTEGER PRIMARY KEY,text TEXT,done INT,created_at TEXT);</p><table><tr><td>todos</td><td>table</td></tr></table><pre>sqlite</pre><svg width=\"40\" height=\"20\"></svg><div class=\"card\">db</div></section></article></body></html>"
  22 + },
  23 + {
  24 + "path": "sdd/mvcp/view.html",
  25 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>View</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"mvcp/view.html\"><article data-doc=\"sdd\" data-rev=\"1\"><section data-rev=\"1\" data-unit-id=\"todo-fe\"><h3>V-1 列表组件</h3><p>顶部 input + 按钮 + 列表。</p><table><tr><th>组件</th><th>事件</th></tr><tr><td>TodoList</td><td>load/add</td></tr></table><pre>Vue SFC: TodoList.vue</pre><svg width=\"60\" height=\"40\"><rect x=\"5\" y=\"5\" width=\"50\" height=\"10\" fill=\"#fff\" stroke=\"#999\"/></svg><div class=\"card\">UI</div></section></article></body></html>"
  26 + },
  27 + {
  28 + "path": "sdd/mvcp/control.html",
  29 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>Control</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"mvcp/control.html\"><article data-doc=\"sdd\" data-rev=\"1\"><section data-rev=\"1\" data-unit-id=\"todo-be\"><h3>C-1 POST /todos</h3><p>Body: { text }; Resp 201: { id, text, done:false, created_at }</p><table><tr><th>field</th><th>req</th></tr><tr><td>text</td><td>true</td></tr></table><pre>POST /todos</pre><svg width=\"40\" height=\"20\"></svg><div class=\"card\">api</div></section><section data-rev=\"1\" data-unit-id=\"todo-be\"><h3>C-2 GET /todos</h3><p>Resp 200: Todo[]</p><table><tr><td>list</td><td>Todo[]</td></tr></table><pre>GET /todos</pre><svg width=\"40\" height=\"20\"></svg><div class=\"card\">api</div></section></article></body></html>"
  30 + },
  31 + {
  32 + "path": "sdd/mvcp/process.html",
  33 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>Process</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"mvcp/process.html\"><article data-doc=\"sdd\" data-rev=\"1\"><section data-rev=\"1\" data-unit-id=\"todo-be\"><h3>P-1 启动流程</h3><p>node server.js → listen $PORT → ready</p><table><tr><th>step</th><th>action</th></tr><tr><td>1</td><td>spawn</td></tr></table><pre>spawn -> listen -> ready</pre><svg width=\"60\" height=\"20\"><line x1=\"0\" y1=\"10\" x2=\"60\" y2=\"10\" marker-end=\"url(#a)\" stroke-dasharray=\"3 2\"/></svg><div class=\"card\">proc</div></section></article></body></html>"
  34 + },
  35 + {
  36 + "path": "sdd/assets/shell.css",
  37 + "content": "/* sdd shell.css placeholder */\nbody { font-family: system-ui; }\n.card { padding: 6px; border: 1px solid #ddd; }\n"
  38 + },
  39 + {
  40 + "path": "sdd/assets/shell.js",
  41 + "content": "/* sdd shell.js placeholder */\nconsole.log('[devloop-sdd] shell loaded');\n"
  42 + },
  43 + {
  44 + "path": "sdd/assets/search-index.json",
  45 + "content": "{\"version\":\"1\",\"pages\":5,\"entries\":[]}"
  46 + },
  47 + {
  48 + "path": "units.json",
  49 + "content": "{\n \"rev\": 1,\n \"created_at\": \"2026-05-13T10:01:00.000Z\",\n \"units\": [\n {\n \"id\": \"todo-db\",\n \"kind\": \"db\",\n \"description\": \"SQLite schema for todos table\",\n \"depends_on\": [],\n \"contract_hash\": \"sha256:0000000000000001\",\n \"l2_rounds\": 0,\n \"l2_budget\": 3\n },\n {\n \"id\": \"todo-be\",\n \"kind\": \"be\",\n \"description\": \"Express API for /todos\",\n \"depends_on\": [\"todo-db\"],\n \"contract_hash\": \"sha256:0000000000000002\",\n \"l2_rounds\": 0,\n \"l2_budget\": 3\n },\n {\n \"id\": \"todo-fe\",\n \"kind\": \"fe\",\n \"description\": \"Vue list page\",\n \"depends_on\": [\"todo-be\"],\n \"contract_hash\": \"sha256:0000000000000003\",\n \"l2_rounds\": 0,\n \"l2_budget\": 3\n }\n ]\n}\n"
  50 + },
  51 + {
  52 + "path": "integration/spec.json",
  53 + "content": "{\n \"rev\": 1,\n \"created_at\": \"2026-05-13T10:01:00.000Z\",\n \"cases\": [\n {\n \"id\": \"case-add-list\",\n \"title\": \"add a todo then list shows it\",\n \"involves\": [\"todo-be\", \"todo-db\"],\n \"steps\": [\n { \"unit\": \"todo-be\", \"call\": \"POST /todos\", \"body\": { \"text\": \"buy milk\" }, \"expect\": { \"status\": 201, \"json\": { \"id\": \"$.id\", \"text\": \"buy milk\" } } },\n { \"unit\": \"todo-be\", \"call\": \"GET /todos\", \"expect\": { \"status\": 200 } }\n ]\n }\n ]\n}\n"
  54 + },
  55 + {
  56 + "path": "history/sdd-rev-001.html",
  57 + "content": "<!doctype html><html><head><title>SDD rev 1 snapshot</title></head><body><article data-doc=\"sdd\" data-rev=\"1\"><section data-rev=\"1\"><h3>Snapshot</h3><p>Archive of SDD rev 1, see sdd/ for live version.</p></section></article></body></html>"
  58 + },
  59 + {
  60 + "path": "agent-state/architect.json",
  61 + "content": "{\"agent\":\"devloop-architect\",\"status\":\"idle\",\"current_step\":6,\"total_steps\":6,\"last_call_id\":\"call-mock-architect\",\"updated_at\":\"2026-05-13T10:01:01.000Z\"}"
  62 + },
  63 + {
  64 + "path": "agent-state/architect-todo.json",
  65 + "content": "{\"agent\":\"devloop-architect\",\"call_id\":\"call-mock-architect\",\"created_at\":\"2026-05-13T10:01:00.000Z\",\"items\":[{\"id\":\"step-001\",\"description\":\"bootstrap_sdd_site\",\"status\":\"done\",\"depends_on\":[]},{\"id\":\"step-002\",\"description\":\"write mvcp/model.html\",\"status\":\"done\",\"depends_on\":[\"step-001\"]},{\"id\":\"step-003\",\"description\":\"write mvcp/{view,control,process}.html\",\"status\":\"done\",\"depends_on\":[\"step-002\"]},{\"id\":\"step-004\",\"description\":\"write units.json (3 units, DAG)\",\"status\":\"done\",\"depends_on\":[\"step-003\"]},{\"id\":\"step-005\",\"description\":\"write integration/spec.json\",\"status\":\"done\",\"depends_on\":[\"step-004\"]},{\"id\":\"step-006\",\"description\":\"validate_sdd_consistency + archive\",\"status\":\"done\",\"depends_on\":[\"step-005\"]}],\"current\":null,\"progress_pct\":100}"
  66 + }
  67 + ]
  68 +}
... ...
fixtures/devloop-mock/devloop-pm.json
1 1 {
  2 + "_doc": "Mock fixture for PM Agent — drives P1 acceptance (todo-demo project). Produces the full PRD multi-page site + pm agent-state + history snapshot.",
2 3 "chunks": [
3 4 "## 第 1 步: 解析 idea\n",
4   - "用户需求是构建一个最小可行的 DevLoop demo。\n",
5   - "\n## 第 2 步: 写 prd 站点\n",
6   - "(在真实运行时这里会调 bootstrap_prd_site + write_chapter)\n",
  5 + "用户要求做一个 TODO 列表 API + Vue 前端。\n",
  6 + "\n## 第 2 步: 初始化 prd/ 站点\n",
  7 + "(在真实运行时这里会调 bootstrap_prd_site)\n",
  8 + "\n## 第 3 步: 写章节\n",
  9 + "background / personas / scope / feature-tree / user-flows / prototype\n",
7 10 "\n## 完成\n",
8   - "已生成 PRD v1。\n"
  11 + "PRD v1 已生成,可交付给 Architect。\n"
9 12 ],
10   - "result": "mock-ok devloop-pm: PRD v1 scaffolded (no real writes in mock mode)"
  13 + "result": "mock-ok devloop-pm: PRD scaffolded (todo-demo, rev=1)",
  14 + "files": [
  15 + {
  16 + "path": "prd/index.html",
  17 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>PRD · todo-demo</title><link rel=\"stylesheet\" href=\"assets/shell.css\"></head><body data-page=\"index.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"system@2026-05-13T10:00:00.000Z\"><h3>项目首页</h3><p>todo-demo · 一个 TODO 列表 API + 前端</p><table><tr><th>章节</th><th>路径</th></tr><tr><td>背景</td><td>product/background.html</td></tr></table><pre>flow: list -> add -> done</pre><svg width=\"100\" height=\"20\"><line x1=\"0\" y1=\"10\" x2=\"100\" y2=\"10\" stroke=\"black\" marker-end=\"url(#arrow)\"/></svg><div class=\"card\">导航卡片</div><details><summary>更多</summary><p>站点入口</p></details></section><footer data-changelog>rev1 init by mock-pm</footer></article><script src=\"assets/shell.js\"></script></body></html>"
  18 + },
  19 + {
  20 + "path": "prd/reading-guide.html",
  21 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>Reading Guide</title><link rel=\"stylesheet\" href=\"assets/shell.css\"></head><body data-page=\"reading-guide.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"system@2026-05-13T10:00:00.000Z\"><h3>阅读顺序</h3><p>建议按 background → personas → scope → feature-tree → user-flows → prototype 阅读。</p><pre>├── product\n├── feature\n└── flow</pre><table><tr><td>第 1 步</td><td>product/background</td></tr></table><div class=\"card\">tip</div><svg width=\"60\" height=\"20\"><rect width=\"60\" height=\"20\" fill=\"#eef\"/></svg></section></article></body></html>"
  22 + },
  23 + {
  24 + "path": "prd/product/background.html",
  25 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>背景</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"product/background.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"yibo@2026-05-13T10:00:00.000Z\"><h3>背景</h3><p>个人 / 小团队需要轻量 TODO 工具,不愿引入 Notion / Jira。</p><table><tr><th>痛点</th><th>解法</th></tr><tr><td>无快速记录</td><td>极简 API</td></tr></table><pre>需求 → API → 前端</pre><svg width=\"80\" height=\"20\"><circle cx=\"10\" cy=\"10\" r=\"5\"/></svg><div class=\"card\">scope: MVP</div></section></article></body></html>"
  26 + },
  27 + {
  28 + "path": "prd/product/personas.html",
  29 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>用户</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"product/personas.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"yibo@2026-05-13T10:00:00.000Z\"><h3>用户画像</h3><p>独立开发者 / 学生 / 产品经理 — 单人或 ≤3 人小团队。</p><table><tr><th>画像</th><th>场景</th></tr><tr><td>开发者</td><td>记 bug / 任务</td></tr></table><pre>persona-a / persona-b</pre><svg width=\"80\" height=\"20\"><circle cx=\"40\" cy=\"10\" r=\"5\"/></svg><div class=\"card\">primary: dev</div></section></article></body></html>"
  30 + },
  31 + {
  32 + "path": "prd/product/scope.html",
  33 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>范围</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"product/scope.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"yibo@2026-05-13T10:00:00.000Z\"><h3>本期范围</h3><p>POST /todos 新增 · GET /todos 列表 · Vue 简单列表前端。不做用户系统、不做拖拽排序。</p><table><tr><th>In</th><th>Out</th></tr><tr><td>CRUD</td><td>登录</td></tr></table><pre>scope: api + fe</pre><svg width=\"80\" height=\"20\"><rect x=\"5\" y=\"5\" width=\"60\" height=\"10\" fill=\"#cfc\"/></svg><div class=\"card\">MVP</div></section></article></body></html>"
  34 + },
  35 + {
  36 + "path": "prd/feature/feature-tree.html",
  37 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>功能树</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"feature/feature-tree.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"yibo@2026-05-13T10:00:00.000Z\"><h3>功能树</h3><p>todo-be(POST/GET /todos) · todo-fe(Vue 列表) · 可选 todo-db(SQLite schema)。</p><table><tr><th>模块</th><th>说明</th></tr><tr><td>todo-be</td><td>API 服务</td></tr><tr><td>todo-fe</td><td>前端</td></tr></table><pre>├── todo-be\n├── todo-fe\n└── todo-db</pre><svg width=\"80\" height=\"40\"><line x1=\"10\" y1=\"10\" x2=\"60\" y2=\"30\" marker-end=\"url(#a)\"/><polygon points=\"60,30 55,25 55,35\"/></svg><div class=\"card\">3 unit</div></section></article></body></html>"
  38 + },
  39 + {
  40 + "path": "prd/flow/user-flows.html",
  41 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>用户流</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"flow/user-flows.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"yibo@2026-05-13T10:00:00.000Z\"><h3>核心流程</h3><p>打开页面 → 看到列表 → 输入 → 提交 → 刷新看到新条目。</p><table><tr><th>步骤</th><th>动作</th></tr><tr><td>1</td><td>GET /todos</td></tr><tr><td>2</td><td>POST /todos</td></tr></table><pre>user -> fe -> be -> db</pre><svg width=\"120\" height=\"30\"><line x1=\"0\" y1=\"15\" x2=\"110\" y2=\"15\" stroke=\"black\" marker-end=\"url(#arrow)\" stroke-dasharray=\"4 2\"/></svg><div class=\"card\">主流程</div></section></article></body></html>"
  42 + },
  43 + {
  44 + "path": "prd/prototype/proto-list.html",
  45 + "content": "<!doctype html><html><head><meta charset=\"utf-8\"><title>原型 · 列表</title><link rel=\"stylesheet\" href=\"../assets/shell.css\"></head><body data-page=\"prototype/proto-list.html\"><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\" data-origin=\"yibo@2026-05-13T10:00:00.000Z\"><h3>原型 · TODO 列表</h3><p>顶部 input + 按钮,下方列表展示。</p><table><tr><th>组件</th><th>事件</th></tr><tr><td>input</td><td>enter</td></tr></table><pre>+----------+\n| input |\n+----------+\n| item 1 |\n| item 2 |\n+----------+</pre><svg width=\"60\" height=\"40\"><rect x=\"5\" y=\"5\" width=\"50\" height=\"10\" fill=\"#fff\" stroke=\"#999\"/></svg><div class=\"card\">UI 草图</div></section></article></body></html>"
  46 + },
  47 + {
  48 + "path": "prd/assets/shell.css",
  49 + "content": "/* shell.css placeholder (P1 mock) */\nbody { font-family: system-ui; max-width: 960px; margin: 2em auto; }\n.card { padding: 8px; border: 1px solid #ccc; border-radius: 4px; }\n"
  50 + },
  51 + {
  52 + "path": "prd/assets/shell.js",
  53 + "content": "/* shell.js placeholder (P1 mock) */\nconsole.log('[devloop-prd] shell loaded');\n"
  54 + },
  55 + {
  56 + "path": "prd/assets/search-index.json",
  57 + "content": "{\"version\":\"1\",\"pages\":8,\"entries\":[]}"
  58 + },
  59 + {
  60 + "path": "history/prd-rev-001.html",
  61 + "content": "<!doctype html><html><head><title>PRD rev 1 snapshot</title></head><body><article data-doc=\"prd\" data-rev=\"1\"><section data-rev=\"1\"><h3>Snapshot</h3><p>Archive of PRD rev 1, see prd/index.html for live version.</p></section></article></body></html>"
  62 + },
  63 + {
  64 + "path": "agent-state/pm.json",
  65 + "content": "{\"agent\":\"devloop-pm\",\"status\":\"idle\",\"current_step\":8,\"total_steps\":8,\"last_call_id\":\"call-mock-pm\",\"updated_at\":\"2026-05-13T10:00:01.000Z\"}"
  66 + },
  67 + {
  68 + "path": "agent-state/pm-todo.json",
  69 + "content": "{\"agent\":\"devloop-pm\",\"call_id\":\"call-mock-pm\",\"created_at\":\"2026-05-13T10:00:00.000Z\",\"items\":[{\"id\":\"step-001\",\"description\":\"bootstrap_prd_site\",\"status\":\"done\",\"depends_on\":[]},{\"id\":\"step-002\",\"description\":\"write index.html\",\"status\":\"done\",\"depends_on\":[\"step-001\"]},{\"id\":\"step-003\",\"description\":\"write product/*.html\",\"status\":\"done\",\"depends_on\":[\"step-002\"]},{\"id\":\"step-004\",\"description\":\"write feature/* + flow/* + prototype/*\",\"status\":\"done\",\"depends_on\":[\"step-002\"]},{\"id\":\"step-005\",\"description\":\"update_search_index\",\"status\":\"done\",\"depends_on\":[\"step-004\"]},{\"id\":\"step-006\",\"description\":\"validate_prd_site\",\"status\":\"done\",\"depends_on\":[\"step-005\"]},{\"id\":\"step-007\",\"description\":\"archive_doc → history/\",\"status\":\"done\",\"depends_on\":[\"step-006\"]},{\"id\":\"step-008\",\"description\":\"echo_diff\",\"status\":\"done\",\"depends_on\":[\"step-007\"]}],\"current\":null,\"progress_pct\":100}"
  70 + }
  71 + ]
11 72 }
... ...
packages/acp-core/protocol/ClaudeCliProtocol.js
... ... @@ -569,6 +569,21 @@ class ClaudeCliProtocol extends EventEmitter {
569 569 });
570 570 }
571 571  
  572 + // 发 mock/files (若 fixture 含 files[]):
  573 + // LoopController 听到这事件后 把 files 落盘到项目根。
  574 + // 这是 mock 模式下让 Agent 真正"产出文件"的桥梁。
  575 + if (Array.isArray(fixture.files) && fixture.files.length > 0) {
  576 + this.emit('acp_event', {
  577 + type: 'notification',
  578 + method: 'mock/files',
  579 + params: {
  580 + agent: agentName,
  581 + files: fixture.files, // [{ path, content }] (path 相对项目根)
  582 + },
  583 + timestamp: Date.now(),
  584 + });
  585 + }
  586 +
572 587 // 发 session/result(模拟 type=result)
573 588 const resultText = fixture.result || chunks.join('');
574 589 this.emit('acp_event', {
... ... @@ -583,6 +598,7 @@ class ClaudeCliProtocol extends EventEmitter {
583 598 usage: { input: 0, output: 0 },
584 599 model: 'mock',
585 600 mock: true,
  601 + files_produced: Array.isArray(fixture.files) ? fixture.files.length : 0,
586 602 },
587 603 timestamp: Date.now(),
588 604 });
... ...
scripts/phase1-verify.js 0 → 100644
  1 +#!/usr/bin/env node
  2 +/**
  3 + * scripts/phase1-verify.js
  4 + *
  5 + * P1 Docs MVP 验收 (mock 模式端到端):
  6 + * 1. 启动只挂 devloop router 的 express app (随机端口)
  7 + * 2. POST /api/devloop/projects 创建 todo-demo 项目
  8 + * 3. 校验响应体: ok / pid / pm.files_written / architect.files_written / commit sha
  9 + * 4. 校验文件系统:对齐 plan-migration.md §P1 验收的 22 个必要路径
  10 + * 5. 校验 units.json 含 l2_rounds/l2_budget
  11 + * 6. GET /state 返 prd_rev/sdd_rev/units
  12 + * 7. git log 至少 4 个 commit (init meta + PM + Architect + project init)
  13 + *
  14 + * 通过 → exit 0;失败 → exit 1。
  15 + *
  16 + * 用法: node scripts/phase1-verify.js
  17 + */
  18 +
  19 +process.env.LEMONBOSS_CLAUDE_MODE = 'mock';
  20 +
  21 +const fs = require('fs');
  22 +const path = require('path');
  23 +// 复用 server/ 下的 express (top-level scripts/ 没自己 node_modules)
  24 +const serverNodeModules = require('path').resolve(__dirname, '../server/node_modules');
  25 +require('module').globalPaths.push(serverNodeModules);
  26 +const express = (() => {
  27 + try { return require('express'); }
  28 + catch {
  29 + return require(require.resolve('express', { paths: [require('path').resolve(__dirname, '../server')] }));
  30 + }
  31 +})();
  32 +
  33 +const pathResolver = require('../server/services/devloop/path-resolver');
  34 +const gitVault = require('../server/services/devloop/git-vault');
  35 +const devloopRouter = require('../server/routes/devloop');
  36 +
  37 +const results = [];
  38 +function step(name, fn) {
  39 + return (async () => {
  40 + try {
  41 + const r = await fn();
  42 + results.push({ name, ok: true, detail: r?.detail || '' });
  43 + return r;
  44 + } catch (e) {
  45 + results.push({ name, ok: false, reason: e.message });
  46 + throw e;
  47 + }
  48 + })();
  49 +}
  50 +
  51 +async function startApp() {
  52 + const app = express();
  53 + app.use(express.json());
  54 + app.use('/api/devloop', devloopRouter);
  55 + return new Promise((resolve) => {
  56 + const srv = app.listen(0, '127.0.0.1', () => {
  57 + const port = srv.address().port;
  58 + resolve({ srv, base: `http://127.0.0.1:${port}` });
  59 + });
  60 + });
  61 +}
  62 +
  63 +async function main() {
  64 + const { srv, base } = await startApp();
  65 + const cid = 'c-phase1-' + Date.now().toString(36);
  66 + let pid = null;
  67 +
  68 + try {
  69 + const r = await step('POST /api/devloop/projects', async () => {
  70 + const resp = await fetch(`${base}/api/devloop/projects`, {
  71 + method: 'POST',
  72 + headers: { 'Content-Type': 'application/json' },
  73 + body: JSON.stringify({
  74 + company_id: cid,
  75 + name: 'todo-demo',
  76 + requirement: '做一个 TODO 列表:能新增、列表、Vue 前端',
  77 + }),
  78 + });
  79 + if (resp.status !== 200) {
  80 + const t = await resp.text();
  81 + throw new Error(`POST status ${resp.status}: ${t}`);
  82 + }
  83 + const j = await resp.json();
  84 + if (!j.ok || !j.pid?.startsWith('p-')) throw new Error('bad body: ' + JSON.stringify(j));
  85 + if (j.pm.files_written < 10) throw new Error('pm.files_written too few: ' + j.pm.files_written);
  86 + if (j.architect.files_written < 10) throw new Error('architect.files_written too few');
  87 + if (!j.pm.commit) throw new Error('no pm commit');
  88 + if (!j.architect.commit) throw new Error('no architect commit');
  89 + pid = j.pid;
  90 + return { detail: `pid=${pid} pm=${j.pm.files_written} arch=${j.architect.files_written}` };
  91 + });
  92 +
  93 + await step('P1 acceptance file tree complete', async () => {
  94 + const root = pathResolver.resolveProjectRoot(pid);
  95 + const required = [
  96 + 'project.json',
  97 + 'prd/index.html',
  98 + 'prd/reading-guide.html',
  99 + 'prd/product/background.html',
  100 + 'prd/product/personas.html',
  101 + 'prd/product/scope.html',
  102 + 'prd/feature/feature-tree.html',
  103 + 'prd/flow/user-flows.html',
  104 + 'prd/prototype/proto-list.html',
  105 + 'prd/assets/shell.css',
  106 + 'sdd/index.html',
  107 + 'sdd/mvcp/model.html',
  108 + 'sdd/mvcp/view.html',
  109 + 'sdd/mvcp/control.html',
  110 + 'sdd/mvcp/process.html',
  111 + 'units.json',
  112 + 'integration/spec.json',
  113 + 'agent-state/pm.json',
  114 + 'agent-state/pm-todo.json',
  115 + 'agent-state/architect.json',
  116 + 'agent-state/architect-todo.json',
  117 + 'history/prd-rev-001.html',
  118 + 'history/sdd-rev-001.html',
  119 + ];
  120 + const missing = required.filter(f => !fs.existsSync(path.join(root, f)));
  121 + if (missing.length) throw new Error('missing files:\n ' + missing.join('\n '));
  122 + return { detail: `${required.length}/${required.length} files present` };
  123 + });
  124 +
  125 + await step('units.json has 3 units with l2_rounds/l2_budget', () => {
  126 + const u = JSON.parse(fs.readFileSync(pathResolver.resolveUnitsJson(pid), 'utf8'));
  127 + if (!Array.isArray(u.units) || u.units.length !== 3) {
  128 + throw new Error('want 3 units, got: ' + (u.units?.length || 0));
  129 + }
  130 + for (const x of u.units) {
  131 + if (typeof x.l2_rounds !== 'number') throw new Error(`unit ${x.id} missing l2_rounds`);
  132 + if (typeof x.l2_budget !== 'number') throw new Error(`unit ${x.id} missing l2_budget`);
  133 + }
  134 + return { detail: '3 units · l2 fields present · DAG: ' + u.units.map(x => x.id).join(' → ') };
  135 + });
  136 +
  137 + await step('integration/spec.json has cases', () => {
  138 + const sp = JSON.parse(fs.readFileSync(path.join(pathResolver.resolveProjectRoot(pid), 'integration/spec.json'), 'utf8'));
  139 + if (!Array.isArray(sp.cases) || sp.cases.length === 0) {
  140 + throw new Error('no integration cases');
  141 + }
  142 + return { detail: `${sp.cases.length} case(s)` };
  143 + });
  144 +
  145 + await step('GET /state', async () => {
  146 + const resp = await fetch(`${base}/api/devloop/projects/${pid}/state`);
  147 + if (resp.status !== 200) throw new Error('state status: ' + resp.status);
  148 + const s = await resp.json();
  149 + if (!s.prd_site) throw new Error('prd_site=false');
  150 + if (!s.sdd_site) throw new Error('sdd_site=false');
  151 + if (s.units?.length !== 3) throw new Error('state.units length: ' + s.units?.length);
  152 + return { detail: `prd_rev=${s.prd_rev} sdd_rev=${s.sdd_rev} units=${s.units.length}` };
  153 + });
  154 +
  155 + await step('git log ≥4 commits', async () => {
  156 + const log = await gitVault.log(pid, { limit: 20 });
  157 + const commits = Array.isArray(log) ? log : (log.commits || []);
  158 + if (commits.length < 4) {
  159 + throw new Error('want ≥4 commits, got ' + commits.length);
  160 + }
  161 + return { detail: `${commits.length} commits` };
  162 + });
  163 +
  164 + await step('timeline.ndjson has agent.call + docs.complete', () => {
  165 + const tl = pathResolver.resolveTimelineLog(pid);
  166 + const kinds = fs.readFileSync(tl, 'utf8').trim().split('\n')
  167 + .map(l => { try { return JSON.parse(l).kind; } catch { return ''; }});
  168 + if (!kinds.includes('agent.call')) throw new Error('no agent.call in timeline');
  169 + if (!kinds.includes('docs.complete')) throw new Error('no docs.complete in timeline');
  170 + return { detail: kinds.length + ' timeline events' };
  171 + });
  172 +
  173 + } finally {
  174 + srv.close();
  175 + // cleanup sandbox project
  176 + try {
  177 + fs.rmSync(path.join(pathResolver.DATA_DIR, 'companies', cid), { recursive: true, force: true });
  178 + } catch { /* ignore */ }
  179 + }
  180 +
  181 + let pass = 0, fail = 0;
  182 + console.log('\n┌─ DevLoop Phase 1 — Docs MVP Acceptance ───────────');
  183 + for (const r of results) {
  184 + const tag = r.ok ? '✓' : '✗';
  185 + console.log(`│ ${tag} ${r.name.padEnd(50)} ${r.ok ? r.detail : '— ' + r.reason}`);
  186 + r.ok ? pass++ : fail++;
  187 + }
  188 + console.log(`└─ ${pass}/${pass + fail} steps passed${fail ? ' · ' + fail + ' failed' : ''}\n`);
  189 + process.exit(fail ? 1 : 0);
  190 +}
  191 +
  192 +main().catch(e => {
  193 + console.error('\n[phase1-verify] fatal:', e);
  194 + for (const r of results) {
  195 + console.log(' ', r.ok ? '✓' : '✗', r.name, r.ok ? r.detail : '— ' + r.reason);
  196 + }
  197 + process.exit(1);
  198 +});
... ...
server/agent-server.js
... ... @@ -66,6 +66,7 @@ app.use(&#39;/api/agent&#39;, agentChatRoute);
66 66 app.use('/api/company', require('./routes/company'));
67 67 app.use('/api/goals', require('./routes/goals'));
68 68 app.use('/api/tasks', require('./routes/tasks'));
  69 +app.use('/api/devloop', require('./routes/devloop'));
69 70  
70 71 // Health
71 72 app.get('/api/health', (req, res) => res.json({ status: 'ok', service: 'agent-chat' }));
... ...
server/index.js
... ... @@ -93,6 +93,7 @@ app.use(&#39;/api/agent&#39;, require(&#39;./routes/agent-chat&#39;));
93 93 app.use('/api/goals', require('./routes/goals'));
94 94 app.use('/api/company', require('./routes/company'));
95 95 app.use('/api/tasks', require('./routes/tasks'));
  96 +app.use('/api/devloop', require('./routes/devloop'));
96 97  
97 98 // ─── 系统端点 ───
98 99 app.get('/api/health', (req, res) => res.json({
... ...
server/routes/devloop.js 0 → 100644
  1 +/**
  2 + * DevLoop · REST Routes (P1)
  3 + *
  4 + * POST /api/devloop/projects
  5 + * body: { company_id, name?, requirement, mode?, target_path?, mock? }
  6 + * → 创建项目 + 跑 PM / Architect 两个 Agent (mock 模式产出 PRD/SDD)
  7 + * → 返 { pid, root_path, pm: {...}, architect: {...} }
  8 + *
  9 + * GET /api/devloop/projects/:pid/state
  10 + * → 返 { pid, project, units, prd_rev, sdd_rev, prd_site, sdd_site, timeline_tail }
  11 + *
  12 + * GET /api/devloop/projects (额外:列项目)
  13 + * → 返 { projects: [...] }
  14 + *
  15 + * 规格: docs/prd/newfunction/_spec/plan-migration.md · P1 验收
  16 + */
  17 +
  18 +const express = require('express');
  19 +const router = express.Router();
  20 +
  21 +const loopController = require('../src/core/devloop/loop-controller');
  22 +const pathResolver = require('../services/devloop/path-resolver');
  23 +
  24 +const h = (fn) => async (req, res) => {
  25 + try { await fn(req, res); }
  26 + catch (e) {
  27 + console.error(`[DevLoop] ${req.method} ${req.path}:`, e.message);
  28 + res.status(e.statusCode || 500).json({ error: e.message });
  29 + }
  30 +};
  31 +
  32 +// POST /api/devloop/projects
  33 +router.post('/projects', h(async (req, res) => {
  34 + const { company_id, requirement, mode, target_path, mock, name } = req.body || {};
  35 + if (!company_id) {
  36 + return res.status(400).json({ error: 'missing field: company_id' });
  37 + }
  38 + if (!requirement || typeof requirement !== 'string') {
  39 + return res.status(400).json({ error: 'missing field: requirement' });
  40 + }
  41 +
  42 + // 1. 创建项目 (sandbox 默认)
  43 + const proj = await loopController.createProject({
  44 + company_id,
  45 + mode: mode || 'sandbox',
  46 + target_path,
  47 + idea: name ? `${name}: ${requirement}` : requirement,
  48 + });
  49 +
  50 + // 2. PM → Architect (mock 模式)
  51 + const phase = await loopController.runDocsPhase(proj.pid, requirement, {
  52 + mock: mock !== false,
  53 + });
  54 +
  55 + res.json({
  56 + ok: true,
  57 + pid: proj.pid,
  58 + root_path: proj.root_path,
  59 + mode: proj.mode,
  60 + pm: {
  61 + files_written: phase.pm.files_written.length,
  62 + commit: phase.pm.commit?.sha || null,
  63 + mock: phase.pm.mock,
  64 + },
  65 + architect: {
  66 + files_written: phase.architect.files_written.length,
  67 + commit: phase.architect.commit?.sha || null,
  68 + mock: phase.architect.mock,
  69 + },
  70 + });
  71 +}));
  72 +
  73 +// GET /api/devloop/projects
  74 +router.get('/projects', h(async (_req, res) => {
  75 + const projects = pathResolver.listProjects();
  76 + res.json({ projects });
  77 +}));
  78 +
  79 +// GET /api/devloop/projects/:pid/state
  80 +router.get('/projects/:pid/state', h(async (req, res) => {
  81 + try {
  82 + const state = loopController.getProjectState(req.params.pid);
  83 + res.json(state);
  84 + } catch (e) {
  85 + if (/Unknown project/.test(e.message)) {
  86 + return res.status(404).json({ error: 'unknown project: ' + req.params.pid });
  87 + }
  88 + throw e;
  89 + }
  90 +}));
  91 +
  92 +module.exports = router;
... ...
server/src/core/devloop/loop-controller.js
1 1 /**
2   - * DevLoop · LoopController (P0 最小骨架)
  2 + * DevLoop · LoopController
3 3 *
4   - * 在 P0 阶段只暴露两个对外接口:
5   - * - createProject({ company_id, mode, target_path }) — 调 path-resolver + gitVault.init
6   - * - commitAfterAgent(pid, agentName, summary) — 每次 Agent 完成后 auto-commit
  4 + * P0 已提供:
  5 + * - createProject({ company_id, mode, target_path, idea }) — 项目分配 + git init
  6 + * - commitAfterAgent(pid, agentName, summary) — Agent 收尾自动 commit
7 7 *
8   - * 完整的 dispatch / unit fsm / retry 逻辑留待 P1 实现。
  8 + * P1 新增 (Docs MVP):
  9 + * - runDocsPhase(pid, requirement, opts) — 串行跑 PM → Architect (mock 模式),
  10 + * 把 fixture.files 落盘到项目根,每个 Agent 收尾自动 commit
  11 + * - callAgent(pid, agentName, prompt, opts) — 单次 Agent 调用 (P1 仅支持 mock 模式)
9 12 *
10 13 * 规格:
11 14 * - docs/prd/newfunction/_spec/sdd-process.md · P-10 GitCommit
12 15 * - docs/prd/newfunction/_spec/arch-git-versioning.md
13 16 * - docs/prd/newfunction/_spec/arch-project-root.md
  17 + * - docs/prd/newfunction/_spec/plan-migration.md · P1 Docs MVP
14 18 */
15 19  
16 20 const fs = require('fs');
... ... @@ -19,6 +23,9 @@ const path = require(&#39;path&#39;);
19 23 const pathResolver = require('../../../services/devloop/path-resolver');
20 24 const gitVault = require('../../../services/devloop/git-vault');
21 25 const timelineLogger = require('../../../services/devloop/timeline-logger');
  26 +const { ClaudeCliProtocol } = require('../../../../packages/acp-core/protocol/ClaudeCliProtocol');
  27 +
  28 +const TEMPLATES_DIR = path.resolve(__dirname, '../../../../system/templates');
22 29  
23 30 /**
24 31 * 新建项目:
... ... @@ -119,7 +126,201 @@ async function commitAfterAgent(pid, agentName, summary = &#39;&#39;) {
119 126 return commit;
120 127 }
121 128  
  129 +/**
  130 + * 单次 Agent 调用 (P1 mock 实现):
  131 + * 1. 读 system/templates/{agentName}/prompt.md (系统提示)
  132 + * 2. 用 ClaudeCliProtocol(mock=true) 跑一遍
  133 + * 3. 收集 chunks / files / result
  134 + * 4. 把 fixture.files 落盘到项目根
  135 + * 5. 触发 commitAfterAgent
  136 + *
  137 + * @param {string} pid
  138 + * @param {string} agentName e.g. "devloop-pm"
  139 + * @param {string} userPrompt 用户/上一步追加的提示
  140 + * @param {object} opts
  141 + * - onChunk?: (text) => void 流式回调
  142 + * - mock?: boolean 默认走 LEMONBOSS_CLAUDE_MODE=mock
  143 + * - skipCommit?: boolean 默认 false
  144 + * @returns { ok, agent, files_written, commit, result_text }
  145 + */
  146 +async function callAgent(pid, agentName, userPrompt, opts = {}) {
  147 + const projectRoot = pathResolver.resolveProjectRoot(pid);
  148 +
  149 + // 1. 系统提示 (可选 — 没文件就空串)
  150 + const promptPath = path.join(TEMPLATES_DIR, agentName, 'prompt.md');
  151 + const systemPrompt = fs.existsSync(promptPath)
  152 + ? fs.readFileSync(promptPath, 'utf8')
  153 + : '';
  154 + const fullPrompt = systemPrompt
  155 + ? `${systemPrompt}\n\n## User Task\n${userPrompt}`
  156 + : userPrompt;
  157 +
  158 + // 2. 启动 protocol
  159 + const protocol = new ClaudeCliProtocol(
  160 + { name: agentName },
  161 + { mock: opts.mock !== false }, // 默认 mock=true (P1 阶段)
  162 + );
  163 +
  164 + let resultParams = null;
  165 + const filesFromMock = [];
  166 + protocol.on('session_update', (u) => {
  167 + if (u.update?.sessionUpdate === 'agent_message_chunk' && opts.onChunk) {
  168 + opts.onChunk(u.update.content.text);
  169 + }
  170 + });
  171 + protocol.on('acp_event', (ev) => {
  172 + if (ev.method === 'session/result') resultParams = ev.params;
  173 + else if (ev.method === 'mock/files' && Array.isArray(ev.params?.files)) {
  174 + filesFromMock.push(...ev.params.files);
  175 + }
  176 + });
  177 +
  178 + try {
  179 + await protocol.connect(null, projectRoot);
  180 + await protocol.sendPrompt(fullPrompt);
  181 + } finally {
  182 + protocol.disconnect();
  183 + }
  184 +
  185 + // 3. 落盘 fixture.files (path 相对 projectRoot)
  186 + const filesWritten = [];
  187 + for (const f of filesFromMock) {
  188 + if (!f?.path || typeof f.content !== 'string') continue;
  189 + if (path.isAbsolute(f.path) || f.path.includes('..')) {
  190 + throw new Error(`unsafe mock file path: ${f.path}`);
  191 + }
  192 + const abs = path.join(projectRoot, f.path);
  193 + fs.mkdirSync(path.dirname(abs), { recursive: true });
  194 + fs.writeFileSync(abs, f.content);
  195 + filesWritten.push(f.path);
  196 + }
  197 +
  198 + // 4. timeline + commit
  199 + try {
  200 + timelineLogger.append(pid, {
  201 + source: agentName,
  202 + kind: 'agent.call',
  203 + ref: resultParams?.session_id || 'mock',
  204 + summary: (resultParams?.result || '').slice(0, 200) || `${agentName} ran (mock)`,
  205 + payload: { files_written: filesWritten.length, mock: !!resultParams?.mock },
  206 + });
  207 + } catch { /* swallow */ }
  208 +
  209 + let commit = null;
  210 + if (!opts.skipCommit) {
  211 + const summary = (resultParams?.result || '').slice(0, 80) || `${agentName} produced ${filesWritten.length} files`;
  212 + commit = await commitAfterAgent(pid, agentName, summary);
  213 + }
  214 +
  215 + return {
  216 + ok: true,
  217 + agent: agentName,
  218 + files_written: filesWritten,
  219 + commit,
  220 + result_text: resultParams?.result || '',
  221 + mock: !!resultParams?.mock,
  222 + };
  223 +}
  224 +
  225 +/**
  226 + * Docs phase (P1): PM → Architect 串行跑。
  227 + *
  228 + * @param {string} pid
  229 + * @param {string} requirement 用户原始需求一段话
  230 + * @param {object} opts
  231 + * - onChunk?: (agent, text) => void
  232 + * @returns { ok, pm, architect }
  233 + */
  234 +async function runDocsPhase(pid, requirement, opts = {}) {
  235 + if (!requirement || typeof requirement !== 'string') {
  236 + throw new Error('requirement (string) required');
  237 + }
  238 +
  239 + const onChunk = opts.onChunk
  240 + ? (agent) => (text) => opts.onChunk(agent, text)
  241 + : null;
  242 +
  243 + const pm = await callAgent(pid, 'devloop-pm',
  244 + `Requirement:\n${requirement}\n\nmode: init`,
  245 + { onChunk: onChunk ? onChunk('devloop-pm') : undefined });
  246 +
  247 + const architect = await callAgent(pid, 'devloop-architect',
  248 + `Read prd/ from project root and produce SDD + units.json + integration/spec.json.\nRequirement context:\n${requirement}`,
  249 + { onChunk: onChunk ? onChunk('devloop-architect') : undefined });
  250 +
  251 + // timeline 总结
  252 + try {
  253 + timelineLogger.append(pid, {
  254 + source: 'system',
  255 + kind: 'docs.complete',
  256 + ref: pid,
  257 + summary: `Docs phase complete: PM (${pm.files_written.length} files) + Architect (${architect.files_written.length} files)`,
  258 + payload: {
  259 + pm_files: pm.files_written.length,
  260 + architect_files: architect.files_written.length,
  261 + },
  262 + });
  263 + } catch { /* swallow */ }
  264 +
  265 + return { ok: true, pm, architect };
  266 +}
  267 +
  268 +/**
  269 + * 读项目当前状态 (P1 用,routes/devloop.js GET /state 后端):
  270 + * - project.json
  271 + * - units.json (if any)
  272 + * - PRD/SDD revs (扫 article[data-rev] 最大值)
  273 + * - 最近一次 commit
  274 + * - timeline 最近 5 条
  275 + * - bugs 计数
  276 + */
  277 +function getProjectState(pid) {
  278 + const root = pathResolver.resolveProjectRoot(pid);
  279 + const out = { pid, root_path: root };
  280 +
  281 + const projectJson = pathResolver.resolveProjectJson(pid);
  282 + if (fs.existsSync(projectJson)) {
  283 + try { out.project = JSON.parse(fs.readFileSync(projectJson, 'utf8')); } catch {}
  284 + }
  285 +
  286 + const unitsJson = pathResolver.resolveUnitsJson(pid);
  287 + if (fs.existsSync(unitsJson)) {
  288 + try {
  289 + const u = JSON.parse(fs.readFileSync(unitsJson, 'utf8'));
  290 + out.units = u.units || [];
  291 + out.units_rev = u.rev || 0;
  292 + } catch {}
  293 + }
  294 +
  295 + // PRD/SDD rev = 站点根 index.html 的 article[data-rev]
  296 + for (const kind of ['prd', 'sdd']) {
  297 + const idx = path.join(root, kind, 'index.html');
  298 + if (fs.existsSync(idx)) {
  299 + const html = fs.readFileSync(idx, 'utf8');
  300 + const m = html.match(/<article[^>]*data-doc="(prd|sdd)"[^>]*data-rev="(\d+)"/);
  301 + out[`${kind}_rev`] = m ? parseInt(m[2], 10) : 1;
  302 + out[`${kind}_site`] = true;
  303 + } else {
  304 + out[`${kind}_site`] = false;
  305 + }
  306 + }
  307 +
  308 + // timeline tail
  309 + const tl = pathResolver.resolveTimelineLog(pid);
  310 + if (fs.existsSync(tl)) {
  311 + const lines = fs.readFileSync(tl, 'utf8').trim().split('\n').filter(Boolean);
  312 + out.timeline_tail = lines.slice(-5).map(l => {
  313 + try { return JSON.parse(l); } catch { return null; }
  314 + }).filter(Boolean);
  315 + }
  316 +
  317 + return out;
  318 +}
  319 +
122 320 module.exports = {
123 321 createProject,
124 322 commitAfterAgent,
  323 + callAgent,
  324 + runDocsPhase,
  325 + getProjectState,
125 326 };
... ...
server/tests/devloop/loop-controller.test.js 0 → 100644
  1 +/**
  2 + * loop-controller (P1) 单测
  3 + * - callAgent (mock 模式) 能从 fixture 产出文件 + git commit
  4 + * - runDocsPhase 串行跑 PM + Architect,产物齐全
  5 + * - getProjectState 返回 prd_rev/sdd_rev/units
  6 + */
  7 +
  8 +process.env.LEMONBOSS_CLAUDE_MODE = 'mock';
  9 +
  10 +const fs = require('fs');
  11 +const path = require('path');
  12 +const os = require('os');
  13 +
  14 +const TEST_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'devloop-lc-'));
  15 +process.env.HOME = TEST_HOME;
  16 +
  17 +const pathResolver = require('../../services/devloop/path-resolver');
  18 +const lc = require('../../src/core/devloop/loop-controller');
  19 +
  20 +describe('loop-controller (P1)', () => {
  21 + let pid, cid;
  22 + const created = [];
  23 +
  24 + afterAll(() => {
  25 + // 清理 sandbox 项目目录
  26 + for (const c of created) {
  27 + try {
  28 + fs.rmSync(path.join(pathResolver.DATA_DIR, 'companies', c), { recursive: true, force: true });
  29 + } catch { /* ignore */ }
  30 + }
  31 + });
  32 +
  33 + async function fresh() {
  34 + pathResolver._resetForTesting();
  35 + cid = 'c-test-' + Math.random().toString(36).slice(2, 7);
  36 + created.push(cid);
  37 + const proj = await lc.createProject({
  38 + company_id: cid, mode: 'sandbox', idea: 'unit-test',
  39 + });
  40 + pid = proj.pid;
  41 + return proj;
  42 + }
  43 +
  44 + describe('callAgent (mock devloop-pm)', () => {
  45 + beforeAll(async () => { await fresh(); });
  46 +
  47 + it('produces files from fixture + commits', async () => {
  48 + const r = await lc.callAgent(pid, 'devloop-pm', 'requirement: hello');
  49 + expect(r.ok).toBe(true);
  50 + expect(r.mock).toBe(true);
  51 + expect(r.files_written.length).toBeGreaterThanOrEqual(10);
  52 + expect(r.commit).not.toBeNull();
  53 + expect(r.commit.sha).toBeTruthy();
  54 + const root = pathResolver.resolveProjectRoot(pid);
  55 + expect(fs.existsSync(path.join(root, 'prd', 'index.html'))).toBe(true);
  56 + expect(fs.existsSync(path.join(root, 'agent-state', 'pm.json'))).toBe(true);
  57 + });
  58 +
  59 + it('subsequent call still commits (timeline.ndjson always appended)', async () => {
  60 + const r = await lc.callAgent(pid, 'devloop-pm', 'second time same fixture');
  61 + // mock 产物相同但 timeline.ndjson 会追加一行 → 总有 diff,有 commit
  62 + expect(r.commit).not.toBeNull();
  63 + expect(r.commit.sha).toBeTruthy();
  64 + });
  65 + });
  66 +
  67 + describe('runDocsPhase (PM → Architect)', () => {
  68 + beforeAll(async () => { await fresh(); });
  69 +
  70 + let phase;
  71 + it('completes both agents', async () => {
  72 + phase = await lc.runDocsPhase(pid, '做一个 TODO 列表');
  73 + expect(phase.ok).toBe(true);
  74 + expect(phase.pm.commit?.sha).toBeTruthy();
  75 + expect(phase.architect.commit?.sha).toBeTruthy();
  76 + });
  77 +
  78 + it('produces full P1 acceptance file tree', () => {
  79 + const root = pathResolver.resolveProjectRoot(pid);
  80 + const required = [
  81 + 'project.json',
  82 + 'prd/index.html',
  83 + 'prd/reading-guide.html',
  84 + 'prd/product/background.html',
  85 + 'prd/product/personas.html',
  86 + 'prd/product/scope.html',
  87 + 'prd/feature/feature-tree.html',
  88 + 'prd/flow/user-flows.html',
  89 + 'sdd/index.html',
  90 + 'sdd/mvcp/model.html',
  91 + 'sdd/mvcp/view.html',
  92 + 'sdd/mvcp/control.html',
  93 + 'sdd/mvcp/process.html',
  94 + 'units.json',
  95 + 'integration/spec.json',
  96 + 'agent-state/pm.json',
  97 + 'agent-state/pm-todo.json',
  98 + 'agent-state/architect.json',
  99 + 'agent-state/architect-todo.json',
  100 + 'history/prd-rev-001.html',
  101 + 'history/sdd-rev-001.html',
  102 + ];
  103 + const missing = required.filter(f => !fs.existsSync(path.join(root, f)));
  104 + expect(missing).toEqual([]);
  105 + });
  106 +
  107 + it('units.json has 3 units with l2_rounds/l2_budget', () => {
  108 + const u = JSON.parse(fs.readFileSync(pathResolver.resolveUnitsJson(pid), 'utf8'));
  109 + expect(u.units).toHaveLength(3);
  110 + for (const x of u.units) {
  111 + expect(typeof x.l2_rounds).toBe('number');
  112 + expect(typeof x.l2_budget).toBe('number');
  113 + }
  114 + });
  115 +
  116 + it('getProjectState reflects produced docs', () => {
  117 + const s = lc.getProjectState(pid);
  118 + expect(s.prd_site).toBe(true);
  119 + expect(s.sdd_site).toBe(true);
  120 + expect(s.prd_rev).toBe(1);
  121 + expect(s.sdd_rev).toBe(1);
  122 + expect(s.units).toHaveLength(3);
  123 + expect(Array.isArray(s.timeline_tail)).toBe(true);
  124 + expect(s.timeline_tail.length).toBeGreaterThan(0);
  125 + });
  126 + });
  127 +
  128 + describe('runDocsPhase rejects bad input', () => {
  129 + beforeAll(async () => { await fresh(); });
  130 +
  131 + it('throws when requirement missing', async () => {
  132 + await expect(lc.runDocsPhase(pid, '')).rejects.toThrow(/requirement/);
  133 + });
  134 + });
  135 +});
... ...
server/tests/devloop/routes.test.js 0 → 100644
  1 +/**
  2 + * routes/devloop.js 集成测试
  3 + *
  4 + * 不启动完整 server,只挂 devloop router 到独立 express app + fetch。
  5 + */
  6 +
  7 +process.env.LEMONBOSS_CLAUDE_MODE = 'mock';
  8 +
  9 +const fs = require('fs');
  10 +const path = require('path');
  11 +const os = require('os');
  12 +const express = require('express');
  13 +
  14 +const TEST_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'devloop-rt-'));
  15 +process.env.HOME = TEST_HOME;
  16 +
  17 +const pathResolver = require('../../services/devloop/path-resolver');
  18 +const devloopRouter = require('../../routes/devloop');
  19 +
  20 +function startApp() {
  21 + const app = express();
  22 + app.use(express.json());
  23 + app.use('/api/devloop', devloopRouter);
  24 + return new Promise((resolve) => {
  25 + const srv = app.listen(0, '127.0.0.1', () => {
  26 + const port = srv.address().port;
  27 + resolve({ srv, base: `http://127.0.0.1:${port}` });
  28 + });
  29 + });
  30 +}
  31 +
  32 +describe('routes/devloop', () => {
  33 + let app, base;
  34 + const created = [];
  35 +
  36 + beforeAll(async () => {
  37 + pathResolver._resetForTesting();
  38 + ({ srv: app, base } = await startApp());
  39 + });
  40 +
  41 + afterAll(() => {
  42 + app.close();
  43 + for (const c of created) {
  44 + try {
  45 + fs.rmSync(path.join(pathResolver.DATA_DIR, 'companies', c), { recursive: true, force: true });
  46 + } catch { /* ignore */ }
  47 + }
  48 + });
  49 +
  50 + it('POST /api/devloop/projects requires company_id', async () => {
  51 + const r = await fetch(`${base}/api/devloop/projects`, {
  52 + method: 'POST',
  53 + headers: { 'Content-Type': 'application/json' },
  54 + body: JSON.stringify({ requirement: 'x' }),
  55 + });
  56 + expect(r.status).toBe(400);
  57 + const j = await r.json();
  58 + expect(j.error).toMatch(/company_id/);
  59 + });
  60 +
  61 + it('POST /api/devloop/projects requires requirement', async () => {
  62 + const r = await fetch(`${base}/api/devloop/projects`, {
  63 + method: 'POST',
  64 + headers: { 'Content-Type': 'application/json' },
  65 + body: JSON.stringify({ company_id: 'c-x' }),
  66 + });
  67 + expect(r.status).toBe(400);
  68 + const j = await r.json();
  69 + expect(j.error).toMatch(/requirement/);
  70 + });
  71 +
  72 + it('POST /api/devloop/projects → creates project and runs PM + Architect', async () => {
  73 + const cid = 'c-route-test-' + Math.random().toString(36).slice(2, 7);
  74 + created.push(cid);
  75 + const r = await fetch(`${base}/api/devloop/projects`, {
  76 + method: 'POST',
  77 + headers: { 'Content-Type': 'application/json' },
  78 + body: JSON.stringify({
  79 + company_id: cid,
  80 + name: 'todo-demo',
  81 + requirement: '做一个 TODO 列表:能新增、列表、Vue 前端',
  82 + }),
  83 + });
  84 + expect(r.status).toBe(200);
  85 + const j = await r.json();
  86 + expect(j.ok).toBe(true);
  87 + expect(j.pid).toMatch(/^p-/);
  88 + expect(j.pm.files_written).toBeGreaterThanOrEqual(10);
  89 + expect(j.architect.files_written).toBeGreaterThanOrEqual(10);
  90 + expect(j.pm.commit).toBeTruthy();
  91 + expect(j.architect.commit).toBeTruthy();
  92 +
  93 + // 验证文件确实落盘
  94 + const root = pathResolver.resolveProjectRoot(j.pid);
  95 + expect(fs.existsSync(path.join(root, 'prd', 'index.html'))).toBe(true);
  96 + expect(fs.existsSync(path.join(root, 'sdd', 'mvcp', 'model.html'))).toBe(true);
  97 + expect(fs.existsSync(path.join(root, 'units.json'))).toBe(true);
  98 +
  99 + // GET /state
  100 + const sR = await fetch(`${base}/api/devloop/projects/${j.pid}/state`);
  101 + expect(sR.status).toBe(200);
  102 + const s = await sR.json();
  103 + expect(s.pid).toBe(j.pid);
  104 + expect(s.prd_site).toBe(true);
  105 + expect(s.sdd_site).toBe(true);
  106 + expect(s.units).toHaveLength(3);
  107 + });
  108 +
  109 + it('GET /api/devloop/projects/:pid/state on unknown pid returns 404', async () => {
  110 + const r = await fetch(`${base}/api/devloop/projects/p-doesnotexist/state`);
  111 + expect(r.status).toBe(404);
  112 + const j = await r.json();
  113 + expect(j.error).toMatch(/unknown/);
  114 + });
  115 +
  116 + it('GET /api/devloop/projects lists projects', async () => {
  117 + const r = await fetch(`${base}/api/devloop/projects`);
  118 + expect(r.status).toBe(200);
  119 + const j = await r.json();
  120 + expect(Array.isArray(j.projects)).toBe(true);
  121 + });
  122 +});
... ...