/** * goal / task 两级模型的路由层(27-P3C §六,批 1)。 * * 这里只验**不需要真起 run** 的那一半:列表 / 详情 / 改 / 归档,外加两条闸门的 HTTP 翻译 * (描述冻结 → 409、depends_on 非法 → 400 且库里不留脏数据)。起 run 的那条路要真公司 + * 真 org graph + Claude CLI,属于 §八 验收清单里在浏览器上点的部分,不在单测射程内。 * * 进度那条断言(2/3)是本文件的重点:验收 10 点名要挡的就是「列表页逐行查进度」的 N+1, * 路由这边走的是 taskProgress 的一条 GROUP BY —— 结果对不对必须有人盯着, * 否则改成逐行查也一样是绿的。 */ const fs = require('fs'); const os = require('os'); const path = require('path'); const TEST_DB_PATH = '/tmp/test-company-goal-task-routes.sqlite'; const DB_FILES = [TEST_DB_PATH, `${TEST_DB_PATH}-shm`, `${TEST_DB_PATH}-wal`]; // 这几个模块在加载时快照 GRAPH_DB_PATH / GRAPH_RUNS_DIR,必须先设 env 再 require(见 §八 验收 12b) const MODULES = ['../../services/graph-db', '../../services/work-graph-db', '../../routes/company']; const CID = 'route-test-co'; let wdb; let server; let base; let origin; let origCompanyGet; /** 一次请求 → [status, json](没有 supertest,express 起在随机端口上用 fetch 打) */ async function call(method, url, body) { const r = await fetch(base + url, { method, headers: { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), }); return [r.status, await r.json()]; } /** 同上,但公司 id 自己指定(验「打错公司 id → 404」那条要打到别的公司上) */ async function callCompany(cid, method, url) { const r = await fetch(`${origin}/api/company/${cid}${url}`, { method }); return [r.status, await r.json()]; } describe('company goal/task routes(27-P3C §六)', () => { let goal; let t1; let t2; beforeAll(async () => { for (const f of DB_FILES) { try { fs.unlinkSync(f); } catch { /* 本来就没有 */ } } process.env.GRAPH_DB_PATH = TEST_DB_PATH; // 产物根挪到临时目录:不设的话任何走到默认路径的写入都会往仓库 data/companies/ 里堆 process.env.GRAPH_RUNS_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'p3c-routes-')); for (const m of MODULES) delete require.cache[require.resolve(m)]; wdb = require('../../services/work-graph-db'); // 公司实体:`company-service` 的 DATA_DIR 是硬编码的仓库 data/companies/,不认任何 env, // 真建一家公司就是往用户仓库里落目录。这里只让 CID 这一家存在 —— 别的 id 一律 null, // 「打错公司 id → 404」(缺陷 F9)那条断言要靠它。 const { CompanyService } = require('../../services/company-service'); origCompanyGet = CompanyService.prototype.get; CompanyService.prototype.get = (companyId) => (companyId === CID ? { id: CID, name: CID, status: 'running' } : null); const express = require('express'); const app = express(); app.use(express.json()); app.use('/api/company', require('../../routes/company')); await new Promise((resolve) => { server = app.listen(0, resolve); }); origin = `http://127.0.0.1:${server.address().port}`; base = `${origin}/api/company/${CID}`; goal = wdb.createGoal({ companyId: CID, title: '做个官网', description: '做个官网,含首页和后台' }); t1 = wdb.createTask({ goalId: goal.id, title: '首页', description: '写首页' }); t2 = wdb.createTask({ goalId: goal.id, title: '后台', description: '写后台', dependsOn: [t1.id] }); // 给 t1 挂一条 run + 3 个节点行(2 success / 1 pending),用来验进度口径 const db = wdb.getDb(); const now = new Date().toISOString(); db.prepare(`INSERT INTO graph_runs (id, graph_kind, graph_id, company_id, root_run_id, run_status, created_at, updated_at) VALUES ('run_rt','org',?,?, 'run_rt','running',?,?)`).run(CID, CID, now, now); ['success', 'success', 'pending'].forEach((status, i) => { db.prepare(`INSERT INTO graph_run_nodes (id, run_id, def_node_id, status, created_at, updated_at) VALUES (?, 'run_rt', ?, ?, ?, ?)`).run(`rn_rt${i}`, `d${i}`, status, now, now); }); wdb.updateTask(t1.id, { currentRunId: 'run_rt', status: 'running' }); }); afterAll(() => { if (server) server.close(); if (origCompanyGet) require('../../services/company-service').CompanyService.prototype.get = origCompanyGet; for (const f of DB_FILES) { try { fs.unlinkSync(f); } catch { /* 已经删了 */ } } try { fs.rmSync(process.env.GRAPH_RUNS_DIR, { recursive: true, force: true }); } catch { /* ignore */ } delete process.env.GRAPH_DB_PATH; delete process.env.GRAPH_RUNS_DIR; for (const m of MODULES) delete require.cache[require.resolve(m)]; }); it('GET /goals?withTasks=1 一次带出两级树,进度走一条 GROUP BY', async () => { const [status, body] = await call('GET', '/goals?withTasks=1'); expect(status).toBe(200); expect(body.goals).toHaveLength(1); const tasks = body.goals[0].tasks; expect(tasks.map((t) => t.taskId)).toEqual([t1.id, t2.id]); // 树的顺序是 seq,不是队列位次 expect(tasks[0].progress).toEqual({ done: 2, total: 3 }); // 没有 run 的 task 是 null 而不是 0/0:前端据此画「未开始」,画成 0/0 会像是「跑了但没进展」 expect(tasks[1].progress).toBeNull(); expect(tasks[1].dependsOn).toEqual([t1.id]); }); it('GET /tasks 支持按 status 过滤,且默认不含已归档', async () => { const [status, body] = await call('GET', '/tasks?status=running'); expect(status).toBe(200); expect(body.tasks.map((t) => t.taskId)).toEqual([t1.id]); }); it('GET /goals/:goalId 带出每条 task 的当前 run 摘要', async () => { const [status, body] = await call('GET', `/goals/${goal.id}`); expect(status).toBe(200); expect(body.tasks[0].run).toMatchObject({ runId: 'run_rt', runStatus: 'running' }); expect(body.tasks[1].run).toBeNull(); }); it('不属于本公司 / 不存在的 goal 一律 404', async () => { const [status] = await call('GET', '/goals/G-nope'); expect(status).toBe(404); }); it('描述冻结:未下达可改,dispatched_at 一非空就 409 + hint(§四.4)', async () => { const [ok, before] = await call('PATCH', `/goals/${goal.id}`, { description: '换个需求' }); expect(ok).toBe(200); expect(before.description).toBe('换个需求'); wdb.updateGoal(goal.id, { dispatchedAt: new Date().toISOString() }); const [conflict, body] = await call('PATCH', `/goals/${goal.id}`, { description: '再换一次' }); expect(conflict).toBe(409); expect(body.frozenFields).toEqual(['description']); expect(body.hint).toBeTruthy(); // 「取消后新建」这句必须给出来,否则用户只知道被拒不知道该怎么办 // title 是列表上的标签、不进 agent 上下文,冻结之后仍可改 const [stillOk] = await call('PATCH', `/goals/${goal.id}`, { title: '改个名' }); expect(stillOk).toBe(200); }); it('depends_on 非法 → 400,且库里不留半条脏数据(§六.3)', async () => { const [status, body] = await call('PATCH', `/tasks/${t2.id}`, { depends_on: [t2.id] }); expect(status).toBe(400); expect(body.error).toMatch(/依赖自己/); expect(JSON.parse(wdb.getTask(t2.id).depends_on)).toEqual([t1.id]); }); it('跑起来之后不许改依赖(判据在数据层,路由只负责翻成 409)', async () => { const [status] = await call('PATCH', `/tasks/${t1.id}`, { depends_on: [] }); expect(status).toBe(409); }); it('归档:正在跑的 task 拦下来并指出该先停哪条 run', async () => { const [status, body] = await call('DELETE', `/goals/${goal.id}`); expect(status).toBe(409); expect(body.runningTasks).toEqual([t1.id]); expect(body.hint).toContain('run_rt'); }); it('归档只是隐藏:默认列表不出现,includeArchived=1 查得回来', async () => { const [status] = await call('DELETE', `/tasks/${t2.id}`); expect(status).toBe(200); const [, plain] = await call('GET', '/tasks'); expect(plain.tasks.map((t) => t.taskId)).toEqual([t1.id]); const [, all] = await call('GET', '/tasks?includeArchived=1'); expect(all.tasks).toHaveLength(2); }); it('OKR 的 /goals 别名已退役:这条路径下只剩 goal 两级模型(§六.1)', async () => { // 别名还在的话,GET /goals 会被 OkrService 接走、返回 objective 数组而不是 { goals: [...] } const [status, body] = await call('GET', '/goals'); expect(status).toBe(200); expect(Array.isArray(body.goals)).toBe(true); expect(body.goals[0].goalId).toBe(goal.id); }); // ────────────────────────────────────────────────────────────── // 复核缺陷 F3 / F4 / F5 / F7 / F9 // ────────────────────────────────────────────────────────────── it('打错公司 id 的两个新 GET 端点回 404,不拿空列表冒充「没有目标」(缺陷 F9)', async () => { for (const p of ['/goals', '/tasks']) { const [status, body] = await callCompany('route-test-c0', 'GET', p); expect(status).toBe(404); expect(body.error).toMatch(/不存在/); } }); it('建 goal 时 tasks[].depends_on 可按 seq 引用同批兄弟,响应回真 id(缺陷 F5)', async () => { const [status, body] = await call('POST', '/goals', { description: '上线一个服务', tasks: [ { description: '构建镜像' }, { description: '部署到测试环境', depends_on: [1] }, // 1 = 本次第 1 条的 seq ], }); expect(status).toBe(201); const [build, deploy] = body.tasks; expect(deploy.seq).toBe(2); // 翻译成真 id 才算数:回 [1] 或 [] 都会让批 3 的调度器把这条依赖当不存在 expect(deploy.dependsOn).toEqual([build.taskId]); expect(JSON.parse(wdb.getTask(deploy.taskId).depends_on)).toEqual([build.taskId]); // 环仍然要被数据层挡住(seq 引用不是绕过校验的后门) const [cyclic, err] = await call('POST', '/goals', { description: '互相依赖', tasks: [ { description: 'A', depends_on: [2] }, { description: 'B', depends_on: [1] }, ], }); expect(cyclic).toBe(400); expect(err.error).toMatch(/环/); }); it('tasks[k] 非法 → 400,且 goals / tasks 两张表都不留残行(缺陷 F4)', async () => { const before = wdb.listCompanyGoals(CID, { includeArchived: true }).length; // task 也要数:只数 goal 的话,「goal 回滚了但第 0 条 task 已提交」这种半回滚是绿的 const beforeTasks = wdb.listCompanyTasks(CID, { includeArchived: true }).length; const [status, body] = await call('POST', '/goals', { description: '两条活,第二条写错了', tasks: [{ description: '合法的第一条' }, { description: '第二条', mode: 'AUTO' }], }); expect(status).toBe(400); expect(body.error).toMatch(/tasks\[1\]\.mode/); // 修之前:goal 已提交、第 0 条 task 已 INSERT,客户端改完重发就是第二个 goal, // 第一个孤儿 goal 带着孤儿 task 永远躺在列表里 expect(wdb.listCompanyGoals(CID, { includeArchived: true }).length).toBe(before); expect(wdb.listCompanyTasks(CID, { includeArchived: true }).length).toBe(beforeTasks); }); it('建 goal 时申报的 budget 落库到 task 行(缺陷 F3 的写侧)', async () => { const budget = { total_agent_calls: 7, total_tokens: 123456 }; const [status, body] = await call('POST', '/goals', { description: '带预算的需求', budget }); expect(status).toBe(201); // 只有写侧没有读侧等于没写;读侧(dispatch 起 run 时用它)在 goal-task-acceptance.test.js 里验 expect(JSON.parse(wdb.getTask(body.tasks[0].taskId).budget_json)).toEqual(budget); // 也要回得出来:查不到自己填的额度,用户就只能等任务 blocked 才发现不对 expect(body.tasks[0].budget).toEqual(budget); }); it('PATCH 的 mode 走同一道信任边界:非法值 400 而不是 500 泄 SQLite 原文(缺陷 F7)', async () => { const [, created] = await call('POST', '/goals', { description: '改 mode 用的 goal' }); const taskId = created.tasks[0].taskId; const [bad, err] = await call('PATCH', `/tasks/${taskId}`, { mode: 'AUTO' }); expect(bad).toBe(400); // 修之前:直送 DB 撞 CHECK 约束 → 500 + "CHECK constraint failed: …" expect(err.error).toMatch(/manual/); // null 既不是「没传」也不是合法值:修之前被 `!== undefined` 过滤掉 → 200 但什么都没改 const [nulled] = await call('PATCH', `/tasks/${taskId}`, { mode: null }); expect(nulled).toBe(400); const [ok, patched] = await call('PATCH', `/tasks/${taskId}`, { mode: 'auto' }); expect(ok).toBe(200); expect(patched.mode).toBe('auto'); }); });