taskboard-workbench 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +132 -0
- package/LICENSE +21 -0
- package/README.md +121 -2
- package/cli/tb.mjs +314 -0
- package/cordis.patch.yml +5 -0
- package/index.js +633 -0
- package/lib/client.js +522 -0
- package/package.json +83 -4
- package/spec//345/233/242/351/230/237agent.md +171 -0
- package/src/core/advance.mjs +192 -0
- package/src/core/agent-teams.mjs +48 -0
- package/src/core/binding.mjs +44 -0
- package/src/core/config.mjs +22 -0
- package/src/core/debug-dispatch.mjs +94 -0
- package/src/core/delivery.mjs +93 -0
- package/src/core/deps.mjs +53 -0
- package/src/core/diagnostics.mjs +648 -0
- package/src/core/domain.mjs +235 -0
- package/src/core/empty-state.mjs +240 -0
- package/src/core/errors.mjs +139 -0
- package/src/core/executor.mjs +645 -0
- package/src/core/human-review.mjs +773 -0
- package/src/core/intake.mjs +116 -0
- package/src/core/kickoff.mjs +147 -0
- package/src/core/loop.mjs +498 -0
- package/src/core/memory.mjs +193 -0
- package/src/core/next-step.mjs +377 -0
- package/src/core/notify.mjs +183 -0
- package/src/core/owner.mjs +41 -0
- package/src/core/requirements.mjs +262 -0
- package/src/core/review.mjs +82 -0
- package/src/core/session-naming.mjs +64 -0
- package/src/core/split-ask.mjs +107 -0
- package/src/core/store.mjs +3103 -0
- package/src/core/team.mjs +170 -0
- package/src/core/verify.mjs +170 -0
- package/src/core/watchdog.mjs +144 -0
- package/src/host/ai-elaborator.mjs +26 -0
- package/src/host/team-engine.mjs +125 -0
- package/src/host/tool-surface.mjs +205 -0
- package/src/server/api.mjs +1974 -0
- package/src/server/events.mjs +32 -0
- package/src/server/kickoff.mjs +46 -0
- package/src/server/server.mjs +211 -0
- package/src/server/verify.mjs +112 -0
- package/tools/env-check.mjs +35 -0
- package/tools/seed.mjs +67 -0
- package/web/app.js +5237 -0
- package/web/index.html +15 -0
- package/web/tokens.css +1139 -0
|
@@ -0,0 +1,1974 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* api.mjs —— 纯路由逻辑(不依赖 node:http)。独立服务与 DSH 宿主插件共用。
|
|
3
|
+
*/
|
|
4
|
+
import { PRIORITIES, STATUSES } from "../core/domain.mjs";
|
|
5
|
+
import { EXIT, TbError, invalidField } from "../core/errors.mjs";
|
|
6
|
+
import { resolveContext } from "../core/binding.mjs";
|
|
7
|
+
import { scanProjectMaterials, buildMaterialIndex, collectExternalFiles } from "../core/intake.mjs";
|
|
8
|
+
import { scanAgentTeams, OFFICIAL_TEAM } from "../core/agent-teams.mjs";
|
|
9
|
+
import { buildTeamDirective } from "../host/team-engine.mjs";
|
|
10
|
+
import { runExecutionLoop, activeEngine } from "../core/loop.mjs";
|
|
11
|
+
import { assertTeamTemplate, assertQualityGates, planTeamMembers } from "../core/team.mjs";
|
|
12
|
+
import { assessTaskRef, projectWatchdog } from "../core/watchdog.mjs";
|
|
13
|
+
import { isHumanReviewTask, planHumanReview } from "../core/human-review.mjs";
|
|
14
|
+
import { deriveNextStep } from "../core/next-step.mjs";
|
|
15
|
+
/**
|
|
16
|
+
* 能力缺失的统一措辞(真机 2026-10-29 · `:47830`「未能投递:host-unavailable · 检查宿主会话通道后重试」)。
|
|
17
|
+
*
|
|
18
|
+
* 旧文案把**能力缺失**说成了**临时故障** —— 人会一直重试一个永远不会成立的条件。
|
|
19
|
+
* 真实情况:独立进程实例(`node src/server/server.mjs`,没有 DSH 宿主)的 `host.capabilities` 恒为 `null`,
|
|
20
|
+
* 这类动作在该进程上**做不到**,正确出路是"换到 DSH 内的任务工作台"或"把 prompt 粘到会话里手工投递"。
|
|
21
|
+
*/
|
|
22
|
+
const HOST_UNAVAILABLE_NEXT = "该实例没有宿主会话通道(独立进程,/api/health 的 host.capabilities 为 null):改到 DSH 内的任务工作台操作,或把返回的 prompt 直接粘到会话里手工投递";
|
|
23
|
+
|
|
24
|
+
import { buildDebugDispatchPrompt } from "../core/debug-dispatch.mjs";
|
|
25
|
+
import { buildSplitAskPrompt } from "../core/split-ask.mjs";
|
|
26
|
+
import { buildReviewEvidence, formatVerifyComment, normalizeVerifyCommand, summarizeVerifyOutput, VERIFY_DEFAULT_COMMAND } from "../core/verify.mjs";
|
|
27
|
+
import { evaluateKickoff } from "../core/kickoff.mjs";
|
|
28
|
+
import { deriveEmptyState } from "../core/empty-state.mjs";
|
|
29
|
+
// 2026-10-28 拍板 E1–E3 / D-M1–D-M5:项目推进清单(纯投影 + 幂等回写)与项目记忆(L2 条目 + L3 召回)。
|
|
30
|
+
import { buildAdvance, renderAdvanceBlock, applyDecision } from "../core/advance.mjs";
|
|
31
|
+
import { renderMemoryBlock } from "../core/memory.mjs";
|
|
32
|
+
import { taskSessionTitle, projectMainSessionTitle } from "../core/session-naming.mjs";
|
|
33
|
+
import { collectKickoffFacts, hasEngineerExecutor, hasReviewerRole } from "./kickoff.mjs";
|
|
34
|
+
import { runVerifyCommand, probeVerifyApplicability } from "./verify.mjs";
|
|
35
|
+
import { DIAGNOSTIC_KINDS, evaluateTaskDiagnostics, projectDiagnostics, summarizeDiagnostics, resolveSessionRef, humanReviewProbe, humanReviewAnsweredBy } from "../core/diagnostics.mjs";
|
|
36
|
+
import { summarizeNotifyDelivery } from "../core/notify.mjs";
|
|
37
|
+
import { resolveCliExecutor, executeTaskWithCli, buildTaskPrompt, cliArgsFor, claimForCliExecution, DEFAULT_TIMEOUT_MS } from "../core/executor.mjs";
|
|
38
|
+
import { DEFAULT_FAILURE_LIMIT } from "../core/store.mjs";
|
|
39
|
+
|
|
40
|
+
export const API_SCHEMA_VERSION = 2;
|
|
41
|
+
|
|
42
|
+
export function httpStatusFor(error) {
|
|
43
|
+
if (error.code === "STORE_UNAVAILABLE") return 503;
|
|
44
|
+
if (error.code === "NOT_FOUND" || error.code.endsWith("_NOT_FOUND")) return 404;
|
|
45
|
+
if (error.exitCode === EXIT.CONFLICT) return 409;
|
|
46
|
+
return 400;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function createApiRouter({ store, aiElaborator, events } = {}) {
|
|
50
|
+
const emit = (type, payload) => { try { events?.publish?.(type, payload); } catch { /* ignore */ } };
|
|
51
|
+
/**
|
|
52
|
+
* 已有执行会话仍在执行(未返回结论)→ 不得再次下发。
|
|
53
|
+
* 判定:任务已记录执行会话,且宿主 agents 注册表显示该会话 running / inbox 仍有待消费消息。
|
|
54
|
+
*/
|
|
55
|
+
const inflightOf = (task) => {
|
|
56
|
+
// FR-77:**认领锁 + 心跳优先**——锁未过期且心跳新鲜才算"在途"(会话状态仅作降级信号)。
|
|
57
|
+
const claim = store.taskClaimState(task);
|
|
58
|
+
if (claim.locked && !claim.expired && !claim.stale) return { ...claim, via: "claim" };
|
|
59
|
+
const st = store.taskSessionState(task);
|
|
60
|
+
if (!st?.sessionId) return null;
|
|
61
|
+
if (st.running || (st.live && (st.pending ?? 0) > 0)) return { ...st, via: "session" };
|
|
62
|
+
return null;
|
|
63
|
+
};
|
|
64
|
+
const inflightError = (task, st) =>
|
|
65
|
+
new TbError(
|
|
66
|
+
"EXECUTION_ALREADY_RUNNING",
|
|
67
|
+
`当前已有在途执行(${st.via === "claim" ? `认领锁未过期、心跳 ${st.heartbeatAgeSeconds ?? "?"}s 前` : `会话仍在执行${st.pending ? `,待消费 ${st.pending} 条` : ""}`}):已停止再次下发。可「打开执行会话」查看进展,或等其回写状态/认领回收后再派发。`,
|
|
68
|
+
{
|
|
69
|
+
identifier: task.identifier, via: st.via,
|
|
70
|
+
sessionId: st.sessionId ?? null, lock: st.lock ?? null,
|
|
71
|
+
heartbeatAgeSeconds: st.heartbeatAgeSeconds ?? null,
|
|
72
|
+
status: st.status ?? null, pending: st.pending ?? 0,
|
|
73
|
+
},
|
|
74
|
+
);
|
|
75
|
+
/** FR-78:熔断原因 → 给用户的说明。 */
|
|
76
|
+
const circuitMessage = (reason, task) => {
|
|
77
|
+
const limit = task.maxRetries ?? DEFAULT_FAILURE_LIMIT;
|
|
78
|
+
if (reason === "quota-blocked") return `上次失败属配额/鉴权类(重试无益):已停止自动重试。请先解决配额/鉴权,或人工「重置失败计数」后再派发。${task.lastFailureError ? `\n原因:${task.lastFailureError}` : ""}`;
|
|
79
|
+
if (reason === "circuit-open") return `连续失败已达阈值(${task.consecutiveFailures ?? "?"}/${limit}):已熔断并置「受阻」,不再自动重试。请人工判断后用「重置失败计数」或修改任务后再派发。${task.lastFailureError ? `\n最近原因:${task.lastFailureError}` : ""}`;
|
|
80
|
+
return `窗口内该任务已成功完成且之后无人工重跑:为避免重复产出,已跳过自动派发。如需重跑请用「退回待办(重新派发)」。`;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* FR-84:会话存活判定(打开/接续前的统一探活)。
|
|
84
|
+
* `exists` 三态:true 存在 / false 确认失效 / **null 未知**(判不准时不得谎报失效)。
|
|
85
|
+
*/
|
|
86
|
+
async function sessionStateOf(sessionId) {
|
|
87
|
+
const port = store.hostSessionPort;
|
|
88
|
+
const live = (() => { try { return port?.sessionState?.(sessionId) ?? null; } catch { return null; } })();
|
|
89
|
+
let exists = null;
|
|
90
|
+
let source = "unavailable";
|
|
91
|
+
if (typeof port?.sessionExists === "function") {
|
|
92
|
+
try { const r = await port.sessionExists(sessionId); exists = r?.exists ?? null; source = r?.source ?? "sessionExists"; }
|
|
93
|
+
catch (error) { exists = null; source = `error:${error?.code ?? error?.message ?? "unknown"}`; }
|
|
94
|
+
} else if (live?.live) { exists = true; source = "agents"; }
|
|
95
|
+
return {
|
|
96
|
+
sessionId: sessionId ?? null, exists, source,
|
|
97
|
+
live: Boolean(live?.live), running: Boolean(live?.running), status: live?.status ?? null, pending: live?.pending ?? 0,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* FR-84 补口 · **接续会话的工作区归属**:会话创建时的 cwd → 归属项目。
|
|
103
|
+
*
|
|
104
|
+
* 为什么需要:`resolveSessionRef` 的三级回落只判「存在/存活」,**不判这个会话是不是本项目的**。
|
|
105
|
+
* 真机事故(2026-10-19):`taskboard-workbench` 的主会话指针被指到**另一个工作区**(项目-dsh-acp)的
|
|
106
|
+
* 6.3 MB 会话上 → 看板每张卡「打开执行会话」都会打开**别人的、巨大的**会话,对话页长时间只显示输入框。
|
|
107
|
+
*
|
|
108
|
+
* 判定口径:`mismatch:true` = 会话 cwd 归属的项目 ≠ 当前项目(或不属于任何项目);
|
|
109
|
+
* **判不准**(宿主不给 cwd / 项目没有 workspacePath)一律 `mismatch:null` —— 不臆断、不误拦。
|
|
110
|
+
*/
|
|
111
|
+
async function sessionOriginOf(sessionId, project = null) {
|
|
112
|
+
const base = { sessionId: sessionId ?? null, cwd: null, projectId: null, projectName: null, mismatch: null, source: "unavailable" };
|
|
113
|
+
if (!sessionId) return base;
|
|
114
|
+
const port = store.hostSessionPort;
|
|
115
|
+
if (!port || typeof port.sessionOrigin !== "function") return base;
|
|
116
|
+
let info = null;
|
|
117
|
+
try { info = await port.sessionOrigin(sessionId); }
|
|
118
|
+
catch (error) { return { ...base, source: `error:${error?.code ?? error?.message ?? "unknown"}` }; }
|
|
119
|
+
const cwd = info?.cwd ?? null;
|
|
120
|
+
if (!cwd) return { ...base, source: info?.source ?? "unknown" };
|
|
121
|
+
// 显式路径比对(**不用 `resolveProjectForCwd`**:它在无匹配时会回落"第一个项目",会把"谁都不属于"误判成"属于本项目")。
|
|
122
|
+
const norm = (p) => String(p ?? "").replace(/\/+$/, "");
|
|
123
|
+
const cwdNorm = norm(cwd);
|
|
124
|
+
const under = (base) => {
|
|
125
|
+
const b = norm(base);
|
|
126
|
+
return Boolean(b) && (cwdNorm === b || cwdNorm.startsWith(`${b}/`));
|
|
127
|
+
};
|
|
128
|
+
const owner = store.listProjects().filter((p) => under(p.workspacePath)).sort((a, b) => norm(b.workspacePath).length - norm(a.workspacePath).length)[0] ?? null;
|
|
129
|
+
const hasOwnPath = Boolean(norm(project?.workspacePath));
|
|
130
|
+
const mismatch = hasOwnPath ? !under(project.workspacePath) : null;
|
|
131
|
+
return { sessionId, cwd, projectId: owner?.id ?? null, projectName: owner?.name ?? null, mismatch, source: info?.source ?? "unknown" };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* FR-61 开局提示词(重建主会话后投递,确保新会话知道自己是项目主会话)。
|
|
135
|
+
*
|
|
136
|
+
* **格式口径(卡 `-145` · `docs/规范/01-协作规范.md` §一)**:本仓「派发指令」的第二个产出点,
|
|
137
|
+
* 按 §一 模板给齐 **已获授权 / 硬边界 / 停下情形 / 回报格式**。它是**长期坐席**的主会话指令
|
|
138
|
+
* (不像 `buildTaskPrompt` 一次一卡),故不写 Step 0/1/2 的逐卡判据,改为「每接到一张卡时」
|
|
139
|
+
* 的判据与停下情形 —— 保持 §一 的字段齐备,同时不臆造一次性的分步流程。
|
|
140
|
+
*/
|
|
141
|
+
function buildOpeningPrompt(project) {
|
|
142
|
+
return [
|
|
143
|
+
`[任务工作台 · 项目主会话] 项目:${project?.name ?? project?.id ?? "?"}(${project?.id ?? "?"})`,
|
|
144
|
+
"你已成为该项目的**主会话**:工作台的任务派发、状态回流与通知唤醒都会投递到这里。",
|
|
145
|
+
"请在该会话内加载「任务工作台」插件,并在需要时按团队契约创建/承接 agent team(详见随包文档 `spec/团队agent.md` 的『智能体操作规范(随包)』一节)。",
|
|
146
|
+
"",
|
|
147
|
+
"## 已获授权",
|
|
148
|
+
"- 在本项目工作区内认领并执行派发到本会话的任务卡(`todo` 卡不得直接执行,须先经人授权开工)。",
|
|
149
|
+
"- 在本项目工作区内运行只读检查与该卡相关的测试 / 构建命令。",
|
|
150
|
+
"- 代拟派发给子 agent 的任务书时,按 `docs/规范/01-协作规范.md` §一 模板书写。",
|
|
151
|
+
"",
|
|
152
|
+
"## 硬边界",
|
|
153
|
+
"- ❌ 执行侧不得置「完成(done)」—— 完成只能由人确认;你只提交「待验收」。",
|
|
154
|
+
"- ❌ 不 commit / 不 push。",
|
|
155
|
+
"- ❌ 不改范围外文件;不改历史决策文档;不删既有数据。",
|
|
156
|
+
"- ❌ 不自行重载 / 重启 dsh 宿主进程,不动 `~/.dsh/profiles/**`(属须报批范围,见 AGENTS.md §3)。",
|
|
157
|
+
"",
|
|
158
|
+
"## 每接到一张卡时的判据",
|
|
159
|
+
"- 先读该卡的描述、`acceptance`(完成验收标准)与复核动作、以及全部既有评论,再动手。",
|
|
160
|
+
"- 判据 = 该卡 `acceptance` 逐条可核 + 复核动作退出码为 0。",
|
|
161
|
+
"",
|
|
162
|
+
"---",
|
|
163
|
+
"",
|
|
164
|
+
"## 回报格式(严格按这四节,缺节=不合格)",
|
|
165
|
+
"**判定**:完成 / 部分 / 停下(哪一步)",
|
|
166
|
+
"**偏离说明**:指令假设 X、实测 Y、故改为 Z;**无偏离也显式写「无」**,不得省略本节。",
|
|
167
|
+
"**边界自查**:逐条对齐上方「硬边界」的 ❌ 清单。",
|
|
168
|
+
"**产物路径**:改动文件清单、测试输出、落盘报告或截图的路径。",
|
|
169
|
+
"",
|
|
170
|
+
"## 停下情形(严格,逐条编号;命中即停)",
|
|
171
|
+
"1. 前置不满足(卡片未授权 / `acceptance` 为空且无从判定 / 基线非绿)→ 停下并回报「停下(Step 0)」。",
|
|
172
|
+
"2. 门禁不过(复核动作退出码非 0)→ 停在失败步,贴出失败证据,不修饰。",
|
|
173
|
+
"3. 不可逆动作前(commit / push / 重载宿主 / 插件增删)→ 一律停,等人授权;指令不含此授权。",
|
|
174
|
+
"4. 偏离预期(实测与卡面不符)→ 停,并在「偏离说明」写清「指令假设 X、实测 Y、故改为 Z」。",
|
|
175
|
+
"",
|
|
176
|
+
"## 禁止",
|
|
177
|
+
"- 不得以「报告说完成」当事实:交付前用实际命令自证(`git status`、测试输出)。",
|
|
178
|
+
"- 不得臆断:实测不到的事实写「未取得 / 无法判定」,不编造。",
|
|
179
|
+
].join("\n");
|
|
180
|
+
}
|
|
181
|
+
async function route({ method, pathname, searchParams, body = {} }) {
|
|
182
|
+
if (pathname === "/api/health" && method === "GET") {
|
|
183
|
+
// 宿主能力可见性(诊断):投递指令 / 建会话 / 打开会话 各依赖的宿主服务是否已就绪。
|
|
184
|
+
const has = (fn) => { try { return typeof fn === "function"; } catch { return false; } };
|
|
185
|
+
const port = store.hostSessionPort;
|
|
186
|
+
const host = {
|
|
187
|
+
createSession: Boolean(port?.available),
|
|
188
|
+
sendPrompt: has(port?.sendPrompt),
|
|
189
|
+
openSession: has(port?.openSession),
|
|
190
|
+
// 2026-10-29(二轮复核):**按"真正依赖的能力"报**,不要拿 createSession 当万能代理 ——
|
|
191
|
+
// FR-84 的「改绑已有会话 / 改指本任务」恰恰在**建会话不可用**时是保底出口(`sessionExists`/`listSessions`
|
|
192
|
+
// 在、`createSession` 不在),拿 createSession 去置灰它们会把唯一的出路也焊死。
|
|
193
|
+
listSessions: has(port?.listSessions),
|
|
194
|
+
sessionExists: has(port?.sessionExists),
|
|
195
|
+
sessionOrigin: has(port?.sessionOrigin),
|
|
196
|
+
renameSession: has(port?.renameSession),
|
|
197
|
+
sessionState: has(port?.sessionState),
|
|
198
|
+
capabilities: (() => { try { return port?.capabilities?.() ?? null; } catch { return null; } })(),
|
|
199
|
+
};
|
|
200
|
+
return { status: 200, payload: { status: "ok", host, ...store.stats() } };
|
|
201
|
+
}
|
|
202
|
+
if (pathname === "/api/host/probe" && method === "GET") {
|
|
203
|
+
// 只读探测:宿主「建会话」这条路此刻通不通。**不建会话、不写任何数据**。
|
|
204
|
+
const port = store.hostSessionPort;
|
|
205
|
+
let probe = null;
|
|
206
|
+
try { probe = (await port?.probeHost?.()) ?? null; }
|
|
207
|
+
catch (error) { probe = { verdict: "error:" + (error?.message ?? String(error)) }; }
|
|
208
|
+
return { status: 200, payload: { schemaVersion: 2, probe } };
|
|
209
|
+
}
|
|
210
|
+
if (pathname === "/api/meta" && method === "GET") {
|
|
211
|
+
return {
|
|
212
|
+
status: 200,
|
|
213
|
+
payload: { statuses: STATUSES, priorities: PRIORITIES, dataDir: store.dataDir, dbPath: store.dbPath },
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
if (pathname === "/api/context" && method === "GET") {
|
|
217
|
+
// 工作区(cwd) → 项目 → 需求文档 的初始绑定;session= 时绑定/校验"主会话与关联"(FR-60/FR-62/FR-63)
|
|
218
|
+
const cwd = searchParams.get("cwd") ?? undefined;
|
|
219
|
+
const session = searchParams.get("session") ?? undefined;
|
|
220
|
+
const projectParam = searchParams.get("project") ?? undefined;
|
|
221
|
+
// FR-60/63:优先按"会话归属哪个项目"解析(主会话/已关联),避免只按 cwd 误落到别的项目
|
|
222
|
+
const bySession = session ? store.findProjectBySession(session) : null;
|
|
223
|
+
let ctx = projectParam
|
|
224
|
+
? { project: store.requireProject(projectParam), requirementDoc: store.ensureRequirementDoc(projectParam) }
|
|
225
|
+
: bySession
|
|
226
|
+
? { project: bySession.project, requirementDoc: store.ensureRequirementDoc(bySession.project.id) }
|
|
227
|
+
: resolveContext(store, cwd);
|
|
228
|
+
// FR-62:全局入口(无会话、无工作区)默认进入"近期执行"项目
|
|
229
|
+
if (!session && !cwd && !projectParam) {
|
|
230
|
+
const dp = store.defaultProject();
|
|
231
|
+
if (dp) ctx = { project: dp, requirementDoc: store.ensureRequirementDoc(dp.id) };
|
|
232
|
+
}
|
|
233
|
+
let sessionBound = null;
|
|
234
|
+
let association = null;
|
|
235
|
+
if (ctx.project && session) {
|
|
236
|
+
// 首个进入该项目的会话成为"主会话"(首次绑定不改写)
|
|
237
|
+
if (!ctx.project.initialSessionId) ctx = { ...ctx, project: store.bindInitialSession(ctx.project.id, session) };
|
|
238
|
+
const binding = store.sessionBinding(ctx.project.id, session);
|
|
239
|
+
sessionBound = binding.bound;
|
|
240
|
+
association = binding.role;
|
|
241
|
+
}
|
|
242
|
+
const mainSessionId = ctx.project ? (store.requireProject(ctx.project.id).initialSessionId ?? null) : null;
|
|
243
|
+
// FR-84 补口(2026-10-23)· **实例工作区预检**:一个 DSH 实例只有一个工作区(宿主不给切换服务,
|
|
244
|
+
// `capabilities.uiWorkspace=false`),所以「在看板里切到别的项目」**不会**让宿主跟着换工作区。
|
|
245
|
+
// 这里把「本会话落哪个工作区」如实交出来(只读探测),前端据此提前告知,不再让用户走
|
|
246
|
+
// 「重建 → 还是说工作区不对」的弯路。
|
|
247
|
+
const sessionOrigin = session ? await sessionOriginOf(session, ctx.project ?? null) : null;
|
|
248
|
+
return { status: 200, payload: { cwd: cwd ?? null, session: session ?? null, project: ctx.project, requirementDoc: ctx.requirementDoc, sessionBound, mainSessionId, association, sessionOrigin } };
|
|
249
|
+
}
|
|
250
|
+
if (pathname === "/api/projects") {
|
|
251
|
+
if (method === "GET") {
|
|
252
|
+
const projects = store.listProjects();
|
|
253
|
+
return { status: 200, payload: { projects, count: projects.length } };
|
|
254
|
+
}
|
|
255
|
+
if (method === "POST") {
|
|
256
|
+
const project = store.createProject({ name: body.name, id: body.id, workspacePath: body.workspacePath ?? null });
|
|
257
|
+
return { status: 201, payload: { project } };
|
|
258
|
+
}
|
|
259
|
+
throw new TbError("USAGE_ERROR", "/api/projects 仅支持 GET 或 POST");
|
|
260
|
+
}
|
|
261
|
+
// FR-03:删除项目(非空守卫)。`confirm` 可走 query(`?confirm=1`)或 body(`{confirm:true}`)。
|
|
262
|
+
// 非空被拒 / 未确认被拒都抛 TbError(`PROJECT_NOT_EMPTY` / `PROJECT_DELETE_UNCONFIRMED`),
|
|
263
|
+
// 由上层统一映射成 HTTP 状态码 + 明确提示,不静默成功。
|
|
264
|
+
const projectDeleteRoute = /^\/api\/projects\/([^/]+)$/.exec(pathname);
|
|
265
|
+
if (projectDeleteRoute) {
|
|
266
|
+
if (method !== "DELETE") throw new TbError("USAGE_ERROR", "/api/projects/:ref 仅支持 DELETE");
|
|
267
|
+
const ref = decodeURIComponent(projectDeleteRoute[1]);
|
|
268
|
+
const confirm = body.confirm === true || searchParams.get("confirm") === "1";
|
|
269
|
+
const deleted = store.deleteProject(ref, { confirm, actor: body.actor ?? "human", reason: body.reason ?? null });
|
|
270
|
+
return { status: 200, payload: { deleted } };
|
|
271
|
+
}
|
|
272
|
+
// 项目资料引入(FR-55):把本地项目文件夹的 md/doc 资料引入工作台
|
|
273
|
+
const projectIntakeRoute = /^\/api\/projects\/([^/]+)\/intake$/.exec(pathname);
|
|
274
|
+
if (projectIntakeRoute) {
|
|
275
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "intake 仅支持 POST");
|
|
276
|
+
const project = store.requireProject(decodeURIComponent(projectIntakeRoute[1]));
|
|
277
|
+
const root = body.path ?? project.workspacePath;
|
|
278
|
+
if (!root) throw new TbError("USAGE_ERROR", "未指定 path,且项目没有 workspacePath");
|
|
279
|
+
const scan = await scanProjectMaterials(root, {
|
|
280
|
+
maxFiles: body.maxFiles ?? 500, maxDepth: body.maxDepth ?? 8,
|
|
281
|
+
exts: body.exts, include: body.include, exclude: body.exclude,
|
|
282
|
+
});
|
|
283
|
+
// 工作区外的显式文件(extraPaths):按引用纳入,不拷贝
|
|
284
|
+
const extra = await collectExternalFiles(body.extraPaths ?? []);
|
|
285
|
+
const combined = extra.length ? { ...scan, files: [...scan.files, ...extra], count: scan.files.length + extra.length } : scan;
|
|
286
|
+
const built = await buildMaterialIndex(combined, { maxBytesPerFile: body.maxBytesPerFile ?? 8000, includeContent: body.includeContent !== false });
|
|
287
|
+
if (body.dryRun) {
|
|
288
|
+
return { status: 200, payload: { project: project.id, root: combined.root, scanned: combined.count, truncated: combined.truncated, files: combined.files.map((f) => ({ relPath: f.relPath, bytes: f.bytes, readable: f.readable, external: !!f.external })), dryRun: true } };
|
|
289
|
+
}
|
|
290
|
+
const mode = body.mode ?? "both";
|
|
291
|
+
let doc = null;
|
|
292
|
+
if (mode !== "items") {
|
|
293
|
+
const ensured = store.ensureRequirementDoc(project.id, { body: "" });
|
|
294
|
+
doc = store.updateRequirementDoc(ensured.id, { expectedVersion: ensured.version, body: built.index });
|
|
295
|
+
}
|
|
296
|
+
let created = [];
|
|
297
|
+
if (mode === "items" || mode === "both") {
|
|
298
|
+
const existing = new Set(store.listRequirementItems({ projectId: project.id }).map((i) => i.title));
|
|
299
|
+
for (const d of built.docs) {
|
|
300
|
+
if (existing.has(d.title)) continue;
|
|
301
|
+
const item = store.createRequirementItem({
|
|
302
|
+
projectId: project.id, title: d.title, docId: doc?.id,
|
|
303
|
+
description: `来源:\`${d.relPath}\`\n\n${d.content.slice(0, 2000)}`,
|
|
304
|
+
source: "intake", status: body.status ?? "draft",
|
|
305
|
+
});
|
|
306
|
+
existing.add(d.title);
|
|
307
|
+
created.push({ identifier: item.identifier, title: item.title });
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
status: 201,
|
|
312
|
+
payload: {
|
|
313
|
+
project: project.id, root: combined.root, scanned: combined.count, truncated: combined.truncated, mode,
|
|
314
|
+
doc: doc ? { id: doc.id, version: doc.version, bytes: built.index.length } : null,
|
|
315
|
+
itemsCreated: created.length, items: created,
|
|
316
|
+
},
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
// FR-92:**项目开局对齐**自检(标准步骤程序)—— 只读,绝不写任何数据。
|
|
320
|
+
// 用户 2026-10-22 要求把《Vibe Coding 团队协作技巧》作为「项目开局对齐事项」引入,
|
|
321
|
+
// 并「作为任务工作台标准步骤程序执行」:这里让工作台能自己回答"这个项目对齐了没有"。
|
|
322
|
+
const projectKickoffRoute = /^\/api\/projects\/([^/]+)\/kickoff$/.exec(pathname);
|
|
323
|
+
if (projectKickoffRoute) {
|
|
324
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "/api/projects/:id/kickoff 仅支持 GET");
|
|
325
|
+
const project = store.requireProject(decodeURIComponent(projectKickoffRoute[1]));
|
|
326
|
+
const settings = store.getProjectSettings(project.id);
|
|
327
|
+
const facts = collectKickoffFacts(project.workspacePath ?? null);
|
|
328
|
+
const report = evaluateKickoff({
|
|
329
|
+
files: facts.files,
|
|
330
|
+
settings,
|
|
331
|
+
custom: { reviewerRole: hasReviewerRole(settings?.teamTemplate), engineerExecutor: hasEngineerExecutor(settings?.teamTemplate) },
|
|
332
|
+
});
|
|
333
|
+
return { status: 200, payload: { project: project.id, workspacePath: project.workspacePath ?? null, readable: facts.readable, ...report } };
|
|
334
|
+
}
|
|
335
|
+
// 项目设置(FR-56):项目环境约束 + agent 执行团队模板
|
|
336
|
+
const projectSettingsRoute = /^\/api\/projects\/([^/]+)\/settings$/.exec(pathname);
|
|
337
|
+
if (projectSettingsRoute) {
|
|
338
|
+
const project = store.requireProject(decodeURIComponent(projectSettingsRoute[1]));
|
|
339
|
+
if (method === "GET") return { status: 200, payload: store.getProjectSettings(project.id) };
|
|
340
|
+
if (method === "PUT" || method === "POST") {
|
|
341
|
+
// FR-50 残留:保存前过**模板质量门**(与建队同口径,均在**写库之前**,被拒则设置保持原样)。
|
|
342
|
+
// · 已配置 roles ⇒ 走与 `POST /api/teams` 完全同一道门 `assertTeamTemplate({ roles, qualityGates })`;
|
|
343
|
+
// · 未传 / 空 roles ⇒ **保持既有含义**(允许只改 engine / executionTeam / envConfig 等),
|
|
344
|
+
// 此时仍校验质量门(未配置放行;已配置但越界 ⇒ INVALID_TEAM_TEMPLATE / quality-gate-unknown)。
|
|
345
|
+
if (body.teamTemplate !== undefined && body.teamTemplate !== null) {
|
|
346
|
+
const tpl = body.teamTemplate;
|
|
347
|
+
const roles = Array.isArray(tpl?.roles) ? tpl.roles : [];
|
|
348
|
+
if (roles.length) assertTeamTemplate({ roles, qualityGates: tpl?.qualityGates });
|
|
349
|
+
else assertQualityGates({ qualityGates: tpl?.qualityGates });
|
|
350
|
+
}
|
|
351
|
+
const saved = store.saveProjectSettings(project.id, { envConfig: body.envConfig, teamTemplate: body.teamTemplate, loop: body.loop });
|
|
352
|
+
return { status: 200, payload: saved };
|
|
353
|
+
}
|
|
354
|
+
throw new TbError("USAGE_ERROR", "settings 仅支持 GET 或 PUT");
|
|
355
|
+
}
|
|
356
|
+
// 会话 ↔ 项目关联(FR-63):列出 / 申请 / 批准
|
|
357
|
+
const projectAgentTeamsRoute = /^\/api\/projects\/([^/]+)\/agent-teams$/.exec(pathname);
|
|
358
|
+
if (projectAgentTeamsRoute) {
|
|
359
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "agent-teams 仅支持 GET");
|
|
360
|
+
const project = store.requireProject(decodeURIComponent(projectAgentTeamsRoute[1]));
|
|
361
|
+
// 只列"本项目主会话自身"的团队:官方(队长=主会话)+ 第三方(captainSessionId == 主会话)
|
|
362
|
+
const thirdParty = await scanAgentTeams(project.workspacePath, { mainSessionId: project.initialSessionId ?? null });
|
|
363
|
+
return { status: 200, payload: { mainSessionId: project.initialSessionId ?? null, teams: [OFFICIAL_TEAM, ...thirdParty], count: 1 + thirdParty.length } };
|
|
364
|
+
}
|
|
365
|
+
const projectSessionsRoute = /^\/api\/projects\/([^/]+)\/sessions$/.exec(pathname);
|
|
366
|
+
if (projectSessionsRoute) {
|
|
367
|
+
const project = store.requireProject(decodeURIComponent(projectSessionsRoute[1]));
|
|
368
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "sessions 仅支持 GET");
|
|
369
|
+
// FR-84:每条绑定附**存活徽标**,并单列主会话(失效时前端可一键重建)。
|
|
370
|
+
const rows = store.listProjectSessions(project.id);
|
|
371
|
+
const sessions = [];
|
|
372
|
+
for (const row of rows) sessions.push({ ...row, liveness: await sessionStateOf(row.sessionId) });
|
|
373
|
+
const mainSessionId = project.initialSessionId ?? null;
|
|
374
|
+
const main = mainSessionId ? { sessionId: mainSessionId, role: "main", liveness: await sessionStateOf(mainSessionId) } : null;
|
|
375
|
+
return { status: 200, payload: { sessions, main, staleMain: Boolean(main && main.liveness.exists === false) } };
|
|
376
|
+
}
|
|
377
|
+
// FR-84 补口(2026-10-22)· **本工作区已有会话**候选列表。
|
|
378
|
+
// 用途:宿主**建会话**能力不可用时(实例未加载宿主 shim → `create()` 抛
|
|
379
|
+
// "Agent preset binding requires a scoped context"),「重建并绑定项目主会话」这条路会**彻底走不通**,
|
|
380
|
+
// 而**改绑一个本工作区已有会话**完全不需要建会话 —— 这是接续流程的保底出口。
|
|
381
|
+
const projectSessionCandidatesRoute = /^\/api\/projects\/([^/]+)\/sessions\/candidates$/.exec(pathname);
|
|
382
|
+
if (projectSessionCandidatesRoute) {
|
|
383
|
+
const project = store.requireProject(decodeURIComponent(projectSessionCandidatesRoute[1]));
|
|
384
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "candidates 仅支持 GET");
|
|
385
|
+
const want = project.workspacePath ?? null;
|
|
386
|
+
const port = store.hostSessionPort;
|
|
387
|
+
const base = { projectId: project.id, workspacePath: want, current: project.initialSessionId ?? null, candidates: [] };
|
|
388
|
+
if (!port || typeof port.listSessions !== "function") {
|
|
389
|
+
return { status: 200, payload: { ...base, source: "unavailable", total: 0, reason: "host-cannot-list-sessions" } };
|
|
390
|
+
}
|
|
391
|
+
let res = null;
|
|
392
|
+
try { res = await port.listSessions({ cwd: want ?? undefined }); }
|
|
393
|
+
catch (error) { return { status: 200, payload: { ...base, source: "error", total: 0, reason: error?.code ?? String(error?.message ?? error) } }; }
|
|
394
|
+
const all = Array.isArray(res?.sessions) ? res.sessions : [];
|
|
395
|
+
const candidates = [];
|
|
396
|
+
for (const row of all.slice(0, 50)) {
|
|
397
|
+
candidates.push({
|
|
398
|
+
sessionId: row.sessionId,
|
|
399
|
+
title: row.title ?? null,
|
|
400
|
+
updatedAt: row.updatedAt ?? null,
|
|
401
|
+
cwd: row.cwd ?? null,
|
|
402
|
+
isCurrent: row.sessionId === (project.initialSessionId ?? null),
|
|
403
|
+
liveness: await sessionStateOf(row.sessionId),
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
return { status: 200, payload: { ...base, source: res?.source ?? "unknown", reason: res?.reason ?? null, total: all.length, candidates } };
|
|
407
|
+
}
|
|
408
|
+
// FR-84:重建并重绑项目主会话(需 confirm;成功后投递 FR-61 开局提示词并写审计)。
|
|
409
|
+
const projectRebindRoute = /^\/api\/projects\/([^/]+)\/sessions\/rebind$/.exec(pathname);
|
|
410
|
+
if (projectRebindRoute) {
|
|
411
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "rebind 仅支持 POST");
|
|
412
|
+
const project = store.requireProject(decodeURIComponent(projectRebindRoute[1]));
|
|
413
|
+
const confirmed = body.confirm === true || searchParams.get("confirm") === "1";
|
|
414
|
+
if (!confirmed) return { status: 200, payload: { rebound: false, reason: "confirm-required", projectId: project.id, current: project.initialSessionId ?? null } };
|
|
415
|
+
const port = store.hostSessionPort;
|
|
416
|
+
// FR-84 补口(2026-10-22)· **改绑已有会话**(`sessionId` 显式给出时走这条,**不新建会话**):
|
|
417
|
+
// 真机现场:`:3080` 实例未加载宿主 shim 时 `createSession()` 必抛错 ⇒「重建并绑定项目主会话」点不通,
|
|
418
|
+
// 而项目主会话指针又指着**另一个工作区**的旧会话 ⇒ 用户「从任务台回不到项目主会话」。
|
|
419
|
+
// 改绑路径的前提校验一条都不能省:**必须先探活**(不存在不让绑),**必须校验工作区归属**
|
|
420
|
+
//(指向别的工作区的会话正是本补口要修的病根,默认拒绝,`force:true` 才放行)。
|
|
421
|
+
const explicitSessionId = body.sessionId ?? searchParams.get("session") ?? null;
|
|
422
|
+
if (explicitSessionId) {
|
|
423
|
+
if (!port || typeof port.sessionExists !== "function") throw new TbError("HOST_UNAVAILABLE", "宿主不支持校验会话:无法改绑主会话");
|
|
424
|
+
const existsRes = await port.sessionExists(explicitSessionId);
|
|
425
|
+
if (existsRes?.exists === false) {
|
|
426
|
+
throw new TbError("SESSION_NOT_FOUND", "该会话在本机不存在:不能绑定为项目主会话", { sessionId: explicitSessionId });
|
|
427
|
+
}
|
|
428
|
+
let origin = null;
|
|
429
|
+
if (typeof port.sessionOrigin === "function") { try { origin = await port.sessionOrigin(explicitSessionId); } catch { origin = null; } }
|
|
430
|
+
const want = project.workspacePath ?? null;
|
|
431
|
+
const got = origin?.cwd ?? null;
|
|
432
|
+
const mismatch = Boolean(want && got && got !== want);
|
|
433
|
+
if (mismatch && body.force !== true) {
|
|
434
|
+
throw new TbError("SESSION_OTHER_WORKSPACE", `该会话属于另一个工作区:${got}(本项目工作区 ${want})→ 默认拒绝改绑;确要改绑请显式 force`, { sessionId: explicitSessionId, cwd: got, workspacePath: want });
|
|
435
|
+
}
|
|
436
|
+
// 2026-10-23 用户命名约束(口径 2 后半):**重绑**的主会话名后跟备注「重绑」。
|
|
437
|
+
// 只改该会话标题(用户可见),不动它的历史;拿不到确认就如实回报,不谎报。
|
|
438
|
+
// FR-95 补口(2026-10-26):把**算出来的名字**一并回包(`sessionName`),前端才能如实显示
|
|
439
|
+
// 「已命名《…》」或「⚠ 会话名未生效(原因)」—— 此前 API 回了 titleApplied,但**没有任何界面展示它**,
|
|
440
|
+
// 改名失败时用户看不到半点提示(「如实回报」断在最后一跳)。
|
|
441
|
+
const boundSessionName = projectMainSessionTitle(project.name, { note: "重绑" });
|
|
442
|
+
let titleApplied2 = null; let titleReason2 = null;
|
|
443
|
+
if (typeof port.renameSession === "function") {
|
|
444
|
+
try {
|
|
445
|
+
const named = await port.renameSession(explicitSessionId, boundSessionName);
|
|
446
|
+
titleApplied2 = Boolean(named?.renamed);
|
|
447
|
+
titleReason2 = named?.renamed ? null : (named?.reason ?? "rename-failed");
|
|
448
|
+
} catch (error) { titleApplied2 = false; titleReason2 = error?.code ?? String(error?.message ?? error); }
|
|
449
|
+
}
|
|
450
|
+
const rbExisting = store.rebindInitialSession(project.id, explicitSessionId);
|
|
451
|
+
let openingDelivered2 = false; let deliveryReason2 = null;
|
|
452
|
+
// 该会话通常**已有历史** ⇒ 默认不投递开局提示词(避免往用户的历史会话里塞指令);要投递须显式 deliverOpening:true。
|
|
453
|
+
if (body.deliverOpening === true && typeof port.sendPrompt === "function") {
|
|
454
|
+
try { const r = await port.sendPrompt(explicitSessionId, buildOpeningPrompt(rbExisting.project)); openingDelivered2 = Boolean(r?.sent); deliveryReason2 = r?.reason ?? null; }
|
|
455
|
+
catch (error) { deliveryReason2 = error?.code ?? String(error?.message ?? error); }
|
|
456
|
+
}
|
|
457
|
+
const auditId2 = store.recordAudit({ actor: "board", action: "rebind-initial-session", target: project.id, allowed: true, reason: "bind-existing", detail: JSON.stringify({ before: rbExisting.before, after: rbExisting.after, mode: "bind-existing", cwd: got, mismatch, openingDelivered: openingDelivered2, deliveryReason: deliveryReason2, titleApplied: titleApplied2, titleReason: titleReason2 }) });
|
|
458
|
+
emit("project.updated", { projectId: project.id, initialSessionId: rbExisting.after });
|
|
459
|
+
return { status: 200, payload: { rebound: true, mode: "bind-existing", projectId: project.id, before: rbExisting.before, after: rbExisting.after, cwd: got, mismatch, openingDelivered: openingDelivered2, deliveryReason: deliveryReason2, titleApplied: titleApplied2, titleReason: titleReason2, sessionName: boundSessionName, auditId: auditId2 } };
|
|
460
|
+
}
|
|
461
|
+
if (!port || typeof port.createSession !== "function") throw new TbError("HOST_UNAVAILABLE", "宿主不支持建会话:无法重建主会话");
|
|
462
|
+
// FR-84 修复(2026-10-19):把**项目自己的工作区**传给宿主,否则新会话落在 dsh 进程目录上,
|
|
463
|
+
// 「重建并绑定」之后**仍会被归属门拦下**(项目 workspacePath ≠ 进程 cwd 时必现,见轮次记录 §十)。
|
|
464
|
+
// 2026-10-23 用户命名约束(口径 2):项目主会话统一「【项目】+ 项目名称」;
|
|
465
|
+
// 本次是**重建**(此前已有指针)⇒ 名称后跟备注「重建」(口径 2 后半)。
|
|
466
|
+
// FR-95 补口(2026-10-26):名字算一次、回包带上(`sessionName`),见下方同名注释。
|
|
467
|
+
const mainSessionName = projectMainSessionTitle(project.name, { note: project.initialSessionId ? "重建" : null });
|
|
468
|
+
const created = await port.createSession({
|
|
469
|
+
cwd: project.workspacePath ?? undefined,
|
|
470
|
+
title: mainSessionName,
|
|
471
|
+
});
|
|
472
|
+
const sessionId = created?.sessionId ?? null;
|
|
473
|
+
if (!sessionId) throw new TbError("SESSION_CREATE_FAILED", "宿主未能创建会话", { reason: created?.reason ?? null });
|
|
474
|
+
// FR-84 补口(2026-10-23)· **建完必须验工作区**:宿主若忽略 `cwd`(或本 DSH 实例的工作区与项目不一致),
|
|
475
|
+
// 新会话会落在**进程目录**上 —— 此时若照旧写回指针,用户会得到「重建了还是说工作区不对」的**静默错绑**。
|
|
476
|
+
// 现在改成**如实失败**:报出两个路径、不改写主会话指针(新会话留在磁盘上,不删除、不引用)。
|
|
477
|
+
const createdOrigin = await sessionOriginOf(sessionId, project);
|
|
478
|
+
if (createdOrigin.mismatch === true) {
|
|
479
|
+
throw new TbError(
|
|
480
|
+
"SESSION_WORKSPACE_MISMATCH",
|
|
481
|
+
`新建的会话落在 ${createdOrigin.cwd},而本项目工作区是 ${project.workspacePath} → 宿主未按工作区建会话(当前 DSH 实例的工作区与该项目不一致)。**主会话指针未被改写**。请改用「改绑到本工作区已有会话」;或在 ${project.workspacePath} 下另起一个 DSH 实例再来接续。`,
|
|
482
|
+
{ sessionId, cwd: createdOrigin.cwd, workspacePath: project.workspacePath, projectId: project.id },
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
const rb = store.rebindInitialSession(project.id, sessionId);
|
|
486
|
+
let openingDelivered = false; let deliveryReason = null;
|
|
487
|
+
if (typeof port.sendPrompt === "function") {
|
|
488
|
+
try { const r = await port.sendPrompt(sessionId, buildOpeningPrompt(rb.project)); openingDelivered = Boolean(r?.sent); deliveryReason = r?.reason ?? null; }
|
|
489
|
+
catch (error) { deliveryReason = error?.code ?? String(error?.message ?? error); }
|
|
490
|
+
}
|
|
491
|
+
const auditId = store.recordAudit({ actor: "board", action: "rebind-initial-session", target: project.id, allowed: true, reason: "rebind", detail: JSON.stringify({ before: rb.before, after: rb.after, openingDelivered, deliveryReason, titleApplied: created?.titleApplied ?? null, titleReason: created?.titleReason ?? null }) });
|
|
492
|
+
emit("project.updated", { projectId: project.id, initialSessionId: rb.after });
|
|
493
|
+
return { status: 200, payload: { rebound: true, mode: "create", projectId: project.id, before: rb.before, after: rb.after, openingDelivered, deliveryReason, titleApplied: created?.titleApplied ?? null, titleReason: created?.titleReason ?? null, sessionName: mainSessionName, auditId } };
|
|
494
|
+
}
|
|
495
|
+
// FR-84 补口(2026-10-23)· **任务级接续会话改指**。
|
|
496
|
+
// 病根:任务级 `session_id` 指向别的工作区(实测 `cwd="/"`)时,抽屉会一直报归属门,
|
|
497
|
+
// 而既有动作只有「重建并绑定项目主会话」——它只改**项目**指针,**改不动任务级引用** ⇒ 修不好。
|
|
498
|
+
// 本端点把这张任务的接续会话改指到**项目主会话**(或显式给出的会话),并且**先验工作区**:
|
|
499
|
+
// 目标会话归属不对就如实拒绝(不制造第二个错绑)。只改任务引用,不碰状态/认领锁。
|
|
500
|
+
const taskSessionRebindRoute = /^\/api\/tasks\/([^/]+)\/session\/rebind$/.exec(pathname);
|
|
501
|
+
if (taskSessionRebindRoute) {
|
|
502
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "session/rebind 仅支持 POST");
|
|
503
|
+
const task = store.requireTaskRef(decodeURIComponent(taskSessionRebindRoute[1]));
|
|
504
|
+
const confirmed = body.confirm === true || searchParams.get("confirm") === "1";
|
|
505
|
+
if (!confirmed) return { status: 200, payload: { rebound: false, reason: "confirm-required", identifier: task.identifier, current: task.sessionId ?? null } };
|
|
506
|
+
const project = store.getProject(task.projectId) ?? null;
|
|
507
|
+
const target = body.sessionId ?? searchParams.get("session") ?? project?.initialSessionId ?? null;
|
|
508
|
+
if (!target) {
|
|
509
|
+
throw new TbError("NO_PROJECT_MAIN_SESSION", "该项目还没有主会话可改指:请先「重建并绑定项目主会话」", { identifier: task.identifier, projectId: task.projectId });
|
|
510
|
+
}
|
|
511
|
+
const port = store.hostSessionPort;
|
|
512
|
+
if (port && typeof port.sessionExists === "function") {
|
|
513
|
+
const existsRes = await port.sessionExists(target);
|
|
514
|
+
if (existsRes?.exists === false) throw new TbError("SESSION_NOT_FOUND", "目标会话在本机不存在:不能改指", { sessionId: target });
|
|
515
|
+
}
|
|
516
|
+
const origin = await sessionOriginOf(target, project);
|
|
517
|
+
if (origin.mismatch === true) {
|
|
518
|
+
throw new TbError(
|
|
519
|
+
"SESSION_OTHER_WORKSPACE",
|
|
520
|
+
`目标会话属于另一个工作区:${origin.cwd}(本项目工作区 ${project?.workspacePath ?? "未知"})→ 拒绝改指;请先「重建并绑定项目主会话」,或选一个本项目工作区内的会话`,
|
|
521
|
+
{ sessionId: target, cwd: origin.cwd, workspacePath: project?.workspacePath ?? null },
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
const rb = store.rebindTaskSession(task.identifier, target);
|
|
525
|
+
const auditId = store.recordAudit({
|
|
526
|
+
actor: body.actor ?? "board", action: "rebind-task-session", target: rb.task.identifier, allowed: true,
|
|
527
|
+
reason: "project-main", detail: JSON.stringify({ before: rb.before, after: rb.after, cwd: origin.cwd, changed: rb.changed }),
|
|
528
|
+
});
|
|
529
|
+
store.recordTaskEvent(rb.task.id, { type: "session_rebound", actor: body.actor ?? "board", detail: `${rb.before ?? "(空)"} → ${rb.after}` });
|
|
530
|
+
emit("task.updated", { identifier: rb.task.identifier, sessionId: rb.after });
|
|
531
|
+
return { status: 200, payload: { rebound: true, identifier: rb.task.identifier, before: rb.before, after: rb.after, changed: rb.changed, origin, auditId } };
|
|
532
|
+
}
|
|
533
|
+
const projectSessionActionRoute = /^\/api\/projects\/([^/]+)\/sessions\/(request|approve)$/.exec(pathname);
|
|
534
|
+
if (projectSessionActionRoute) {
|
|
535
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "sessions 动作仅支持 POST");
|
|
536
|
+
const project = store.requireProject(decodeURIComponent(projectSessionActionRoute[1]));
|
|
537
|
+
const sessionId = body.sessionId ?? searchParams.get("session");
|
|
538
|
+
const result = projectSessionActionRoute[2] === "request"
|
|
539
|
+
? store.requestSessionAssociation(project.id, sessionId)
|
|
540
|
+
: store.approveSessionAssociation(project.id, sessionId);
|
|
541
|
+
return { status: 200, payload: result };
|
|
542
|
+
}
|
|
543
|
+
if (pathname === "/api/tasks") {
|
|
544
|
+
if (method === "GET") {
|
|
545
|
+
const tasks = store.listTasks({
|
|
546
|
+
projectId: searchParams.get("project") ?? undefined,
|
|
547
|
+
status: searchParams.get("status") ?? undefined,
|
|
548
|
+
priority: searchParams.get("priority") ?? undefined,
|
|
549
|
+
owner: searchParams.get("owner") ?? undefined,
|
|
550
|
+
labels: searchParams.get("label") ?? undefined,
|
|
551
|
+
// FR-26:会话归属维度(全部 / linked 已关联 / unlinked 未关联),与上面各维度取交集
|
|
552
|
+
sessionScope: searchParams.get("sessionScope") ?? undefined,
|
|
553
|
+
// FR-14:关键词搜索(编号 / 标题 / 描述 / 标签),与上面各维度取交集。
|
|
554
|
+
// `q` 为空串 ⇒ undefined ⇒ 不搜索(清空关键词即恢复全量);缺失同理。
|
|
555
|
+
q: searchParams.get("q") || undefined,
|
|
556
|
+
// FR-15:默认档=「默认顺序」(人工拖拽 / 创建顺序),`sort=priority` 才是优先级档。
|
|
557
|
+
// 此前这里缺省写死 `priority`,导致**看板永远按优先级排**、FR-11 的列内手工顺序再持久化也看不见
|
|
558
|
+
// (前端从不带 `sort`)—— 两档口径与 FR-15 条款相反。缺省改回默认档,与 `cli/tb.mjs` 的
|
|
559
|
+
// `options.sort ?? "created"` 同口径;显式 `sort=priority` 的调用方行为一字不变。
|
|
560
|
+
sort: searchParams.get("sort") ?? "created",
|
|
561
|
+
});
|
|
562
|
+
// FR-75/76:按需附带"执行看护"状态(停滞 / 待决策),供看板卡片标记使用。
|
|
563
|
+
if (searchParams.get("withWatchdog") === "1") {
|
|
564
|
+
// FR-79:卡片只带诊断**摘要**({count, kinds, highestSeverity}),完整列表走 /diagnostics。
|
|
565
|
+
const decorated = tasks.map((t) => {
|
|
566
|
+
const patch = {};
|
|
567
|
+
if (t.status === "in_progress") patch.watchdog = assessTaskRef(store, t.identifier);
|
|
568
|
+
if (t.status === "in_progress" || t.status === "blocked" || t.status === "in_review" || t.triageAt) {
|
|
569
|
+
patch.diagnostics = evaluateTaskDiagnostics(store, t).summary;
|
|
570
|
+
}
|
|
571
|
+
return Object.keys(patch).length ? { ...t, ...patch } : t;
|
|
572
|
+
});
|
|
573
|
+
return { status: 200, payload: { tasks: decorated, count: decorated.length } };
|
|
574
|
+
}
|
|
575
|
+
return { status: 200, payload: { tasks, count: tasks.length } };
|
|
576
|
+
}
|
|
577
|
+
if (method === "POST") {
|
|
578
|
+
const task = store.createTask({
|
|
579
|
+
projectId: body.projectId,
|
|
580
|
+
title: body.title,
|
|
581
|
+
description: body.description,
|
|
582
|
+
// FR-94:添加任务时即记录「完成验收标准 + 复核动作」(真机反馈:便于快速复核)
|
|
583
|
+
acceptance: body.acceptance,
|
|
584
|
+
verifyCommand: body.verifyCommand,
|
|
585
|
+
status: body.status,
|
|
586
|
+
priority: body.priority,
|
|
587
|
+
labels: body.labels ?? [],
|
|
588
|
+
owner: body.owner,
|
|
589
|
+
// P0:归因在**建卡事务内**完成。旧口径是「先建卡、再 POST /attribution」两步 ——
|
|
590
|
+
// 中间任何失败都留一张无归因卡(2026-10-28 修 69 张,其中 56 张来源已不可考)。
|
|
591
|
+
requirementId: body.requirementId ?? body.requirement,
|
|
592
|
+
unattributedReason: body.unattributedReason,
|
|
593
|
+
});
|
|
594
|
+
// 未归因时必须**可见**:返回体带 `attribution.warning`(CLI 侧走 stderr,Web 侧画黄条)。
|
|
595
|
+
// 不写成错误是因为严格拒绝要等 P3(见 store.mjs 的 strictAttribution 注释)。
|
|
596
|
+
const attribution = task.requirementId
|
|
597
|
+
? { attributed: true, requirementId: task.requirementId, warning: null }
|
|
598
|
+
: {
|
|
599
|
+
attributed: false,
|
|
600
|
+
requirementId: null,
|
|
601
|
+
warning:
|
|
602
|
+
"该任务未归属需求条目:启动执行/派发团队会被归因门拒绝(EXECUTION_NOT_ATTRIBUTED)。补归因:POST /api/tasks/<ref>/attribution,或建卡时带 requirement;确实不需要归属请带 unattributedReason。",
|
|
603
|
+
};
|
|
604
|
+
return { status: 201, payload: { task, attribution } };
|
|
605
|
+
}
|
|
606
|
+
throw new TbError("USAGE_ERROR", "/api/tasks 仅支持 GET 或 POST");
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// 会话存活(FR-84):打开会话/接续前的探活;`exists:null` = 判不准(不得当作失效)。
|
|
610
|
+
const sessionStateRoute = /^\/api\/sessions\/([^/]+)\/state$/.exec(pathname);
|
|
611
|
+
if (sessionStateRoute) {
|
|
612
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "sessions state 仅支持 GET");
|
|
613
|
+
return { status: 200, payload: await sessionStateOf(decodeURIComponent(sessionStateRoute[1])) };
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const taskRoute = /^\/api\/tasks\/([^/]+)$/.exec(pathname);
|
|
617
|
+
if (taskRoute) {
|
|
618
|
+
let ref;
|
|
619
|
+
try {
|
|
620
|
+
ref = decodeURIComponent(taskRoute[1]);
|
|
621
|
+
} catch {
|
|
622
|
+
throw new TbError("INVALID_ID", "任务引用包含非法编码");
|
|
623
|
+
}
|
|
624
|
+
if (method === "GET") {
|
|
625
|
+
const task = store.requireTaskRef(ref);
|
|
626
|
+
// FR-90:详情里直接带上「评审证据包」(自动复核结论 + 最近一条进展评论),
|
|
627
|
+
// 评审人打开抽屉即可看到机器结论,而不是只看到两个按钮。
|
|
628
|
+
const comments = store.listComments(task.id);
|
|
629
|
+
return { status: 200, payload: { task, comments, reviewEvidence: buildReviewEvidence({ comments }) } };
|
|
630
|
+
}
|
|
631
|
+
if (method === "PATCH") {
|
|
632
|
+
const task = store.updateTask(ref, {
|
|
633
|
+
expectedVersion: body.version ?? body.expectedVersion,
|
|
634
|
+
title: body.title,
|
|
635
|
+
description: body.description,
|
|
636
|
+
acceptance: body.acceptance,
|
|
637
|
+
verifyCommand: body.verifyCommand,
|
|
638
|
+
status: body.status,
|
|
639
|
+
priority: body.priority,
|
|
640
|
+
labels: body.labels,
|
|
641
|
+
owner: body.owner,
|
|
642
|
+
// FR-11:拖拽落点。三形态:`{before: <编号>}` 锚点(前端用,筛选下唯一正确)、整数下标、`null` = 列尾。
|
|
643
|
+
// **走同一条 PATCH**:评审门 / 授权门 / 归因门 / 人工校验门 / 治理门都在 store.updateTask 里,
|
|
644
|
+
// 拖拽因此与「上一列 / 下一列」按钮**完全同门**,不存在任何旁路。
|
|
645
|
+
// 与筛选共存口径:`boardPosition` 只定**持久顺序**,不因筛选改变;筛选只影响此刻可见集,
|
|
646
|
+
// 前端把落点按"可见邻居"折成锚点提交 ⇒ 隐藏卡在整列里的相对位置不受影响(详见 store.resolveBoardOrder)。
|
|
647
|
+
boardPosition: body.boardPosition,
|
|
648
|
+
// FR-83 补口(卡 `-162`):**显式跳过评审**的逃生口。只有前端在人确认「将跳过评审」时才带 true;
|
|
649
|
+
// 漏带/带字符串一律按"没批准"处理(store 侧严格 `=== true`)⇒ 拖拽/脚本的静默收口必然被拒。
|
|
650
|
+
skipReview: body.skipReview,
|
|
651
|
+
});
|
|
652
|
+
return { status: 200, payload: { task } };
|
|
653
|
+
}
|
|
654
|
+
if (method === "DELETE") {
|
|
655
|
+
const versionParam = searchParams.get("version");
|
|
656
|
+
const expectedVersion = versionParam !== null ? Number(versionParam) : body.version ?? body.expectedVersion;
|
|
657
|
+
const deleted = store.deleteTask(ref, { expectedVersion });
|
|
658
|
+
return { status: 200, payload: { deleted } };
|
|
659
|
+
}
|
|
660
|
+
throw new TbError("USAGE_ERROR", `任务路由不支持 ${method}`);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
// ---- 需求文档(FR-34) ----
|
|
665
|
+
if (pathname === "/api/requirements/docs") {
|
|
666
|
+
if (method === "GET") {
|
|
667
|
+
const docs = store.listRequirementDocs({ projectId: searchParams.get("project") ?? undefined });
|
|
668
|
+
return { status: 200, payload: { docs, count: docs.length } };
|
|
669
|
+
}
|
|
670
|
+
if (method === "POST") {
|
|
671
|
+
const existed = store.getRequirementDoc(body.projectId) ?? null;
|
|
672
|
+
const doc = existed ?? store.ensureRequirementDoc(body.projectId, { body: body.body ?? "" });
|
|
673
|
+
// FR-91 修复(真机已发生的数据损坏):对**已存在**的文档,只有显式传**非空** body 才覆盖。
|
|
674
|
+
// 此前 UI 的「新建文档」会带 `body: ""`,而 `body.body !== undefined` ⇒ 走 update ⇒ **把已有正文清空**
|
|
675
|
+
// (本项目需求文档正是这样被清成 0 字节、版本却涨到 v7 的)。幂等即可,不拿空串当"编辑"。
|
|
676
|
+
const shouldWrite = typeof body.body === "string" && body.body !== "" && body.body !== doc.body;
|
|
677
|
+
const updated = shouldWrite ? store.updateRequirementDoc(doc.id, { expectedVersion: doc.version, body: body.body }) : doc;
|
|
678
|
+
return { status: 201, payload: { doc: updated, existed: Boolean(existed), wrote: shouldWrite } };
|
|
679
|
+
}
|
|
680
|
+
throw new TbError("USAGE_ERROR", "/api/requirements/docs 仅支持 GET 或 POST");
|
|
681
|
+
}
|
|
682
|
+
const reqDocRoute = /^\/api\/requirements\/docs\/([^/]+)$/.exec(pathname);
|
|
683
|
+
if (reqDocRoute) {
|
|
684
|
+
const ref = decodeURIComponent(reqDocRoute[1]);
|
|
685
|
+
if (method === "GET") {
|
|
686
|
+
const doc = store.getRequirementDocById(ref) ?? store.getRequirementDoc(ref);
|
|
687
|
+
if (!doc) throw new TbError("REQUIREMENT_DOC_NOT_FOUND", `需求文档不存在:${ref}`, { ref });
|
|
688
|
+
return { status: 200, payload: { doc, items: store.listRequirementItems({ docId: doc.id }) } };
|
|
689
|
+
}
|
|
690
|
+
if (method === "PATCH") {
|
|
691
|
+
const doc = store.updateRequirementDoc(ref, { expectedVersion: body.version ?? body.expectedVersion, body: body.body });
|
|
692
|
+
return { status: 200, payload: { doc } };
|
|
693
|
+
}
|
|
694
|
+
throw new TbError("USAGE_ERROR", `需求文档路由不支持 ${method}`);
|
|
695
|
+
}
|
|
696
|
+
const reqElaborateRoute = /^\/api\/requirements\/docs\/([^/]+)\/elaborate$/.exec(pathname);
|
|
697
|
+
if (reqElaborateRoute) {
|
|
698
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "elaborate 仅支持 POST");
|
|
699
|
+
const ref = decodeURIComponent(reqElaborateRoute[1]);
|
|
700
|
+
const doc = store.getRequirementDocById(ref) ?? store.getRequirementDoc(ref);
|
|
701
|
+
if (!doc) throw new TbError("REQUIREMENT_DOC_NOT_FOUND", `需求文档不存在:${ref}`, { ref });
|
|
702
|
+
const mode = body.mode ?? "auto";
|
|
703
|
+
const runRule = () => ({ ...store.elaborateRequirementDoc(doc.id), mode: "rule" });
|
|
704
|
+
const runAi = async () => {
|
|
705
|
+
if (typeof aiElaborator !== "function") throw new TbError("AI_UNAVAILABLE", "AI 条目化不可用(当前环境未提供 LLM 直连)");
|
|
706
|
+
const candidates = await aiElaborator(doc);
|
|
707
|
+
return { ...store.addRequirementCandidates(doc.id, candidates, { source: "elaborated-ai" }), mode: "ai" };
|
|
708
|
+
};
|
|
709
|
+
if (mode === "rule") return { status: 201, payload: runRule() };
|
|
710
|
+
if (mode === "ai") return { status: 201, payload: await runAi() };
|
|
711
|
+
if (mode !== "auto") throw new TbError("USAGE_ERROR", `elaborate mode 必须是 auto/ai/rule,收到:${mode}`);
|
|
712
|
+
if (typeof aiElaborator === "function") {
|
|
713
|
+
try { return { status: 201, payload: await runAi() }; }
|
|
714
|
+
catch (error) {
|
|
715
|
+
return { status: 201, payload: { ...runRule(), degraded: true, aiError: error?.code ?? String(error?.message ?? error) } };
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
// B-1:无 AI 时显式标注降级,避免用户误以为用了 AI
|
|
719
|
+
return { status: 201, payload: { ...runRule(), degraded: true, aiError: "AI_UNAVAILABLE" } };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// ---- 需求条目(FR-35) ----
|
|
723
|
+
if (pathname === "/api/requirements/items") {
|
|
724
|
+
if (method === "GET") {
|
|
725
|
+
const items = store.listRequirementItems({
|
|
726
|
+
projectId: searchParams.get("project") ?? undefined,
|
|
727
|
+
docId: searchParams.get("doc") ?? undefined,
|
|
728
|
+
status: searchParams.get("status") ?? undefined,
|
|
729
|
+
});
|
|
730
|
+
return { status: 200, payload: { items, count: items.length } };
|
|
731
|
+
}
|
|
732
|
+
if (method === "POST") {
|
|
733
|
+
const item = store.createRequirementItem({
|
|
734
|
+
projectId: body.projectId, title: body.title, description: body.description,
|
|
735
|
+
acceptance: body.acceptance, priority: body.priority, docId: body.docId,
|
|
736
|
+
});
|
|
737
|
+
return { status: 201, payload: { item } };
|
|
738
|
+
}
|
|
739
|
+
throw new TbError("USAGE_ERROR", "/api/requirements/items 仅支持 GET 或 POST");
|
|
740
|
+
}
|
|
741
|
+
const reqItemRoute = /^\/api\/requirements\/items\/([^/]+)$/.exec(pathname);
|
|
742
|
+
if (reqItemRoute) {
|
|
743
|
+
const ref = decodeURIComponent(reqItemRoute[1]);
|
|
744
|
+
if (method === "GET") {
|
|
745
|
+
// FR-91:详情必须带上**关联任务的完成情况**(真机反馈「展示关联需求的任务完成列表情况,以供
|
|
746
|
+
// 自动/人工评审需求是否完成」)。`completion` 只读、不改状态;终态仍由人点。
|
|
747
|
+
const item = store.requireRequirementItemRef(ref);
|
|
748
|
+
return { status: 200, payload: { item, completion: store.requirementCompletion(item.id) } };
|
|
749
|
+
}
|
|
750
|
+
if (method === "PATCH") {
|
|
751
|
+
const item = store.updateRequirementItem(ref, {
|
|
752
|
+
status: body.status, title: body.title, description: body.description,
|
|
753
|
+
acceptance: body.acceptance, priority: body.priority, docId: body.docId,
|
|
754
|
+
});
|
|
755
|
+
// 需求终态(done/closed)落审计:谁在什么时候把哪条需求收口的(自动只给建议,终态由人定)。
|
|
756
|
+
if (body.status === "done" || body.status === "closed" || item.status === "done" || item.status === "closed") {
|
|
757
|
+
try { store.recordAudit({ actor: body.actor ?? "human", action: "requirement-status", target: item.identifier, allowed: true, reason: String(body.status ?? item.status), detail: body.reason ?? null }); } catch { /* ignore */ }
|
|
758
|
+
}
|
|
759
|
+
return { status: 200, payload: { item } };
|
|
760
|
+
}
|
|
761
|
+
if (method === "DELETE") {
|
|
762
|
+
return { status: 200, payload: store.deleteRequirementItem(ref) };
|
|
763
|
+
}
|
|
764
|
+
throw new TbError("USAGE_ERROR", `需求条目路由不支持 ${method}`);
|
|
765
|
+
}
|
|
766
|
+
const reqFeasibilityRoute = /^\/api\/requirements\/items\/([^/]+)\/feasibility$/.exec(pathname);
|
|
767
|
+
if (reqFeasibilityRoute) {
|
|
768
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "feasibility 仅支持 POST");
|
|
769
|
+
const ref = decodeURIComponent(reqFeasibilityRoute[1]);
|
|
770
|
+
const item = store.setRequirementFeasibility(ref, { verdict: body.verdict, reason: body.reason, by: body.by, override: body.override });
|
|
771
|
+
return { status: 200, payload: { item } };
|
|
772
|
+
}
|
|
773
|
+
const reqSplitRoute = /^\/api\/requirements\/items\/([^/]+)\/split$/.exec(pathname);
|
|
774
|
+
if (reqSplitRoute) {
|
|
775
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "split 仅支持 POST");
|
|
776
|
+
const ref = decodeURIComponent(reqSplitRoute[1]);
|
|
777
|
+
// B-3:可行性门——不可行条目不得分拆
|
|
778
|
+
const item = store.requireRequirementItemRef(ref);
|
|
779
|
+
if (item.feasibility === "infeasible") throw new TbError("FEASIBILITY_INFEASIBLE", "条目标记为不可行,不得分拆技术任务", { ref });
|
|
780
|
+
const result = store.splitRequirement(ref, { tasks: body.tasks });
|
|
781
|
+
return { status: 201, payload: result };
|
|
782
|
+
}
|
|
783
|
+
// 2026-10-28 真机批注:「生成看板任务(分拆)」此前**只有人工 textarea**,没有"自动生成"也没有修订回路。
|
|
784
|
+
// 人拍口径 = **方案 C:走项目主会话** —— 不新增第二条 LLM 通道,把「先出草稿」交给项目主会话里的 agent
|
|
785
|
+
// (它本就有仓库上下文与 `taskboard_*` 工具)。本端点**只投递一条指令**:
|
|
786
|
+
// **不建卡、不改条目状态、不写评论**,唯一落盘是治理审计(`requirement-split-ask`)。
|
|
787
|
+
// 因此它可以安全地反复点("按意见重生成"=再投一次,带上上一版草稿与意见)。
|
|
788
|
+
const reqSplitAskRoute = /^\/api\/requirements\/items\/([^/]+)\/split-ask$/.exec(pathname);
|
|
789
|
+
if (reqSplitAskRoute) {
|
|
790
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "split-ask 仅支持 POST");
|
|
791
|
+
const item = store.requireRequirementItemRef(decodeURIComponent(reqSplitAskRoute[1]));
|
|
792
|
+
// 与 split 同门:不可行条目连草稿都不出(避免"先拆一堆再告诉你不可行")。
|
|
793
|
+
if (item.feasibility === "infeasible") throw new TbError("FEASIBILITY_INFEASIBLE", "条目标记为不可行,不得分拆技术任务", { ref: item.identifier });
|
|
794
|
+
const project = store.requireProject(item.projectId);
|
|
795
|
+
// 会话解析**复用** diagnostics 的三级回落(任务级 → 项目主会话 → 已绑定会话),
|
|
796
|
+
// 条目没有任务级会话,故传 sessionId:null 走后两级。
|
|
797
|
+
const resolved = resolveSessionRef(store, { projectId: item.projectId, sessionId: null });
|
|
798
|
+
const sid = resolved.sessionId ?? null;
|
|
799
|
+
if (!sid) {
|
|
800
|
+
return { status: 200, payload: { delivered: false, sessionId: null, source: null, reason: "no-session", nextAction: "先在项目里重建并绑定主会话" } };
|
|
801
|
+
}
|
|
802
|
+
const liveness = await sessionStateOf(sid);
|
|
803
|
+
if (liveness.exists === false) {
|
|
804
|
+
return { status: 200, payload: { delivered: false, sessionId: sid, source: resolved.source, reason: "session-gone", stale: true, liveness, nextAction: "重建并绑定项目主会话" } };
|
|
805
|
+
}
|
|
806
|
+
const prompt = buildSplitAskPrompt({
|
|
807
|
+
item, project,
|
|
808
|
+
feedback: body?.feedback ?? null,
|
|
809
|
+
previous: Array.isArray(body?.previous) ? body.previous : null,
|
|
810
|
+
maxTasks: body?.maxTasks,
|
|
811
|
+
});
|
|
812
|
+
// 能力判定放在**构建之后**:`host-unavailable` 不是"这个请求有问题",而是"这个实例没有宿主"——
|
|
813
|
+
// 此时把 prompt 一并回带,人至少能自己粘到会话里(真机 2026-10-29:`:47830` 独立进程上
|
|
814
|
+
// 只会得到一句「未能投递:host-unavailable · 检查宿主会话通道后重试」,而重试永远不会成立)。
|
|
815
|
+
const port = store.hostSessionPort;
|
|
816
|
+
if (!port || typeof port.sendPrompt !== "function") {
|
|
817
|
+
return { status: 200, payload: { delivered: false, sessionId: sid, source: resolved.source, reason: "host-unavailable", hostCapabilities: null, nextAction: HOST_UNAVAILABLE_NEXT, prompt } };
|
|
818
|
+
}
|
|
819
|
+
let result = null;
|
|
820
|
+
try { result = await port.sendPrompt(sid, prompt); }
|
|
821
|
+
catch (error) {
|
|
822
|
+
const reason = error?.code ?? String(error?.message ?? error);
|
|
823
|
+
try { store.recordAudit({ actor: "board", action: "requirement-split-ask", target: item.identifier, allowed: false, reason, detail: `投递失败 session=${sid}` }); } catch { /* ignore */ }
|
|
824
|
+
return { status: 200, payload: { delivered: false, sessionId: sid, source: resolved.source, reason, nextAction: "查看主会话状态后重试" } };
|
|
825
|
+
}
|
|
826
|
+
const delivered = Boolean(result?.sent ?? result?.delivered ?? false);
|
|
827
|
+
const reason2 = result?.reason ?? null;
|
|
828
|
+
try {
|
|
829
|
+
store.recordAudit({ actor: "board", action: "requirement-split-ask", target: item.identifier, allowed: true, reason: reason2 ?? "delivered", detail: `session=${sid} source=${resolved.source ?? "null"} feedback=${body?.feedback ? "yes" : "no"} previous=${Array.isArray(body?.previous) ? body.previous.length : 0}` });
|
|
830
|
+
} catch { /* ignore */ }
|
|
831
|
+
return { status: 200, payload: { delivered, sessionId: sid, source: resolved.source, reason: reason2, stale: false, liveness, prompt } };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const reqGraphRoute = /^\/api\/requirements\/items\/([^/]+)\/graph$/.exec(pathname);
|
|
835
|
+
if (reqGraphRoute) {
|
|
836
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "graph 仅支持 GET");
|
|
837
|
+
return { status: 200, payload: store.requirementTaskGraph(decodeURIComponent(reqGraphRoute[1])) };
|
|
838
|
+
}
|
|
839
|
+
// FR-91:只读的「需求完成度」端点(关联任务清单 + 汇总结论),供自动/人工评审复用。
|
|
840
|
+
const reqCompletionRoute = /^\/api\/requirements\/items\/([^/]+)\/completion$/.exec(pathname);
|
|
841
|
+
if (reqCompletionRoute) {
|
|
842
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "completion 仅支持 GET");
|
|
843
|
+
return { status: 200, payload: store.requirementCompletion(decodeURIComponent(reqCompletionRoute[1])) };
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// ---- 条目化候选(FR-36) ----
|
|
847
|
+
if (pathname === "/api/requirements/candidates") {
|
|
848
|
+
if (method === "DELETE") {
|
|
849
|
+
const ids = Array.isArray(body.ids) ? body.ids : null;
|
|
850
|
+
const removed = store.deleteRequirementCandidates({ ids, docId: body.docId ?? searchParams.get("doc") ?? undefined, status: body.status ?? searchParams.get("status") ?? undefined });
|
|
851
|
+
return { status: 200, payload: removed };
|
|
852
|
+
}
|
|
853
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "candidates 仅支持 GET 或 DELETE");
|
|
854
|
+
const candidates = store.listRequirementCandidates({ docId: searchParams.get("doc") ?? undefined, status: searchParams.get("status") ?? undefined });
|
|
855
|
+
return { status: 200, payload: { candidates, count: candidates.length } };
|
|
856
|
+
}
|
|
857
|
+
if (pathname === "/api/requirements/candidates/confirm") {
|
|
858
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "confirm 仅支持 POST");
|
|
859
|
+
return { status: 201, payload: store.confirmRequirementCandidates(body.ids) };
|
|
860
|
+
}
|
|
861
|
+
if (pathname === "/api/requirements/candidates/reject") {
|
|
862
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "reject 仅支持 POST");
|
|
863
|
+
return { status: 200, payload: store.rejectRequirementCandidates(body.ids) };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// ---- 任务依赖(FR-39) ----
|
|
867
|
+
// ---- 执行(FR-40 启动 / FR-41 跟踪与失败) ----
|
|
868
|
+
/* FR-40 补口(2026-10-19 真机):**归因的写入口**。
|
|
869
|
+
归因门(store.assertAttributed)只拦「启动执行 / 派发团队」,不该拦「把任务归回需求条目」本身 ——
|
|
870
|
+
但此前全链路**没有任何**归因写入口:真机上点「启动执行」只得到「请先关联需求条目(归因门)」,
|
|
871
|
+
而任务编辑对话框没有需求条目字段、也没有对应端点,用户无处可点(真机报障)。
|
|
872
|
+
这里补一个最小写入口:把一条已存在的任务关联到需求条目;跨项目由 store 层拒绝。 */
|
|
873
|
+
const taskAttributionRoute = /^\/api\/tasks\/([^/]+)\/attribution$/.exec(pathname);
|
|
874
|
+
if (taskAttributionRoute) {
|
|
875
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "attribution 仅支持 POST");
|
|
876
|
+
const ref = decodeURIComponent(taskAttributionRoute[1]);
|
|
877
|
+
const requirement = body.requirement ?? body.requirementId ?? null;
|
|
878
|
+
if (!requirement) throw new TbError("USAGE_ERROR", "attribution 需要 requirement(需求条目 identifier 或 id)");
|
|
879
|
+
const task = store.associateRequirementTask(requirement, ref);
|
|
880
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
881
|
+
return { status: 200, payload: { task, requirement: requirement } };
|
|
882
|
+
}
|
|
883
|
+
const taskExecRoute = /^\/api\/tasks\/([^/]+)\/execute$/.exec(pathname);
|
|
884
|
+
if (taskExecRoute) {
|
|
885
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "execute 仅支持 POST");
|
|
886
|
+
const ref = decodeURIComponent(taskExecRoute[1]);
|
|
887
|
+
// 防重复下发:已有执行会话仍在执行且未返回结论 → 409 + 明确提醒(不新建/不覆盖)。
|
|
888
|
+
const execTask = store.requireTaskRef(ref);
|
|
889
|
+
const execInflight = inflightOf(execTask);
|
|
890
|
+
if (execInflight) throw inflightError(execTask, execInflight);
|
|
891
|
+
// FR-78:失败熔断 / 配额鉴权 / 近期成功窗口 → 不自动重试(人工可先「重置失败计数」)
|
|
892
|
+
const execGuard = store.dispatchGuard(execTask);
|
|
893
|
+
if (execGuard) {
|
|
894
|
+
throw new TbError("EXECUTION_CIRCUIT_OPEN", circuitMessage(execGuard, execTask), {
|
|
895
|
+
identifier: execTask.identifier, reason: execGuard,
|
|
896
|
+
failures: execTask.consecutiveFailures, limit: execTask.maxRetries ?? DEFAULT_FAILURE_LIMIT,
|
|
897
|
+
lastFailureError: execTask.lastFailureError ?? null,
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
const port = store.hostSessionPort;
|
|
901
|
+
let sessionId = body.sessionId ?? null;
|
|
902
|
+
let presetApplied = null;
|
|
903
|
+
let titleApplied = null;
|
|
904
|
+
let titleReason = null;
|
|
905
|
+
let sessionName = null;
|
|
906
|
+
let reason = null;
|
|
907
|
+
// 真机 2026-10-22(续四十一):**先过门,再建会话**。
|
|
908
|
+
// 原先顺序是「建会话 + 打开会话(切主视图)→ 再在 startTaskExecution 里判门」,
|
|
909
|
+
// 于是被归因门 / 授权门 / 人工校验门拒绝的点击**照样留下副作用**(多一个空会话 + 视图被切走)。
|
|
910
|
+
// 门序列的唯一来源仍是 store.assertExecutable(startTaskExecution 会再复检一次)。
|
|
911
|
+
store.assertExecutable(ref);
|
|
912
|
+
// 宿主路径:可用则建会话(+尝试预置)并打开;不可用则降级(保留 directive 兜底)。
|
|
913
|
+
if (!sessionId && port?.available) {
|
|
914
|
+
try {
|
|
915
|
+
const preset = `任务 ${execTask.identifier}:${execTask.title}\n操作指引:认领 → 执行 → 提交"待验收";不得置"完成"(人工确认)。`;
|
|
916
|
+
// 2026-10-23 用户命名约束(口径 1):任务会话统一「【任务】+ 任务标题 + 时间」。
|
|
917
|
+
// 同时补 `cwd`(本仓旧缺漏):不传 cwd 时宿主把会话落在**进程目录**(真机取证到 `cwd="/"`),
|
|
918
|
+
// 正是「接续会话跨工作区错乱」的一个来源。
|
|
919
|
+
// FR-95 补口(2026-10-26):名字算一次、回包带上,前端据此如实显示命名结果。
|
|
920
|
+
sessionName = taskSessionTitle(execTask.title);
|
|
921
|
+
const created = await port.createSession({
|
|
922
|
+
preset,
|
|
923
|
+
cwd: store.getProject(execTask.projectId)?.workspacePath ?? undefined,
|
|
924
|
+
title: sessionName,
|
|
925
|
+
});
|
|
926
|
+
if (created?.sessionId) {
|
|
927
|
+
sessionId = created.sessionId;
|
|
928
|
+
presetApplied = Boolean(created.presetApplied);
|
|
929
|
+
titleApplied = created.titleApplied ?? null;
|
|
930
|
+
titleReason = created.titleReason ?? null;
|
|
931
|
+
await port.openSession(sessionId);
|
|
932
|
+
} else {
|
|
933
|
+
reason = "session-create-failed";
|
|
934
|
+
}
|
|
935
|
+
} catch (error) {
|
|
936
|
+
reason = error?.code ?? String(error?.message ?? error);
|
|
937
|
+
}
|
|
938
|
+
} else if (!sessionId) {
|
|
939
|
+
reason = "host-session-unavailable";
|
|
940
|
+
}
|
|
941
|
+
const result = store.startTaskExecution(ref, { sessionId });
|
|
942
|
+
result.launch.presetApplied = presetApplied;
|
|
943
|
+
result.launch.titleApplied = titleApplied;
|
|
944
|
+
if (titleApplied === false) result.launch.titleReason = titleReason;
|
|
945
|
+
result.launch.sessionName = sessionName;
|
|
946
|
+
if (!sessionId) result.launch.reason = reason ?? "host-session-unavailable";
|
|
947
|
+
emit("task.updated", { taskId: result.task.id, identifier: result.task.identifier, status: result.task.status });
|
|
948
|
+
return { status: 200, payload: result };
|
|
949
|
+
}
|
|
950
|
+
const taskExecGetRoute = /^\/api\/tasks\/([^/]+)\/execution$/.exec(pathname);
|
|
951
|
+
if (taskExecGetRoute) {
|
|
952
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "execution 仅支持 GET");
|
|
953
|
+
const ref = decodeURIComponent(taskExecGetRoute[1]);
|
|
954
|
+
// FR-75/76:附带执行看护评估(停滞 / 待决策 / 执行中)+ 可跟进的"下一步建议"。
|
|
955
|
+
// FR-77:附带认领/心跳状态(在途判定的一等公民)。
|
|
956
|
+
// FR-79:附带完整诊断列表(详情抽屉一次请求取回)。
|
|
957
|
+
const diag = evaluateTaskDiagnostics(store, ref);
|
|
958
|
+
// FR-82:附带尝试记录(按尝试看每次的结论与证据)
|
|
959
|
+
// FR-84:附带**会话引用解析结果**(三级回落 + 存活三态),前端据此渲染接续徽标、
|
|
960
|
+
// 并把「打开执行会话」换成「重建并绑定项目主会话」(无引用时)。
|
|
961
|
+
const proj = store.getProject(diag.task.projectId) ?? null;
|
|
962
|
+
const sref = resolveSessionRef(store, diag.task);
|
|
963
|
+
const sessionRef = {
|
|
964
|
+
...sref,
|
|
965
|
+
liveness: sref.sessionId ? await sessionStateOf(sref.sessionId) : null,
|
|
966
|
+
origin: sref.sessionId ? await sessionOriginOf(sref.sessionId, proj) : null,
|
|
967
|
+
};
|
|
968
|
+
// FR-84 补口(2026-10-23):任务级引用**落在别的工作区**时,单说「请用重建并绑定项目主会话」是**无效指引**
|
|
969
|
+
// ——重建只改项目主会话指针,动不到 `tasks.session_id`。故这里把「项目主会话此刻可不可用、工作区对不对」
|
|
970
|
+
// 一并算好交给前端,让抽屉能给出**真正生效**的那一个动作。
|
|
971
|
+
if (sessionRef.origin?.mismatch === true) {
|
|
972
|
+
const mainId = proj?.initialSessionId ?? null;
|
|
973
|
+
sessionRef.projectMain = mainId
|
|
974
|
+
? { sessionId: mainId, liveness: await sessionStateOf(mainId), origin: await sessionOriginOf(mainId, proj) }
|
|
975
|
+
: null;
|
|
976
|
+
}
|
|
977
|
+
return { status: 200, payload: { ...store.getTaskExecution(ref), claim: store.taskClaimState(ref), watchdog: assessTaskRef(store, ref), diagnostics: diag.diagnostics, diagnosticSummary: diag.summary, runs: store.listTaskRuns(ref), sessionRef } };
|
|
978
|
+
}
|
|
979
|
+
// FR-82:尝试记录(每次认领执行一条:状态/结果/摘要/错误/起止/心跳/运行时上限)
|
|
980
|
+
const taskRunsRoute = /^\/api\/tasks\/([^/]+)\/runs$/.exec(pathname);
|
|
981
|
+
if (taskRunsRoute) {
|
|
982
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "runs 仅支持 GET");
|
|
983
|
+
const task = store.requireTaskRef(decodeURIComponent(taskRunsRoute[1]));
|
|
984
|
+
const runs = store.listTaskRuns(task);
|
|
985
|
+
return { status: 200, payload: { identifier: task.identifier, count: runs.length, currentRun: store.getCurrentRun(task), runs } };
|
|
986
|
+
}
|
|
987
|
+
// FR-82:任务事件流(追加式;`since` = 已见游标,返回增量)
|
|
988
|
+
const taskEventsRoute = /^\/api\/tasks\/([^/]+)\/events$/.exec(pathname);
|
|
989
|
+
if (taskEventsRoute) {
|
|
990
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "events 仅支持 GET");
|
|
991
|
+
const task = store.requireTaskRef(decodeURIComponent(taskEventsRoute[1]));
|
|
992
|
+
const since = Number(searchParams.get("since") ?? 0) || 0;
|
|
993
|
+
const limit = Number(searchParams.get("limit") ?? 200) || 200;
|
|
994
|
+
const order = searchParams.get("order") ?? "desc";
|
|
995
|
+
const events = store.listTaskEvents(task, { since, limit, order });
|
|
996
|
+
return { status: 200, payload: { identifier: task.identifier, since, count: events.length, cursor: events.reduce((acc, e) => Math.max(acc, e.cursor), since), events } };
|
|
997
|
+
}
|
|
998
|
+
// FR-79:单任务诊断(完整列表 + 摘要 + 自动消解记录)
|
|
999
|
+
const taskDiagnosticsRoute = /^\/api\/tasks\/([^/]+)\/diagnostics$/.exec(pathname);
|
|
1000
|
+
if (taskDiagnosticsRoute) {
|
|
1001
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "diagnostics 仅支持 GET");
|
|
1002
|
+
const ref = decodeURIComponent(taskDiagnosticsRoute[1]);
|
|
1003
|
+
const task = store.requireTaskRef(ref);
|
|
1004
|
+
const r = evaluateTaskDiagnostics(store, task);
|
|
1005
|
+
const history = searchParams.get("history") === "1" ? store.listTaskDiagnostics(task, { includeResolved: true }) : undefined;
|
|
1006
|
+
return {
|
|
1007
|
+
status: 200,
|
|
1008
|
+
payload: {
|
|
1009
|
+
identifier: task.identifier, title: task.title, status: task.status,
|
|
1010
|
+
count: r.diagnostics.length, summary: r.summary, diagnostics: r.diagnostics,
|
|
1011
|
+
resolved: r.resolved, ...(history ? { history } : {}),
|
|
1012
|
+
},
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
// FR-79 / FR-76:人工忽略一条诊断(写忽略留痕 → 规则侧停止产出,直到出现更新的进展)
|
|
1016
|
+
const taskDiagnosticDismissRoute = /^\/api\/tasks\/([^/]+)\/diagnostics\/dismiss$/.exec(pathname);
|
|
1017
|
+
if (taskDiagnosticDismissRoute) {
|
|
1018
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "diagnostics/dismiss 仅支持 POST");
|
|
1019
|
+
const ref = decodeURIComponent(taskDiagnosticDismissRoute[1]);
|
|
1020
|
+
const kind = String(body.kind ?? "").trim();
|
|
1021
|
+
if (!kind) throw invalidField("kind", "需要提供 kind(诊断类型)");
|
|
1022
|
+
if (!DIAGNOSTIC_KINDS.includes(kind)) throw invalidField("kind", `kind 必须是 ${DIAGNOSTIC_KINDS.join(" / ")} 之一`);
|
|
1023
|
+
const r = store.dismissTaskDiagnostic(ref, kind, { actor: body.actor ?? "human", note: body.note ?? null });
|
|
1024
|
+
const task = store.getTaskById(store.requireTaskRef(ref).id);
|
|
1025
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1026
|
+
const after = evaluateTaskDiagnostics(store, task);
|
|
1027
|
+
return { status: 200, payload: { ...r, summary: summarizeDiagnostics(after.diagnostics), diagnostics: after.diagnostics } };
|
|
1028
|
+
}
|
|
1029
|
+
// FR-80:人工兜底队列(同因重复阻断已升级的任务)
|
|
1030
|
+
const projectTriageRoute = /^\/api\/projects\/([^/]+)\/triage$/.exec(pathname);
|
|
1031
|
+
if (projectTriageRoute) {
|
|
1032
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "triage 仅支持 GET");
|
|
1033
|
+
const project = store.requireProject(decodeURIComponent(projectTriageRoute[1]));
|
|
1034
|
+
const tasks = store.listTasks({ projectId: project.id }).filter((t) => t.triageAt || (t.labels || []).includes("triage"));
|
|
1035
|
+
return {
|
|
1036
|
+
status: 200,
|
|
1037
|
+
payload: {
|
|
1038
|
+
project: project.id, count: tasks.length,
|
|
1039
|
+
tasks: tasks.map((t) => ({ identifier: t.identifier, title: t.title, status: t.status, blockKind: t.blockKind, blockRecurrences: t.blockRecurrences, triageAt: t.triageAt })),
|
|
1040
|
+
},
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
// FR-78:人工重置失败计数(清熔断)
|
|
1044
|
+
const taskResetFailuresRoute = /^\/api\/tasks\/([^/]+)\/reset-failures$/.exec(pathname);
|
|
1045
|
+
if (taskResetFailuresRoute) {
|
|
1046
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "reset-failures 仅支持 POST");
|
|
1047
|
+
const task = store.resetTaskFailures(decodeURIComponent(taskResetFailuresRoute[1]));
|
|
1048
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1049
|
+
return { status: 200, payload: { task, guard: store.dispatchGuard(task) } };
|
|
1050
|
+
}
|
|
1051
|
+
// FR-77:执行侧心跳(认领续命)
|
|
1052
|
+
const taskHeartbeatRoute = /^\/api\/tasks\/([^/]+)\/heartbeat$/.exec(pathname);
|
|
1053
|
+
if (taskHeartbeatRoute) {
|
|
1054
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "heartbeat 仅支持 POST");
|
|
1055
|
+
const ref = decodeURIComponent(taskHeartbeatRoute[1]);
|
|
1056
|
+
const r = store.heartbeatTask(ref, { lock: body.lock ?? null, note: body.note ?? null });
|
|
1057
|
+
return { status: r.ok ? 200 : 409, payload: { ...r, claim: store.taskClaimState(ref) } };
|
|
1058
|
+
}
|
|
1059
|
+
// FR-77:回收失效认领(认领过期 / 心跳陈旧)
|
|
1060
|
+
const taskReclaimRoute = /^\/api\/tasks\/([^/]+)\/reclaim$/.exec(pathname);
|
|
1061
|
+
if (taskReclaimRoute) {
|
|
1062
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "reclaim 仅支持 POST");
|
|
1063
|
+
const ref = decodeURIComponent(taskReclaimRoute[1]);
|
|
1064
|
+
const r = store.reclaimStaleClaim(ref);
|
|
1065
|
+
if (r.reclaimed) {
|
|
1066
|
+
const t = store.getTaskById(store.requireTaskRef(ref).id);
|
|
1067
|
+
emit("task.updated", { taskId: t.id, identifier: t.identifier, status: t.status });
|
|
1068
|
+
}
|
|
1069
|
+
return { status: r.reclaimed ? 200 : 409, payload: r };
|
|
1070
|
+
}
|
|
1071
|
+
// FR-76:把执行反馈里的"下一步建议"跟进掉(派生为子任务 / 忽略)。
|
|
1072
|
+
const taskFollowupRoute = /^\/api\/tasks\/([^/]+)\/followup$/.exec(pathname);
|
|
1073
|
+
if (taskFollowupRoute) {
|
|
1074
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "followup 仅支持 POST");
|
|
1075
|
+
const ref = decodeURIComponent(taskFollowupRoute[1]);
|
|
1076
|
+
const action = String(body.action ?? "derive");
|
|
1077
|
+
if (action === "derive") {
|
|
1078
|
+
const title = String(body.title ?? "").trim();
|
|
1079
|
+
if (!title) throw invalidField("title", "派生为子任务需要提供 title(建议内容)");
|
|
1080
|
+
const child = store.deriveSubtask(ref, { title: title.slice(0, 200), actor: body.actor ?? "human" });
|
|
1081
|
+
emit("task.updated", { taskId: child.id, identifier: child.identifier, status: child.status });
|
|
1082
|
+
return { status: 201, payload: { derived: true, child } };
|
|
1083
|
+
}
|
|
1084
|
+
if (action === "dismiss") {
|
|
1085
|
+
const task = store.requireTaskRef(ref);
|
|
1086
|
+
const note = String(body.title ?? "").trim();
|
|
1087
|
+
store.addComment(task.id, { body: `已忽略「下一步建议」${note ? `:${note}` : ""}(人工决策:不派生任务)` });
|
|
1088
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1089
|
+
return { status: 200, payload: { dismissed: true, identifier: task.identifier } };
|
|
1090
|
+
}
|
|
1091
|
+
throw invalidField("action", `action 只支持 derive / dismiss(收到 ${action})`);
|
|
1092
|
+
}
|
|
1093
|
+
// CLI 执行器(FR-85 前置):**由看板侧真的调 `cli:*` CLI 干活**(本仓库约定 engineer → cli:claude)。
|
|
1094
|
+
// 默认同步等待(人工触发时要拿到证据);`?async=1` 后台跑;`dryRun` 只回执行计划不真跑。
|
|
1095
|
+
const taskExecCliRoute = /^\/api\/tasks\/([^/]+)\/exec-cli$/.exec(pathname);
|
|
1096
|
+
if (taskExecCliRoute) {
|
|
1097
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "exec-cli 仅支持 POST");
|
|
1098
|
+
const task = store.requireTaskRef(decodeURIComponent(taskExecCliRoute[1]));
|
|
1099
|
+
// FR-85b:人工校验任务是升级门,不得交给 CLI 执行器跑掉
|
|
1100
|
+
if (isHumanReviewTask(task)) {
|
|
1101
|
+
throw new TbError("HUMAN_REVIEW_NOT_EXECUTABLE", `任务 ${task.identifier} 是人工校验任务:不得交给 CLI 执行器,请用人工结论入口处置`, { identifier: task.identifier });
|
|
1102
|
+
}
|
|
1103
|
+
const project = store.getProject(task.projectId);
|
|
1104
|
+
const settings = store.getProjectSettings(task.projectId);
|
|
1105
|
+
const role = String(body.role ?? "engineer");
|
|
1106
|
+
const executor = resolveCliExecutor(settings, { role });
|
|
1107
|
+
if (!executor) throw new TbError("NO_CLI_EXECUTOR", `项目 ${task.projectId} 没有可用的 CLI 执行器(teamTemplate.roles[].executor 需为 cli:*,且不在 forbiddenExecutors 中)`);
|
|
1108
|
+
const cwd = project?.workspacePath ?? null;
|
|
1109
|
+
const plan = {
|
|
1110
|
+
executor: executor.id, cli: executor.cli, role: executor.role, cwd,
|
|
1111
|
+
args: cliArgsFor({ executorId: executor.id, cwd, settings }),
|
|
1112
|
+
prompt: buildTaskPrompt(task, { project, requirementId: task.requirementId ?? null, verifyCommand: settings?.teamTemplate?.engineer?.verifyCommand ?? null }),
|
|
1113
|
+
};
|
|
1114
|
+
if (body.dryRun === true || searchParams.get("dryRun") === "1") return { status: 200, payload: { ran: false, dryRun: true, plan } };
|
|
1115
|
+
const timeoutMs = Number(body.timeoutMs ?? 0) > 0 ? Number(body.timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
1116
|
+
// FR-40 归因门(2026-10-22 · CLI 链路验证台 `tools/bench-cli-chain.mjs` 抓到):
|
|
1117
|
+
// `/exec-cli` 是**第三条真的会干活的执行入口**(另两条=`/execute` 与 `POST /api/teams` 派发),
|
|
1118
|
+
// 此前只判人工校验门 ⇒ 未归因的卡照样被 CLI **真跑**(真 spawn 子进程 + 状态流转到「待验收」),
|
|
1119
|
+
// 而归因门只在 `claimForCliExecution` 里被 try/catch 吞成 `outcome.note`(不抛、不阻断)
|
|
1120
|
+
// ⇒ 同一类缺口「门判定必须**先于**副作用」在这条路上失效。
|
|
1121
|
+
// 口径:只加**归因门**,**不加**完整 `assertExecutable` —— CLI 执行器有意支持非 `todo` 状态
|
|
1122
|
+
// (`claimForCliExecution` 的 `direct-handoff`:人工显式点击即授权,backlog/in_review/done 都要如实进
|
|
1123
|
+
// 「进行中」),套 `assertExecutable` 会把这条设计挡掉。
|
|
1124
|
+
// `dryRun` 保持宽松:只回执行计划、无副作用,预览不该被归因门挡住。
|
|
1125
|
+
store.assertAttributed(task.identifier);
|
|
1126
|
+
// 真实落盘:先认领并转「进行中」——否则看板只看到 todo / 原状态,且与执行循环之间没有互斥。
|
|
1127
|
+
// 口径见 `claimForCliExecution`:todo 走授权门;其它状态(人工显式点击即授权)也**必须如实
|
|
1128
|
+
// 进入「进行中」**,否则整个执行期看板显示错误的列(2026-10-18 实测 -73 停在「待办池」14 分钟)。
|
|
1129
|
+
const claim = claimForCliExecution(store, task.identifier, { actor: "cli-executor" });
|
|
1130
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: store.requireTaskRef(task.identifier).status });
|
|
1131
|
+
const fire = () => executeTaskWithCli({ store, task, project, settings, role, timeoutMs }).catch((error) => ({ ran: false, reason: String(error?.message ?? error) }));
|
|
1132
|
+
if (body.async === true || searchParams.get("async") === "1") {
|
|
1133
|
+
fire();
|
|
1134
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1135
|
+
return { status: 202, payload: { ran: true, async: true, executor: executor.id, plan, claim } };
|
|
1136
|
+
}
|
|
1137
|
+
const r = await fire();
|
|
1138
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: store.requireTaskRef(task.identifier).status });
|
|
1139
|
+
return {
|
|
1140
|
+
status: 200,
|
|
1141
|
+
payload: {
|
|
1142
|
+
ran: Boolean(r.ran), executor: r.executor?.id ?? executor.id, reason: r.reason ?? null,
|
|
1143
|
+
ok: r.result?.ok ?? false, exitCode: r.result?.exitCode ?? null, timedOut: r.result?.timedOut ?? false,
|
|
1144
|
+
durationMs: r.result?.durationMs ?? 0, cwd: r.result?.cwd ?? null, files: r.result?.diff?.files ?? [],
|
|
1145
|
+
stdout: r.result?.stdout ?? "", stderr: r.result?.stderr ?? "", comment: r.comment ?? null,
|
|
1146
|
+
claim,
|
|
1147
|
+
status: store.requireTaskRef(task.identifier).status,
|
|
1148
|
+
},
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
// 打开任务执行会话(人工介入调试/继续)——FR-84:**三级回落 + 打开前探活**。
|
|
1152
|
+
// 回落链:任务自身会话 → 项目主会话 → 项目已关联会话(排除 rejected,取最新)。
|
|
1153
|
+
// 探活口径:`exists === false`(确认失效)直接失败并标记 stale,**不再尝试打开**;
|
|
1154
|
+
// `exists === null`(判不准)**照旧尝试**,不得当作失效。
|
|
1155
|
+
const taskOpenSessionRoute = /^\/api\/tasks\/([^/]+)\/open-session$/.exec(pathname);
|
|
1156
|
+
if (taskOpenSessionRoute) {
|
|
1157
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "open-session 仅支持 POST");
|
|
1158
|
+
const task = store.requireTaskRef(decodeURIComponent(taskOpenSessionRoute[1]));
|
|
1159
|
+
const project = store.getProject(task.projectId) ?? null;
|
|
1160
|
+
// FR-97:三级回落(任务会话 → 项目主会话 → 项目已关联会话,排除 rejected)此前**内联**在此,
|
|
1161
|
+
// 与 `resolveSessionRef` 同逻辑却各写一份 —— 改口径必然漏改一处。改为**复用共享函数**,
|
|
1162
|
+
// `dispatch-main-session` 等新动作因此自动与本路由同口径(不另写第二份解析)。
|
|
1163
|
+
const resolved = resolveSessionRef(store, task);
|
|
1164
|
+
const sid = resolved.sessionId ?? null;
|
|
1165
|
+
const source = resolved.source ?? null;
|
|
1166
|
+
if (!sid) return { status: 200, payload: { opened: false, sessionId: null, source: null, reason: "no-session", stale: false } };
|
|
1167
|
+
const liveness = await sessionStateOf(sid);
|
|
1168
|
+
if (liveness.exists === false) {
|
|
1169
|
+
return { status: 200, payload: { opened: false, sessionId: sid, source, reason: "session-gone", stale: true, liveness } };
|
|
1170
|
+
}
|
|
1171
|
+
// FR-84 补口:**先判归属再打开** —— 该会话属于别的工作区时默认**不静默打开**(打开的是别人的会话)。
|
|
1172
|
+
const origin = await sessionOriginOf(sid, project);
|
|
1173
|
+
if (origin.mismatch === true && body?.force !== true) {
|
|
1174
|
+
return { status: 200, payload: { opened: false, sessionId: sid, source, reason: "session-other-workspace", stale: false, liveness, origin } };
|
|
1175
|
+
}
|
|
1176
|
+
const port = store.hostSessionPort;
|
|
1177
|
+
if (!port || typeof port.openSession !== "function") return { status: 200, payload: { opened: false, sessionId: sid, source, reason: "host-unavailable", hostCapabilities: null, nextAction: HOST_UNAVAILABLE_NEXT, stale: false, liveness, origin } };
|
|
1178
|
+
try { const r = await port.openSession(sid); return { status: 200, payload: { opened: Boolean(r?.opened), sessionId: sid, source, reason: r?.reason ?? null, stale: false, liveness, origin } }; }
|
|
1179
|
+
catch (error) { return { status: 200, payload: { opened: false, sessionId: sid, source, reason: error?.code ?? String(error?.message ?? error), stale: false, liveness, origin } }; }
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// ── FR-97 · 出口一:交项目主会话执行(调试修复)────────────────────────────────
|
|
1183
|
+
// 为「看板内无法规范流转执行」的卡提供一个**能真的往前推**的动作:把带边界红线的调试修复指令
|
|
1184
|
+
// 投递给项目主会话。刻意与 `/open-session` 同口径(同一条 resolveSessionRef + 同一套探活),
|
|
1185
|
+
// 不另写第二份解析 —— 见上面 open-session 路由里的抽取说明。
|
|
1186
|
+
const taskDispatchMainRoute = /^\/api\/tasks\/([^/]+)\/dispatch-main-session$/.exec(pathname);
|
|
1187
|
+
if (taskDispatchMainRoute) {
|
|
1188
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "dispatch-main-session 仅支持 POST");
|
|
1189
|
+
const task = store.requireTaskRef(decodeURIComponent(taskDispatchMainRoute[1]));
|
|
1190
|
+
// 人工校验任务是升级门:结论只能人给,不交给主会话"顺手修掉"。
|
|
1191
|
+
if (isHumanReviewTask(task)) {
|
|
1192
|
+
throw new TbError("HUMAN_REVIEW_NOT_EXECUTABLE", `任务 ${task.identifier} 是人工校验任务:不得派发执行,请用人工结论入口处置`, { identifier: task.identifier });
|
|
1193
|
+
}
|
|
1194
|
+
const project = store.getProject(task.projectId) ?? null;
|
|
1195
|
+
const resolved = resolveSessionRef(store, task);
|
|
1196
|
+
const sid = resolved.sessionId ?? null;
|
|
1197
|
+
const source = resolved.source ?? null;
|
|
1198
|
+
// 三级都解析不到 → 明确告诉人去重建主会话,**不抛 500、不静默、不写空会话标识**。
|
|
1199
|
+
if (!sid) {
|
|
1200
|
+
return { status: 200, payload: { delivered: false, sessionId: null, source: null, reason: "no-session", nextAction: "重建并绑定项目主会话" } };
|
|
1201
|
+
}
|
|
1202
|
+
// 探活口径与 open-session 一致:**只有 exists===false 才算失效**(null = 查不到,不当失效)。
|
|
1203
|
+
const liveness = await sessionStateOf(sid);
|
|
1204
|
+
if (liveness.exists === false) {
|
|
1205
|
+
return { status: 200, payload: { delivered: false, sessionId: sid, source, reason: "session-gone", nextAction: "重建并绑定项目主会话", stale: true, liveness } };
|
|
1206
|
+
}
|
|
1207
|
+
const prompt = buildDebugDispatchPrompt({
|
|
1208
|
+
task,
|
|
1209
|
+
project,
|
|
1210
|
+
note: body?.note ?? null,
|
|
1211
|
+
nextStep: body?.nextStep ?? null,
|
|
1212
|
+
});
|
|
1213
|
+
const port = store.hostSessionPort;
|
|
1214
|
+
if (!port || typeof port.sendPrompt !== "function") {
|
|
1215
|
+
return { status: 200, payload: { delivered: false, sessionId: sid, source, reason: "host-unavailable", hostCapabilities: null, nextAction: HOST_UNAVAILABLE_NEXT, prompt } };
|
|
1216
|
+
}
|
|
1217
|
+
let result = null;
|
|
1218
|
+
try { result = await port.sendPrompt(sid, prompt); }
|
|
1219
|
+
catch (error) {
|
|
1220
|
+
const reason = error?.code ?? String(error?.message ?? error);
|
|
1221
|
+
try { store.recordAudit({ actor: "board", action: "debug-dispatch-main-session", target: task.identifier, allowed: true, reason, detail: `投递失败:${reason}` }); } catch { /* ignore */ }
|
|
1222
|
+
return { status: 200, payload: { delivered: false, sessionId: sid, source, reason, nextAction: "查看主会话状态后重试" } };
|
|
1223
|
+
}
|
|
1224
|
+
const delivered = Boolean(result?.sent ?? result?.delivered ?? false);
|
|
1225
|
+
const reason2 = result?.reason ?? null;
|
|
1226
|
+
// 投递成功 ⇒ 卡进「进行中」(执行侧可写 in_progress,红线只禁 done)。
|
|
1227
|
+
// 用 `updateTask`(带 expectedVersion 的乐观锁)而不是直接改库:并发下不覆盖他人的改动。
|
|
1228
|
+
let updated = store.requireTaskRef(task.identifier);
|
|
1229
|
+
if (delivered) {
|
|
1230
|
+
updated = store.updateTask(task.identifier, { expectedVersion: updated.version, status: "in_progress", actor: "agent" });
|
|
1231
|
+
store.claimTask(task.identifier, { sessionId: sid, sourceStatus: updated.status });
|
|
1232
|
+
store.addComment(task.identifier, { body: `已交项目主会话执行(调试修复)\n- 会话:${sid}(来源 ${source ?? "未知"})\n- 投递:${delivered ? "成功" : "失败"}${reason2 ? `(${reason2})` : ""}\n- 指令摘要:调试修复 ${task.identifier}「${task.title}」——修复看板卡无法规范流转的问题;边界红线与回报格式见指令正文。` });
|
|
1233
|
+
try { store.recordAudit({ actor: "board", action: "debug-dispatch-main-session", target: task.identifier, allowed: true, reason: reason2 ?? "delivered", detail: `session=${sid} source=${source ?? "null"}` }); } catch { /* ignore */ }
|
|
1234
|
+
emit("task.updated", { taskId: updated.id, identifier: updated.identifier, status: updated.status });
|
|
1235
|
+
}
|
|
1236
|
+
return { status: 200, payload: { delivered, sessionId: sid, source, reason: reason2, stale: false, liveness, prompt } };
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// ── FR-97 · 出口二:转为执行调试 ───────────────────────────────────────────────
|
|
1240
|
+
// 给人接手的**显式标记**:加 `执行调试` 标签(幂等去重)并回「待办」,便于集中筛出来处理。
|
|
1241
|
+
// 不加表、不加列 —— 用 labels / 评论 / 事件承载(本卡口径)。
|
|
1242
|
+
const taskToDebugRoute = /^\/api\/tasks\/([^/]+)\/to-debug$/.exec(pathname);
|
|
1243
|
+
if (taskToDebugRoute) {
|
|
1244
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "to-debug 仅支持 POST");
|
|
1245
|
+
const ref = decodeURIComponent(taskToDebugRoute[1]);
|
|
1246
|
+
const task = store.requireTaskRef(ref);
|
|
1247
|
+
if (isHumanReviewTask(task)) {
|
|
1248
|
+
throw new TbError("HUMAN_REVIEW_NOT_EXECUTABLE", `任务 ${task.identifier} 是人工校验任务:结论请走人工结论入口`, { identifier: task.identifier });
|
|
1249
|
+
}
|
|
1250
|
+
// 归因门在先:未归因的卡转调试也走不通,先说清。
|
|
1251
|
+
store.assertAttributed(task.identifier);
|
|
1252
|
+
const DEBUG_LABEL = "执行调试";
|
|
1253
|
+
const labels = Array.isArray(task.labels) ? [...task.labels] : [];
|
|
1254
|
+
const already = labels.some((l) => String(l ?? "").trim() === DEBUG_LABEL);
|
|
1255
|
+
if (!already) labels.push(DEBUG_LABEL);
|
|
1256
|
+
// 幂等:已在调试标签则不重复追加;状态一律回 todo(未授权不开工 ⇒ 不直接 in_progress)。
|
|
1257
|
+
const updated = store.updateTask(task.identifier, { expectedVersion: task.version, labels, status: "todo", actor: "agent" });
|
|
1258
|
+
store.addComment(task.identifier, { body: already
|
|
1259
|
+
? `已标记为「${DEBUG_LABEL}」(此前已标记,未重复追加)并回「待办」——由人接手处理。`
|
|
1260
|
+
: `已转为「${DEBUG_LABEL}」并回「待办」——该卡的下一步需要宿主/终端环境介入,由人接手处理。` });
|
|
1261
|
+
try { store.recordAudit({ actor: "board", action: "to-debug", target: task.identifier, allowed: true, reason: "host-action-needed", detail: `label=${DEBUG_LABEL} status=todo` }); } catch { /* ignore */ }
|
|
1262
|
+
emit("task.updated", { taskId: updated.id, identifier: updated.identifier, status: updated.status });
|
|
1263
|
+
return { status: 200, payload: { task: updated, labeled: true, idempotent: already } };
|
|
1264
|
+
}
|
|
1265
|
+
// 任务 ↔ 执行会话 / 归属团队(FR-42/43 关联呈现):任务详情右侧的"归属团队"面板数据源。
|
|
1266
|
+
const taskTeamRoute = /^\/api\/tasks\/([^/]+)\/team$/.exec(pathname);
|
|
1267
|
+
if (taskTeamRoute) {
|
|
1268
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "task team 仅支持 GET");
|
|
1269
|
+
const ref = decodeURIComponent(taskTeamRoute[1]);
|
|
1270
|
+
const task = store.requireTaskRef(ref);
|
|
1271
|
+
// FR-67:与派发同口径 —— 活跃执行者团队优先,回落项目引擎配置。
|
|
1272
|
+
const engine = activeEngine(store, task.projectId);
|
|
1273
|
+
// FR-50:回显的质量门链与**派发时同口径**(配置顺序 / 未配置回落默认)——避免"派发指令"与"详情回显"两套口径。
|
|
1274
|
+
const qualityGates = store.getProjectSettings(task.projectId)?.teamTemplate?.qualityGates ?? null;
|
|
1275
|
+
const teams = store.listTeamRuns({ targetTask: ref }).map((run) => {
|
|
1276
|
+
const members = store.listTeamMembers(run.id);
|
|
1277
|
+
const tasks = store.listTeamTasks(run.id).map((tt) => ({ ...tt, attempts: store.listTeamAttempts(tt.id) }));
|
|
1278
|
+
const directive = buildTeamDirective({ teamId: run.id, targetTask: task.identifier, targetRequirement: task.requirementId, members: members.map((m) => m.role), tasks: [{ task: task.identifier, subject: task.title }], qualityGates }, engine);
|
|
1279
|
+
return { run, members, tasks, directive };
|
|
1280
|
+
}).filter((e) => e.members.length > 0 || e.tasks.length > 0); // 跳过空 run,避免详情显示"空团队"掩盖真实反馈
|
|
1281
|
+
return {
|
|
1282
|
+
status: 200,
|
|
1283
|
+
payload: {
|
|
1284
|
+
task: { id: task.id, identifier: task.identifier, title: task.title, status: task.status, sessionId: task.sessionId ?? null },
|
|
1285
|
+
engine, teams, count: teams.length, lock: store.getTaskLock(ref),
|
|
1286
|
+
},
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
const taskExecActionRoute = /^\/api\/tasks\/([^/]+)\/execution\/(fail|review|retry|release)$/.exec(pathname);
|
|
1290
|
+
if (taskExecActionRoute) {
|
|
1291
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "execution 动作仅支持 POST");
|
|
1292
|
+
const ref = decodeURIComponent(taskExecActionRoute[1]);
|
|
1293
|
+
const action = taskExecActionRoute[2];
|
|
1294
|
+
const task = action === "fail" ? store.recordTaskExecutionFailure(ref, { evidence: body.evidence, kind: body.kind })
|
|
1295
|
+
: action === "review" ? store.submitTaskForReview(ref, { comment: body.comment })
|
|
1296
|
+
: action === "retry" ? store.retryTaskExecution(ref)
|
|
1297
|
+
: store.releaseTaskAssignment(ref);
|
|
1298
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1299
|
+
return { status: 200, payload: { task } };
|
|
1300
|
+
}
|
|
1301
|
+
// FR-83:评审流程(请求评审 / 请求返工 / 评审通过)——评审是一等流程,不是单向"提交待验收"
|
|
1302
|
+
const taskReviewRoute = /^\/api\/tasks\/([^/]+)\/review$/.exec(pathname);
|
|
1303
|
+
if (taskReviewRoute) {
|
|
1304
|
+
const ref = decodeURIComponent(taskReviewRoute[1]);
|
|
1305
|
+
if (method === "GET") {
|
|
1306
|
+
const task = store.requireTaskRef(ref);
|
|
1307
|
+
const { detectReviewDeadlock } = await import("../core/review.mjs");
|
|
1308
|
+
return {
|
|
1309
|
+
status: 200,
|
|
1310
|
+
payload: {
|
|
1311
|
+
identifier: task.identifier, status: task.status, reviewState: task.reviewState ?? null,
|
|
1312
|
+
reviewer: task.reviewer ?? null, round: task.reviewRound ?? 0,
|
|
1313
|
+
requestedAt: task.reviewRequestedAt ?? null, sourceStatus: task.reviewSourceStatus ?? null,
|
|
1314
|
+
dependsOn: task.reviewDependsOn ?? null, deadlock: detectReviewDeadlock(store, task),
|
|
1315
|
+
},
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "review 仅支持 GET / POST");
|
|
1319
|
+
const action = String(body.action ?? "request");
|
|
1320
|
+
const result = action === "request" ? store.requestReview(ref, { reviewer: body.reviewer ?? null, dependsOn: body.dependsOn ?? null, comment: body.comment ?? "", actor: body.actor ?? "human" })
|
|
1321
|
+
: action === "changes" ? store.requestChanges(ref, { comment: body.comment ?? "", actor: body.actor ?? "reviewer" })
|
|
1322
|
+
: action === "approve" ? store.approveReview(ref, { comment: body.comment ?? "", actor: body.actor ?? "reviewer" })
|
|
1323
|
+
: null;
|
|
1324
|
+
if (!result) throw invalidField("action", "action 只支持 request / changes / approve");
|
|
1325
|
+
emit("task.updated", { taskId: result.task.id, identifier: result.task.identifier, status: result.task.status });
|
|
1326
|
+
return { status: 200, payload: result };
|
|
1327
|
+
}
|
|
1328
|
+
// ---- 人工校验任务(FR-85b · 人在环升级门) ----
|
|
1329
|
+
const projectHumanReviewsRoute = /^\/api\/projects\/([^/]+)\/human-reviews$/.exec(pathname);
|
|
1330
|
+
if (projectHumanReviewsRoute) {
|
|
1331
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "human-reviews 仅支持 GET");
|
|
1332
|
+
const projectId = decodeURIComponent(projectHumanReviewsRoute[1]);
|
|
1333
|
+
const state = searchParams.get("state") ?? null;
|
|
1334
|
+
const items = store.listHumanReviews({ projectId, state });
|
|
1335
|
+
const pending = store.humanReviewPending(projectId);
|
|
1336
|
+
return {
|
|
1337
|
+
status: 200,
|
|
1338
|
+
payload: {
|
|
1339
|
+
projectId, state, items, count: items.length, pendingCount: pending.length,
|
|
1340
|
+
pending: pending.map((t) => ({ identifier: t.identifier, title: t.title, category: t.humanReviewCategory ?? null, createdAt: t.createdAt ?? null })),
|
|
1341
|
+
},
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
const taskHumanReviewConcludeRoute = /^\/api\/tasks\/([^/]+)\/human-review\/conclude$/.exec(pathname);
|
|
1345
|
+
if (taskHumanReviewConcludeRoute) {
|
|
1346
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "human-review/conclude 仅支持 POST");
|
|
1347
|
+
const ref = decodeURIComponent(taskHumanReviewConcludeRoute[1]);
|
|
1348
|
+
const result = store.concludeHumanReview(ref, { conclusion: body.conclusion, comment: body.comment ?? "", actor: body.actor ?? "human" });
|
|
1349
|
+
emit("task.updated", { taskId: result.task.id, identifier: result.task.identifier, status: result.task.status });
|
|
1350
|
+
return { status: 200, payload: result };
|
|
1351
|
+
}
|
|
1352
|
+
// 派发人工校验任务(FR-85b:四类情形升级为"人在环门")。
|
|
1353
|
+
// 判定与草案**全部由服务端按可核验痕迹算**(不接受客户端塞分类);判不准即拒绝(HUMAN_REVIEW_NOT_CONFIDENT)。
|
|
1354
|
+
const taskHumanReviewRoute = /^\/api\/tasks\/([^/]+)\/human-review$/.exec(pathname);
|
|
1355
|
+
if (taskHumanReviewRoute) {
|
|
1356
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "human-review 仅支持 POST");
|
|
1357
|
+
const ref = decodeURIComponent(taskHumanReviewRoute[1]);
|
|
1358
|
+
const task = store.requireTaskRef(ref);
|
|
1359
|
+
if (isHumanReviewTask(task)) throw new TbError("HUMAN_REVIEW_NOT_KIND", `任务 ${task.identifier} 已是人工校验任务:结论请走 conclude 入口`, { identifier: task.identifier });
|
|
1360
|
+
const probe = humanReviewProbe(store, task);
|
|
1361
|
+
const classification = probe.classification;
|
|
1362
|
+
if (!classification?.confident || !classification.category) {
|
|
1363
|
+
throw new TbError("HUMAN_REVIEW_NOT_CONFIDENT", `证据不足,不升级:${classification?.confidenceReason ?? "判不准就不升级"}`, { identifier: task.identifier, missing: classification?.missing ?? [] });
|
|
1364
|
+
}
|
|
1365
|
+
// FR-85 已结论水位线(2026-10-19 真机补):同类已给出结论、且本次判定由**更早的**申报驱动 ⇒ 不得再造同类卡。
|
|
1366
|
+
// 否则「派发人工校验任务」这个按钮对一条常驻申报评论可以无限造卡(诊断会每轮重新产出该门)。
|
|
1367
|
+
const answered = humanReviewAnsweredBy(classification, probe.declarations, store.listHumanReviews({ projectId: task.projectId, state: "concluded" }));
|
|
1368
|
+
if (answered) {
|
|
1369
|
+
throw new TbError("HUMAN_REVIEW_ALREADY_EXISTS", `项目 ${task.projectId} 的同类人工校验任务 ${answered.identifier} 已给出结论(${answered.humanReviewConclusion}):如需重新升级,请先补一条**更新的**申报评论`, { identifier: answered.identifier, category: classification.category });
|
|
1370
|
+
}
|
|
1371
|
+
let plan;
|
|
1372
|
+
try { plan = planHumanReview(probe.input); } catch (error) { throw new TbError("HUMAN_REVIEW_DRAFT_INVALID", String(error?.message ?? error), { identifier: task.identifier }); }
|
|
1373
|
+
const actor = body.actor ?? "human";
|
|
1374
|
+
const humanTask = store.createHumanReviewTask({
|
|
1375
|
+
projectId: task.projectId, draft: plan.draft, actor,
|
|
1376
|
+
requirementId: task.requirementId ?? null, relatedTask: task.identifier,
|
|
1377
|
+
priority: body.priority ?? "high",
|
|
1378
|
+
});
|
|
1379
|
+
// **停手等人**:原任务移出可开工池,一直停在「受阻」,直到人工结论把它放行(conclude → continue)。
|
|
1380
|
+
// 用 holdForHumanReview 而**不是** blockTask:后者的复发/类型会覆盖掉"升级门赖以成立的证据"。
|
|
1381
|
+
let blocked = null;
|
|
1382
|
+
try {
|
|
1383
|
+
blocked = store.holdForHumanReview(task.identifier, {
|
|
1384
|
+
reason: `FR-85 人在环升级门:已派发人工校验任务 ${humanTask.identifier}(类别=${classification.category}),结论给出前不自动推进`,
|
|
1385
|
+
actor, reviewTask: humanTask.identifier,
|
|
1386
|
+
});
|
|
1387
|
+
} catch { /* 原任务已是终态等 → 不阻断建卡 */ }
|
|
1388
|
+
emit("task.updated", { taskId: humanTask.id, identifier: humanTask.identifier, status: humanTask.status, humanReview: true });
|
|
1389
|
+
if (blocked) emit("task.updated", { taskId: blocked.id, identifier: blocked.identifier, status: blocked.status });
|
|
1390
|
+
return { status: 201, payload: { task: humanTask, classification, evidence: probe.evidence, original: blocked } };
|
|
1391
|
+
}
|
|
1392
|
+
const taskDepsRoute = /^\/api\/tasks\/([^/]+)\/dependencies$/.exec(pathname);
|
|
1393
|
+
if (taskDepsRoute) {
|
|
1394
|
+
const ref = decodeURIComponent(taskDepsRoute[1]);
|
|
1395
|
+
if (method === "GET") return { status: 200, payload: store.listTaskDependencies(ref) };
|
|
1396
|
+
if (method === "POST") return { status: 201, payload: store.addTaskDependency({ blocker: body.blocker, blocked: ref, reason: body.reason }) };
|
|
1397
|
+
if (method === "DELETE") {
|
|
1398
|
+
const blocker = searchParams.get("blocker") ?? body.blocker;
|
|
1399
|
+
return { status: 200, payload: store.removeTaskDependency({ blocker, blocked: ref }) };
|
|
1400
|
+
}
|
|
1401
|
+
throw new TbError("USAGE_ERROR", `依赖路由不支持 ${method}`);
|
|
1402
|
+
}
|
|
1403
|
+
const taskReadyRoute = /^\/api\/tasks\/([^/]+)\/ready$/.exec(pathname);
|
|
1404
|
+
if (taskReadyRoute) {
|
|
1405
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "ready 仅支持 GET");
|
|
1406
|
+
return { status: 200, payload: store.isTaskReady(decodeURIComponent(taskReadyRoute[1])) };
|
|
1407
|
+
}
|
|
1408
|
+
// 抽屉「下一步」引导(真机反馈 2026-10-22:抽屉只有按功能分类的按钮,没有任何一处回答
|
|
1409
|
+
// "我现在该干嘛";人工校验门挡住的卡只有一行文字、连跳过去下结论的入口都没有)。
|
|
1410
|
+
// 推导口径唯一来源=src/core/next-step.mjs(纯函数 + 单测覆盖);本端点只做**只读**装配:
|
|
1411
|
+
// 查依赖表找出「待结论的人工校验前置」,并取看护读数,交给纯函数决定引导。
|
|
1412
|
+
const taskNextStepRoute = /^\/api\/tasks\/([^/]+)\/next-step$/.exec(pathname);
|
|
1413
|
+
if (taskNextStepRoute) {
|
|
1414
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "next-step 仅支持 GET");
|
|
1415
|
+
const task = store.requireTaskRef(decodeURIComponent(taskNextStepRoute[1]));
|
|
1416
|
+
const deps = store.listTaskDependencies(task.identifier);
|
|
1417
|
+
let humanReviewBlocker = null;
|
|
1418
|
+
for (const blocker of (deps?.blockers ?? [])) {
|
|
1419
|
+
const candidate = store.getTaskRef(blocker.identifier);
|
|
1420
|
+
if (!candidate) continue;
|
|
1421
|
+
if (!isHumanReviewTask(candidate)) continue;
|
|
1422
|
+
if (String(candidate.humanReviewState ?? "pending") === "concluded") continue;
|
|
1423
|
+
humanReviewBlocker = {
|
|
1424
|
+
identifier: candidate.identifier,
|
|
1425
|
+
title: candidate.title ?? null,
|
|
1426
|
+
category: candidate.humanReviewCategory ?? null,
|
|
1427
|
+
};
|
|
1428
|
+
break;
|
|
1429
|
+
}
|
|
1430
|
+
let stalled = false;
|
|
1431
|
+
try { stalled = assessTaskRef(store, task.identifier)?.state === "stalled"; } catch { stalled = false; }
|
|
1432
|
+
return { status: 200, payload: { task: task.identifier, humanReviewBlocker, nextStep: deriveNextStep(task, { humanReviewBlocker, stalled }) } };
|
|
1433
|
+
}
|
|
1434
|
+
// FR-93(缺陷 F-05):看板空态引导口径。推导唯一来源=src/core/empty-state.mjs(纯函数 + 单测)。
|
|
1435
|
+
// 本端点**只读**:查当前项目口径下的任务列表(含折叠卡),交给纯函数判断"为什么不显示"。
|
|
1436
|
+
// 前端是零依赖原生脚本(无法 import ESM),故按 next-step 的既有做法用只读端点传口径。
|
|
1437
|
+
const boardEmptyStateRoute = /^\/api\/projects\/([^/]+)\/empty-state$/.exec(pathname);
|
|
1438
|
+
if (boardEmptyStateRoute) {
|
|
1439
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "empty-state 仅支持 GET");
|
|
1440
|
+
const projectId = decodeURIComponent(boardEmptyStateRoute[1]);
|
|
1441
|
+
// 项目必须真实存在:否则「项目不存在」会被误报成「本项目暂无任务」(空态口径最忌讳的事就是臆断)
|
|
1442
|
+
store.requireProject(projectId);
|
|
1443
|
+
// 2026-10-22(续二十四)修复:取数口径必须与前端一致 —— 前端拿列数据走 `/api/tasks` 且**带筛选参数**,
|
|
1444
|
+
// 这里原先只用 `{ projectId }` 取全量,导致「筛选把卡全挡掉」时可见集仍非空 ⇒ 返回 `empty:false`
|
|
1445
|
+
// ⇒ 前端 `state.emptyState.empty` 为 false、**整块空态引导不渲染**(七列只剩「暂无任务」),
|
|
1446
|
+
// 正是 FR-93 要修的 F-05 场景(前端降级反而算对了 ⇒ 端点一上线行为比降级更差)。
|
|
1447
|
+
const emptyStatePriority = (searchParams.get("priority") ?? "").trim();
|
|
1448
|
+
const emptyStateLabel = (searchParams.get("label") ?? "").trim();
|
|
1449
|
+
// FR-26:会话归属维度也参与取数口径(缺失/空串=「全部」,不当作筛选条件)
|
|
1450
|
+
const emptyStateSessionScope = (searchParams.get("sessionScope") ?? "").trim();
|
|
1451
|
+
// FR-14:搜索关键词同样参与取数口径(否则"搜索无命中"会被误判成"本项目暂无任务")
|
|
1452
|
+
const emptyStateKeyword = (searchParams.get("q") ?? "").trim();
|
|
1453
|
+
const tasks = store.listTasks({
|
|
1454
|
+
projectId,
|
|
1455
|
+
priority: emptyStatePriority === "" ? undefined : emptyStatePriority,
|
|
1456
|
+
labels: emptyStateLabel === "" ? undefined : emptyStateLabel,
|
|
1457
|
+
sessionScope: emptyStateSessionScope === "" ? undefined : emptyStateSessionScope,
|
|
1458
|
+
q: emptyStateKeyword === "" ? undefined : emptyStateKeyword,
|
|
1459
|
+
}).map((task) => ({
|
|
1460
|
+
identifier: task.identifier,
|
|
1461
|
+
status: task.status,
|
|
1462
|
+
labels: task.labels ?? [],
|
|
1463
|
+
}));
|
|
1464
|
+
// 可见口径=前端 FR-88 的折叠过滤;showArchived 由查询参数带入(默认 false = 默认视图)。
|
|
1465
|
+
const showArchived = searchParams.get("showArchived") === "1";
|
|
1466
|
+
const visible = showArchived ? tasks : tasks.filter((task) => !task.labels.includes("archived"));
|
|
1467
|
+
const emptyState = deriveEmptyState({
|
|
1468
|
+
allTasks: tasks,
|
|
1469
|
+
visibleTasks: visible,
|
|
1470
|
+
filters: { priority: emptyStatePriority, label: emptyStateLabel, sessionScope: emptyStateSessionScope, keyword: emptyStateKeyword },
|
|
1471
|
+
showArchived,
|
|
1472
|
+
});
|
|
1473
|
+
return { status: 200, payload: { project: projectId, emptyState } };
|
|
1474
|
+
}
|
|
1475
|
+
// 任务评论/反馈(执行证据、进展)
|
|
1476
|
+
const taskCommentsRoute = /^\/api\/tasks\/([^/]+)\/comments$/.exec(pathname);
|
|
1477
|
+
if (taskCommentsRoute) {
|
|
1478
|
+
const ref = decodeURIComponent(taskCommentsRoute[1]);
|
|
1479
|
+
if (method === "GET") { const task = store.requireTaskRef(ref); return { status: 200, payload: { comments: store.listComments(task.id) } }; }
|
|
1480
|
+
if (method === "POST") { const task = store.requireTaskRef(ref); const c = store.addComment(task.id, { body: body.body ?? body.comment ?? "" }); emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status }); return { status: 201, payload: { comment: c } }; }
|
|
1481
|
+
throw new TbError("USAGE_ERROR", "comments 仅支持 GET 或 POST");
|
|
1482
|
+
}
|
|
1483
|
+
// FR-17:编辑一条评论(PATCH)。口径见 store.updateComment —— 乐观锁(冲突 → VERSION_CONFLICT/409)
|
|
1484
|
+
// + **编辑前原正文留痕**(comment_revisions,可回看)+ 机器证据评论只读(不得成为改写评审证据的旁路)。
|
|
1485
|
+
const taskCommentRoute = /^\/api\/tasks\/([^/]+)\/comments\/([^/]+)$/.exec(pathname);
|
|
1486
|
+
if (taskCommentRoute) {
|
|
1487
|
+
const ref = decodeURIComponent(taskCommentRoute[1]);
|
|
1488
|
+
const commentId = decodeURIComponent(taskCommentRoute[2]);
|
|
1489
|
+
const task = store.requireTaskRef(ref);
|
|
1490
|
+
if (method === "GET") {
|
|
1491
|
+
const comment = store.getComment(commentId);
|
|
1492
|
+
if (!comment || comment.taskId !== task.id) throw new TbError("COMMENT_NOT_FOUND", `评论不存在:${commentId}`, { commentId });
|
|
1493
|
+
return { status: 200, payload: { comment, revisions: store.listCommentRevisions(commentId) } };
|
|
1494
|
+
}
|
|
1495
|
+
if (method === "PATCH") {
|
|
1496
|
+
// 归属先校验:别让"编辑别的卡下的评论"绕开本任务路径(也不产生任何留痕副作用)。
|
|
1497
|
+
const existing = store.getComment(commentId);
|
|
1498
|
+
if (!existing || existing.taskId !== task.id) throw new TbError("COMMENT_NOT_FOUND", `评论不存在于任务 ${task.identifier}:${commentId}`, { commentId, identifier: task.identifier });
|
|
1499
|
+
const result = store.updateComment(commentId, {
|
|
1500
|
+
expectedVersion: body.version ?? body.expectedVersion,
|
|
1501
|
+
body: body.body ?? body.comment,
|
|
1502
|
+
actor: body.actor ?? "human",
|
|
1503
|
+
});
|
|
1504
|
+
if (result.changed) emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1505
|
+
return { status: 200, payload: { comment: result.comment, changed: result.changed, revision: result.revision ?? null } };
|
|
1506
|
+
}
|
|
1507
|
+
throw new TbError("USAGE_ERROR", "单条评论仅支持 GET 或 PATCH");
|
|
1508
|
+
}
|
|
1509
|
+
// 复杂任务自动拆解为关联子任务(FR-69)
|
|
1510
|
+
const taskDecomposeRoute = /^\/api\/tasks\/([^/]+)\/decompose$/.exec(pathname);
|
|
1511
|
+
if (taskDecomposeRoute) {
|
|
1512
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "decompose 仅支持 POST");
|
|
1513
|
+
const parent = store.requireTaskRef(decodeURIComponent(taskDecomposeRoute[1]));
|
|
1514
|
+
let specs = Array.isArray(body.tasks) && body.tasks.length ? body.tasks : null;
|
|
1515
|
+
if (!specs) {
|
|
1516
|
+
const lines = String(parent.description ?? "").split("\n").map((l) => l.trim().replace(/^[-*]\s+|^\d+[).、]\s+/, "").trim()).filter((l) => l && l.length <= 100);
|
|
1517
|
+
specs = lines.length >= 2 ? lines.map((title) => ({ title })) : [{ title: `${parent.title} — 实现` }, { title: `${parent.title} — 验证` }];
|
|
1518
|
+
}
|
|
1519
|
+
const children = [];
|
|
1520
|
+
for (const s of specs) {
|
|
1521
|
+
const child = store.createTask({ projectId: parent.projectId, title: s.title, description: s.description ?? "", status: "backlog", owner: s.owner ?? null, labels: s.labels ?? [], parentId: parent.id });
|
|
1522
|
+
if (parent.requirementId) { try { store.associateRequirementTask(parent.requirementId, child.id); } catch { /* ignore */ } }
|
|
1523
|
+
children.push({ identifier: child.identifier, title: child.title });
|
|
1524
|
+
}
|
|
1525
|
+
emit("task.updated", { taskId: parent.id, identifier: parent.identifier, status: parent.status });
|
|
1526
|
+
return { status: 201, payload: { parent: parent.identifier, children } };
|
|
1527
|
+
}
|
|
1528
|
+
// FR-90:评审前的「自动复核」—— 跑一遍项目配置的验证命令,把**机器结论**落成证据评论。
|
|
1529
|
+
// 真机反馈(2026-10-22):「判断为无法人工校验的任务,理应有自动复核或者已自动跑过测试的返回结论
|
|
1530
|
+
// 以供人员评审任务通过使用」。红线:**只旁路产证据,绝不改状态**(评审通过 / 完成仍只能由人点)。
|
|
1531
|
+
const autoReviewRoute = /^\/api\/tasks\/([^/]+)\/auto-review$/.exec(pathname);
|
|
1532
|
+
if (autoReviewRoute) {
|
|
1533
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "auto-review 仅支持 POST");
|
|
1534
|
+
const task = store.requireTaskRef(decodeURIComponent(autoReviewRoute[1]));
|
|
1535
|
+
if (task.status === "done" || task.status === "canceled") {
|
|
1536
|
+
throw new TbError("USAGE_ERROR", `已收口的卡(${task.status})不需要复核:要复核请先重新打开这张卡`);
|
|
1537
|
+
}
|
|
1538
|
+
if (isHumanReviewTask(task)) {
|
|
1539
|
+
throw new TbError("USAGE_ERROR", "人工校验卡不走自动复核:它的出口是人工结论(FR-85 人在环升级门)");
|
|
1540
|
+
}
|
|
1541
|
+
const project = store.getProject(task.projectId);
|
|
1542
|
+
const cwd = project?.workspacePath ?? null;
|
|
1543
|
+
if (!cwd) {
|
|
1544
|
+
throw new TbError("PROJECT_WORKSPACE_MISSING", "本项目未配置工作区目录(workspacePath)——自动复核需要知道在哪个目录跑命令");
|
|
1545
|
+
}
|
|
1546
|
+
const settings = store.getProjectSettings(task.projectId);
|
|
1547
|
+
// FR-94:复核动作的回落链 —— 本次显式指定 → **本卡复核动作** → 项目设置 → 内置默认。
|
|
1548
|
+
const configured = body.command ?? task.verifyCommand ?? settings?.envConfig?.verifyCommand ?? null;
|
|
1549
|
+
const command = normalizeVerifyCommand(configured ?? VERIFY_DEFAULT_COMMAND);
|
|
1550
|
+
const acceptance = String(task.acceptance ?? "");
|
|
1551
|
+
// 真机报障(2026-10-28 · hydro-two-ticket 的 T7-B):**没人配过命令**时回落到内置 `npm test`,
|
|
1552
|
+
// 而该工作区是 Java 工程 ⇒ `ENOENT package.json` ⇒ 退出码 254 ⇒ 结论「失败」。
|
|
1553
|
+
// 这是「命令不适用」,不是「测试失败」:不跑这条注定报错的命令,落一个**第三态**(不适用)+
|
|
1554
|
+
// 一条明路(去填本卡复核动作)。人配过的命令(`configured` 非空)一律照跑,不替他判断。
|
|
1555
|
+
const probe = configured ? { applicable: true, reason: null } : await probeVerifyApplicability({ command, cwd });
|
|
1556
|
+
const skipReason = probe.applicable ? null : probe.reason;
|
|
1557
|
+
const result = skipReason
|
|
1558
|
+
? { exitCode: null, timedOut: false, durationMs: 0, tail: `未执行:${skipReason}。\n请在任务「编辑 → 复核动作」(或项目设置 envConfig.verifyCommand)里填本项目的复核命令后重跑,例如 Java 工程填 \`mvn -q test\`。` }
|
|
1559
|
+
: await runVerifyCommand({ command, cwd });
|
|
1560
|
+
// FR-90 强化(真机反馈 2026-10-22:「执行结果只返回一个结果,应该在自动复核证据内自动填入
|
|
1561
|
+
// 复核总结证据及结论」):除机器头外,再把**总结 / 失败点**一并落成证据,并回传前端供自动填入。
|
|
1562
|
+
// 「不适用」不给测试计数(没跑),也不编造总结:只把原因原样写成一句结论。
|
|
1563
|
+
const summary = skipReason
|
|
1564
|
+
? { summary: `未执行命令(${skipReason}):这不是测试失败,请先配置本项目的复核命令`, failures: [], counts: { tests: null, passed: null, failed: null, durationMs: null } }
|
|
1565
|
+
: summarizeVerifyOutput(result);
|
|
1566
|
+
const comment = store.addComment(task.id, { body: formatVerifyComment({ command, ...result, ...summary, acceptance, skipReason }) });
|
|
1567
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1568
|
+
const verdict = result.timedOut ? "超时未完成" : (skipReason ? `不适用(${skipReason})` : (result.exitCode === 0 ? "通过" : `失败(退出码 ${result.exitCode})`));
|
|
1569
|
+
return { status: 201, payload: { command, cwd, ...result, applicable: !skipReason, skipReason, verdict, summary: summary.summary, failures: summary.failures, counts: summary.counts, commentId: comment.id } };
|
|
1570
|
+
}
|
|
1571
|
+
// ---- 团队执行记录(FR-42)/ 治理(FR-43) ----
|
|
1572
|
+
if (pathname === "/api/teams") {
|
|
1573
|
+
if (method === "GET") {
|
|
1574
|
+
const teams = store.listTeamRuns({
|
|
1575
|
+
targetTask: searchParams.get("task") ?? undefined,
|
|
1576
|
+
status: searchParams.get("status") ?? undefined,
|
|
1577
|
+
}).map((run) => ({
|
|
1578
|
+
...run,
|
|
1579
|
+
members: store.listTeamMembers(run.id),
|
|
1580
|
+
tasks: store.listTeamTasks(run.id),
|
|
1581
|
+
}));
|
|
1582
|
+
return { status: 200, payload: { teams, count: teams.length } };
|
|
1583
|
+
}
|
|
1584
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "/api/teams 仅支持 POST");
|
|
1585
|
+
// 派发级归因门(复用 assertAttributed):目标须归属需求条目
|
|
1586
|
+
const target = body.targetTask ? store.assertAttributed(body.targetTask) : null;
|
|
1587
|
+
if (body.targetRequirement) store.requireRequirementItemRef(body.targetRequirement);
|
|
1588
|
+
// 防重复下发:目标/成员任务中任一已有执行会话仍在执行且未返回结论 → 停发并提醒。
|
|
1589
|
+
const guardRefs = [target?.identifier ?? body.targetTask, ...(body.tasks ?? []).map((it) => (typeof it === "string" ? it : (it.task ?? it.ref)))].filter(Boolean);
|
|
1590
|
+
for (const ref of guardRefs) {
|
|
1591
|
+
const t = store.requireTaskRef(ref);
|
|
1592
|
+
const st = inflightOf(t);
|
|
1593
|
+
if (st) throw inflightError(t, st);
|
|
1594
|
+
const guard = store.dispatchGuard(t); // FR-78
|
|
1595
|
+
if (guard) throw new TbError("EXECUTION_CIRCUIT_OPEN", circuitMessage(guard, t), { identifier: t.identifier, reason: guard, failures: t.consecutiveFailures });
|
|
1596
|
+
// 真机 2026-10-22(续四十一):**认领门也要在建 run 之前判**。
|
|
1597
|
+
// 原先只在下面的 acquireTeamTask 里判 backlog ⇒ 被拒的派发仍留下空团队 run(孤儿记录)。
|
|
1598
|
+
store.assertTeamClaimable(ref);
|
|
1599
|
+
}
|
|
1600
|
+
// FR-50 验收第三条:**团队模板校验门**——模板非法(角色缺失 / 数量为 0 / 角色名不在契约集合内)⇒ 拒绝。
|
|
1601
|
+
// 必须在 `createTeamRun` **之前**(否则又留下孤儿 run)。校验的"有效模板"=本次建队实际用于装配成员的来源:
|
|
1602
|
+
// body.members 非空 → 以它为准(UI 派发走这条);否则取项目设置里的 teamTemplate.roles。
|
|
1603
|
+
// 目标未归因沿用上面的归因门(`assertAttributed`),此处不重复。
|
|
1604
|
+
let teamQualityGates = null;
|
|
1605
|
+
// FR-50 验收第一条:**装配计划**在建 run 之前就用同一份「已校验模板」算好
|
|
1606
|
+
// (角色 / 数量 / 模型 / 执行器),避免"门校验一份、装配另一份"的口径分裂。
|
|
1607
|
+
let memberPlan = [];
|
|
1608
|
+
{
|
|
1609
|
+
const pid = target?.projectId
|
|
1610
|
+
?? (body.targetTask ? store.requireTaskRef(body.targetTask).projectId : null)
|
|
1611
|
+
?? (body.targetRequirement ? store.requireRequirementItemRef(body.targetRequirement).projectId : null);
|
|
1612
|
+
const tpl = pid ? store.getProjectSettings(pid).teamTemplate : null;
|
|
1613
|
+
const effectiveRoles = (body.members ?? []).length ? body.members : (tpl?.roles ?? []);
|
|
1614
|
+
assertTeamTemplate({ roles: effectiveRoles, qualityGates: tpl?.qualityGates });
|
|
1615
|
+
memberPlan = planTeamMembers(effectiveRoles);
|
|
1616
|
+
// FR-50:把**已校验**的原始配置带下去渲染派发指令(顺序 = 配置声明顺序;未配置回落默认链并注明来源)。
|
|
1617
|
+
teamQualityGates = tpl?.qualityGates ?? null;
|
|
1618
|
+
}
|
|
1619
|
+
const run = store.createTeamRun({ targetTask: target?.id ?? null, targetRequirement: body.targetRequirement ?? null });
|
|
1620
|
+
// 按装配计划落成员:`count>1` ⇒ 同角色多名;`model` / `executor` 逐字带下去(FR-50 验收第一条)。
|
|
1621
|
+
try {
|
|
1622
|
+
for (const member of memberPlan) {
|
|
1623
|
+
store.addTeamMember({ teamId: run.id, role: member.role, model: member.model, executor: member.executor });
|
|
1624
|
+
}
|
|
1625
|
+
} catch { /* ignore */ }
|
|
1626
|
+
// 任务级执行锁(复用 acquireTeamTask):同一任务同时只 1 个活跃执行单元
|
|
1627
|
+
const locks = [];
|
|
1628
|
+
for (const item of body.tasks ?? []) {
|
|
1629
|
+
const taskRef = typeof item === "string" ? item : (item.task ?? item.ref);
|
|
1630
|
+
locks.push(store.acquireTeamTask({ teamId: run.id, task: taskRef, member: (typeof item === "object" && item.member) || null, kind: (typeof item === "object" && item.kind) || "work" }));
|
|
1631
|
+
}
|
|
1632
|
+
// 双引擎"下发对接":按项目配置的引擎分派;默认沿用端口模式
|
|
1633
|
+
const port = store.teamEnginePort;
|
|
1634
|
+
let engine = port?.mode ?? "instruction";
|
|
1635
|
+
try {
|
|
1636
|
+
const pid2 = target?.projectId ?? (body.targetTask ? store.requireTaskRef(body.targetTask).projectId : null);
|
|
1637
|
+
if (pid2) engine = activeEngine(store, pid2); // FR-67:活跃执行者团队优先
|
|
1638
|
+
} catch { /* ignore */ }
|
|
1639
|
+
let draft = null;
|
|
1640
|
+
let mode = "local-only";
|
|
1641
|
+
let sessionId = null;
|
|
1642
|
+
let presetApplied = null;
|
|
1643
|
+
if (engine === "nanmicoder" && port?.createDraft) {
|
|
1644
|
+
try {
|
|
1645
|
+
const result = await port.createDraft({
|
|
1646
|
+
teamId: run.id,
|
|
1647
|
+
targetTask: target?.identifier ?? body.targetTask ?? null,
|
|
1648
|
+
targetRequirement: body.targetRequirement ?? null,
|
|
1649
|
+
members: body.members ?? [],
|
|
1650
|
+
tasks: body.tasks ?? [],
|
|
1651
|
+
name: body.name,
|
|
1652
|
+
description: body.description,
|
|
1653
|
+
// FR-50:端口路径(nanmicoder / 其退路)同样带**已校验**门链,避免该路径派发指令丢门。
|
|
1654
|
+
qualityGates: teamQualityGates,
|
|
1655
|
+
});
|
|
1656
|
+
draft = result?.draft ?? null;
|
|
1657
|
+
mode = result?.mode ?? port.mode ?? "instruction";
|
|
1658
|
+
sessionId = result?.sessionId ?? null;
|
|
1659
|
+
presetApplied = result?.presetApplied ?? null;
|
|
1660
|
+
} catch (error) {
|
|
1661
|
+
mode = `error:${error?.code ?? error?.message ?? String(error)}`;
|
|
1662
|
+
}
|
|
1663
|
+
} else {
|
|
1664
|
+
// official / instruction:产出面向引擎的派发指令(由 DSH 队长/会话承接)
|
|
1665
|
+
draft = { directive: buildTeamDirective({ teamId: run.id, targetTask: target?.identifier ?? body.targetTask ?? null, targetRequirement: body.targetRequirement ?? null, members: body.members ?? [], tasks: body.tasks ?? [], qualityGates: teamQualityGates }, engine) };
|
|
1666
|
+
mode = engine;
|
|
1667
|
+
// 任务下发:把派发指令投递到项目主会话(否则任务只会"派发成功"但无人执行)
|
|
1668
|
+
try {
|
|
1669
|
+
const pid3 = target?.projectId ?? (body.targetTask ? store.requireTaskRef(body.targetTask).projectId : null);
|
|
1670
|
+
const bound = pid3 ? store.getProject(pid3)?.initialSessionId ?? null : null;
|
|
1671
|
+
if (bound && typeof store.hostSessionPort?.sendPrompt === "function") {
|
|
1672
|
+
const sent = await store.hostSessionPort.sendPrompt(bound, draft.directive);
|
|
1673
|
+
sessionId = sent?.sent ? bound : null;
|
|
1674
|
+
presetApplied = Boolean(sent?.sent);
|
|
1675
|
+
draft.delivered = Boolean(sent?.sent);
|
|
1676
|
+
draft.deliveryReason = sent?.sent ? null : (sent?.reason ?? "unknown");
|
|
1677
|
+
} else {
|
|
1678
|
+
draft.delivered = false;
|
|
1679
|
+
draft.deliveryReason = bound ? "prompt-unavailable" : "no-bound-session";
|
|
1680
|
+
}
|
|
1681
|
+
} catch (error) {
|
|
1682
|
+
draft.delivered = false;
|
|
1683
|
+
draft.deliveryReason = error?.message ?? String(error);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
emit("team.updated", { teamId: run.id, status: run.status });
|
|
1687
|
+
return { status: 201, payload: { team: store.getTeamRun(run.id), mode, draft, sessionId, presetApplied, locks } };
|
|
1688
|
+
}
|
|
1689
|
+
// 执行循环(FR-68):把"人工设为待执行(todo)且已归因"的任务,自动派发给活跃执行者团队
|
|
1690
|
+
const projectLoopRoute = /^\/api\/projects\/([^/]+)\/execution-loop$/.exec(pathname);
|
|
1691
|
+
if (projectLoopRoute) {
|
|
1692
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "execution-loop 仅支持 POST");
|
|
1693
|
+
const limit = Number.isFinite(body.limit) ? body.limit : 20;
|
|
1694
|
+
const result = await runExecutionLoop({ store, events, projectId: decodeURIComponent(projectLoopRoute[1]), limit });
|
|
1695
|
+
return { status: 200, payload: result };
|
|
1696
|
+
}
|
|
1697
|
+
// 执行看护(FR-75/76):列出需要人介入的任务(停滞 / 待决策)
|
|
1698
|
+
const projectWatchdogRoute = /^\/api\/projects\/([^/]+)\/watchdog$/.exec(pathname);
|
|
1699
|
+
if (projectWatchdogRoute) {
|
|
1700
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "watchdog 仅支持 GET");
|
|
1701
|
+
const project = store.requireProject(decodeURIComponent(projectWatchdogRoute[1]));
|
|
1702
|
+
const rows = projectWatchdog(store, project.id);
|
|
1703
|
+
return {
|
|
1704
|
+
status: 200,
|
|
1705
|
+
payload: {
|
|
1706
|
+
project: project.id, count: rows.length,
|
|
1707
|
+
stalled: rows.filter((r) => r.state === "stalled").length,
|
|
1708
|
+
awaitingDecision: rows.filter((r) => r.state === "awaiting-decision").length,
|
|
1709
|
+
tasks: rows,
|
|
1710
|
+
},
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
// FR-79:项目级诊断(进行中 / 受阻 / 待验收三类任务的可操作诊断 + 严重度汇总)
|
|
1714
|
+
const projectDiagnosticsRoute = /^\/api\/projects\/([^/]+)\/diagnostics$/.exec(pathname);
|
|
1715
|
+
if (projectDiagnosticsRoute) {
|
|
1716
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "diagnostics 仅支持 GET");
|
|
1717
|
+
const project = store.requireProject(decodeURIComponent(projectDiagnosticsRoute[1]));
|
|
1718
|
+
const { rows, summary } = projectDiagnostics(store, project.id);
|
|
1719
|
+
return { status: 200, payload: { project: project.id, count: rows.length, summary, diagnostics: rows } };
|
|
1720
|
+
}
|
|
1721
|
+
// FR-83:评审队列(待验收任务 + 评审态 + 评审死锁判定)
|
|
1722
|
+
const projectReviewsRoute = /^\/api\/projects\/([^/]+)\/reviews$/.exec(pathname);
|
|
1723
|
+
if (projectReviewsRoute) {
|
|
1724
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "reviews 仅支持 GET");
|
|
1725
|
+
const project = store.requireProject(decodeURIComponent(projectReviewsRoute[1]));
|
|
1726
|
+
const state = searchParams.get("state");
|
|
1727
|
+
const rows = store.listReviews(project.id, { state });
|
|
1728
|
+
return {
|
|
1729
|
+
status: 200,
|
|
1730
|
+
payload: {
|
|
1731
|
+
project: project.id, count: rows.length,
|
|
1732
|
+
pending: rows.filter((r) => (r.reviewState ?? "pending") === "pending").length,
|
|
1733
|
+
changesRequested: store.listTasks({ projectId: project.id }).filter((t) => t.reviewState === "changes_requested" && t.status !== "done").length,
|
|
1734
|
+
approved: rows.filter((r) => r.reviewState === "approved").length,
|
|
1735
|
+
deadlocked: rows.filter((r) => r.deadlock?.deadlocked).length,
|
|
1736
|
+
tasks: rows.map((t) => ({
|
|
1737
|
+
identifier: t.identifier, title: t.title, status: t.status, reviewState: t.reviewState ?? null,
|
|
1738
|
+
reviewer: t.reviewer ?? null, round: t.reviewRound ?? 0, requestedAt: t.reviewRequestedAt ?? null,
|
|
1739
|
+
deadlock: t.deadlock ?? null,
|
|
1740
|
+
})),
|
|
1741
|
+
},
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1744
|
+
// ---------------- 项目推进清单(2026-10-28 · 拍板 E1/E3) ----------------
|
|
1745
|
+
// E1:**纯投影**,不落表;同状态重复请求字节级一致(不含 now/minutes)。
|
|
1746
|
+
const projectAdvanceRoute = /^\/api\/projects\/([^/]+)\/advance$/.exec(pathname);
|
|
1747
|
+
if (projectAdvanceRoute) {
|
|
1748
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "推进清单仅支持 GET(要投给主会话用 POST …/advance/announce)");
|
|
1749
|
+
const project = store.requireProject(decodeURIComponent(projectAdvanceRoute[1]));
|
|
1750
|
+
const list = buildAdvance(store, project.id);
|
|
1751
|
+
const payload = { ...list };
|
|
1752
|
+
// P-B:`?format=block` 直接给可投递的指令装载块(含【项目记忆】段)
|
|
1753
|
+
if (String(searchParams.get("format") ?? "") === "block") {
|
|
1754
|
+
const recall = store.recallMemory({ projectId: project.id });
|
|
1755
|
+
payload.block = [renderAdvanceBlock(list), renderMemoryBlock(recall, { projectName: project.name })].join("\n\n");
|
|
1756
|
+
payload.memory = { count: recall.count, ids: recall.entries.map((e) => e.id) };
|
|
1757
|
+
}
|
|
1758
|
+
return { status: 200, payload };
|
|
1759
|
+
}
|
|
1760
|
+
// P-B:把清单 + 项目记忆拼成**一段**装载块投给主会话(复用既有 sendPrompt,不新增投递通道)
|
|
1761
|
+
const projectAdvanceAnnounceRoute = /^\/api\/projects\/([^/]+)\/advance\/announce$/.exec(pathname);
|
|
1762
|
+
if (projectAdvanceAnnounceRoute) {
|
|
1763
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "advance/announce 仅支持 POST");
|
|
1764
|
+
const project = store.requireProject(decodeURIComponent(projectAdvanceAnnounceRoute[1]));
|
|
1765
|
+
const sid = body.sessionId ? String(body.sessionId) : (project.initialSessionId ?? null);
|
|
1766
|
+
if (!sid) throw new TbError("NO_MAIN_SESSION", "该项目还没有主会话:先在开局流程绑主会话,或用 body.sessionId 指定", { projectId: project.id });
|
|
1767
|
+
const hostPort = store.hostSessionPort;
|
|
1768
|
+
if (!hostPort || typeof hostPort.sendPrompt !== "function") throw new TbError("HOST_UNAVAILABLE", "宿主会话通道不可用,无法投递装载块", { projectId: project.id });
|
|
1769
|
+
const list = buildAdvance(store, project.id);
|
|
1770
|
+
const recall = store.recallMemory({ projectId: project.id });
|
|
1771
|
+
const blockText = [renderAdvanceBlock(list), renderMemoryBlock(recall, { projectName: project.name })].join("\n\n");
|
|
1772
|
+
let sent = null;
|
|
1773
|
+
try { sent = await hostPort.sendPrompt(sid, blockText); } catch (e) { sent = { sent: false, reason: e?.message ?? "error" }; }
|
|
1774
|
+
store.recordMemoryRecalls({ sessionId: sid, entries: recall.entries, reason: "advance-announce" });
|
|
1775
|
+
try {
|
|
1776
|
+
store.recordAudit({ actor: body.actor ?? "board", action: "advance-announce", target: project.id, allowed: Boolean(sent?.sent), reason: sent?.reason ?? "delivered", detail: `session=${sid} items=${list.count} memory=${recall.count}` });
|
|
1777
|
+
} catch { /* 审计失败不阻断投递结果如实回包 */ }
|
|
1778
|
+
return { status: 200, payload: { project: project.id, sessionId: sid, delivered: Boolean(sent?.sent), reason: sent?.reason ?? null, items: list.count, memory: recall.count, block: blockText } };
|
|
1779
|
+
}
|
|
1780
|
+
// P-C:决定回写(**幂等**:同 decisionId 第二次只返回首次结果;accept/complete 仅人)
|
|
1781
|
+
const projectDecideRoute = /^\/api\/projects\/([^/]+)\/advance\/([^/]+)\/decide$/.exec(pathname);
|
|
1782
|
+
if (projectDecideRoute) {
|
|
1783
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "decide 仅支持 POST");
|
|
1784
|
+
const project = store.requireProject(decodeURIComponent(projectDecideRoute[1]));
|
|
1785
|
+
const decisionId = decodeURIComponent(projectDecideRoute[2]);
|
|
1786
|
+
const result = applyDecision(store, project.id, decisionId, { choice: body.choice, note: body.note ?? null, actor: body.actor ?? "human" });
|
|
1787
|
+
try {
|
|
1788
|
+
store.recordAudit({ actor: body.actor ?? "human", action: "advance-decide", target: decisionId, allowed: true, reason: result.replay ? "replay" : String(result.choice ?? ""), detail: `kind=${result.kind ?? result.applied?.kind ?? "?"} task=${result.taskRef ?? result.applied?.taskRef ?? "?"}` });
|
|
1789
|
+
} catch { /* 同上 */ }
|
|
1790
|
+
return { status: 200, payload: result };
|
|
1791
|
+
}
|
|
1792
|
+
// ---------------- 项目记忆(2026-10-28 · 拍板 D-M1/D-M2/D-M5) ----------------
|
|
1793
|
+
const projectMemoryRoute = /^\/api\/projects\/([^/]+)\/memory$/.exec(pathname);
|
|
1794
|
+
if (projectMemoryRoute) {
|
|
1795
|
+
const project = store.requireProject(decodeURIComponent(projectMemoryRoute[1]));
|
|
1796
|
+
if (method === "GET") {
|
|
1797
|
+
const entries = store.listMemoryEntries({
|
|
1798
|
+
projectId: project.id,
|
|
1799
|
+
scope: searchParams.get("scope") ?? null,
|
|
1800
|
+
kind: searchParams.get("kind") ?? null,
|
|
1801
|
+
includeProposed: String(searchParams.get("includeProposed") ?? "") === "1",
|
|
1802
|
+
});
|
|
1803
|
+
const recall = store.recallMemory({ projectId: project.id });
|
|
1804
|
+
return { status: 200, payload: { project: project.id, count: entries.length, entries, recall: { count: recall.count, ids: recall.entries.map((e) => e.id), chars: recall.chars } } };
|
|
1805
|
+
}
|
|
1806
|
+
if (method === "POST") {
|
|
1807
|
+
// D-M2:写入即 **proposed**,人 accept 后才会被召回
|
|
1808
|
+
const { entry, created } = store.upsertMemoryEntry({
|
|
1809
|
+
...body,
|
|
1810
|
+
projectId: body?.projectId ?? project.id,
|
|
1811
|
+
createdBy: body?.createdBy ?? "agent:board",
|
|
1812
|
+
});
|
|
1813
|
+
try { store.recordAudit({ actor: body?.createdBy ?? "agent:board", action: "memory-upsert", target: project.id, allowed: true, reason: created ? "created" : "updated", detail: `${entry.id} ${entry.scope}/${entry.kind} ${entry.provenance}` }); } catch { /* ignore */ }
|
|
1814
|
+
return { status: created ? 201 : 200, payload: { entry, created, note: entry.confidence === "proposed" ? "已写入待确认(proposed):人 accept 后才会被召回" : null } };
|
|
1815
|
+
}
|
|
1816
|
+
throw new TbError("USAGE_ERROR", "memory 仅支持 GET(列表+召回预览)/ POST(propose 一条)");
|
|
1817
|
+
}
|
|
1818
|
+
const projectMemoryAcceptRoute = /^\/api\/projects\/([^/]+)\/memory\/([^/]+)\/accept$/.exec(pathname);
|
|
1819
|
+
if (projectMemoryAcceptRoute) {
|
|
1820
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "memory accept 仅支持 POST");
|
|
1821
|
+
store.requireProject(decodeURIComponent(projectMemoryAcceptRoute[1]));
|
|
1822
|
+
const result = store.acceptMemoryEntry(decodeURIComponent(projectMemoryAcceptRoute[2]), { actor: body?.actor ?? "human" });
|
|
1823
|
+
return { status: 200, payload: result };
|
|
1824
|
+
}
|
|
1825
|
+
// FR-82:项目事件流(跨任务按全库游标;FR-81 的订阅推送数据源)
|
|
1826
|
+
const projectEventsRoute = /^\/api\/projects\/([^/]+)\/events$/.exec(pathname);
|
|
1827
|
+
if (projectEventsRoute) {
|
|
1828
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "events 仅支持 GET");
|
|
1829
|
+
const project = store.requireProject(decodeURIComponent(projectEventsRoute[1]));
|
|
1830
|
+
const since = Number(searchParams.get("since") ?? 0) || 0;
|
|
1831
|
+
const limit = Number(searchParams.get("limit") ?? 200) || 200;
|
|
1832
|
+
const events = store.listProjectEvents(project.id, { since, limit, order: searchParams.get("order") ?? "desc" });
|
|
1833
|
+
return { status: 200, payload: { project: project.id, since, count: events.length, cursor: events.reduce((acc, e) => Math.max(acc, e.cursor), since), events } };
|
|
1834
|
+
}
|
|
1835
|
+
// ---------------- FR-81 通知订阅与唤醒 ----------------
|
|
1836
|
+
// 推送一轮:把订阅游标之后的**终态事件**投递给目标会话(失败保留游标,下轮自动重试)
|
|
1837
|
+
const projectNotifyFlushRoute = /^\/api\/projects\/([^/]+)\/notify\/flush$/.exec(pathname);
|
|
1838
|
+
if (projectNotifyFlushRoute) {
|
|
1839
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "notify/flush 仅支持 POST");
|
|
1840
|
+
const project = store.requireProject(decodeURIComponent(projectNotifyFlushRoute[1]));
|
|
1841
|
+
const subId = body.subId ? String(body.subId) : null;
|
|
1842
|
+
const r = await store.flushNotifySubscriptions({ projectId: project.id, subId });
|
|
1843
|
+
for (const item of r.results) {
|
|
1844
|
+
if (item.delivered) emit("notify.delivered", { projectId: project.id, subscriptionId: item.id, sessionId: item.sessionId, mode: item.mode, kinds: item.kinds, count: item.count });
|
|
1845
|
+
else if (item.error) emit("notify.failed", { projectId: project.id, subscriptionId: item.id, sessionId: item.sessionId, error: item.error });
|
|
1846
|
+
}
|
|
1847
|
+
return { status: 200, payload: { project: project.id, count: r.count, summary: summarizeNotifyDelivery(r.results), results: r.results } };
|
|
1848
|
+
}
|
|
1849
|
+
// 预览:某游标之后"待推送的终态事件"(不推进游标、不落库)
|
|
1850
|
+
const projectNotifyEventsRoute = /^\/api\/projects\/([^/]+)\/notify\/events$/.exec(pathname);
|
|
1851
|
+
if (projectNotifyEventsRoute) {
|
|
1852
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "notify/events 仅支持 GET");
|
|
1853
|
+
const project = store.requireProject(decodeURIComponent(projectNotifyEventsRoute[1]));
|
|
1854
|
+
const since = Number(searchParams.get("since") ?? 0) || 0;
|
|
1855
|
+
const limit = Number(searchParams.get("limit") ?? 200) || 200;
|
|
1856
|
+
const taskRef = searchParams.get("task");
|
|
1857
|
+
return { status: 200, payload: store.notifyPreviewEvents({ projectId: project.id, taskRef, since, limit }) };
|
|
1858
|
+
}
|
|
1859
|
+
// 订阅列表(带每条订阅"待推送"摘要)/ 新建订阅
|
|
1860
|
+
const projectNotifyRoute = /^\/api\/projects\/([^/]+)\/notify$/.exec(pathname);
|
|
1861
|
+
if (projectNotifyRoute) {
|
|
1862
|
+
const project = store.requireProject(decodeURIComponent(projectNotifyRoute[1]));
|
|
1863
|
+
if (method === "GET") {
|
|
1864
|
+
const includeInactive = searchParams.get("activeOnly") === "0";
|
|
1865
|
+
const subs = store.listNotifySubscriptions({ projectId: project.id, activeOnly: !includeInactive });
|
|
1866
|
+
const subscriptions = subs.map((sub) => {
|
|
1867
|
+
const pending = store.notifySubPending(sub.id);
|
|
1868
|
+
return { ...sub, pending: { count: pending.count, cursor: pending.cursor, kinds: pending.kinds, since: pending.since } };
|
|
1869
|
+
});
|
|
1870
|
+
const summary = subscriptions.reduce((acc, s) => ({
|
|
1871
|
+
total: acc.total + 1,
|
|
1872
|
+
active: acc.active + (s.active ? 1 : 0),
|
|
1873
|
+
pending: acc.pending + s.pending.count,
|
|
1874
|
+
failing: acc.failing + (s.lastError ? 1 : 0),
|
|
1875
|
+
}), { total: 0, active: 0, pending: 0, failing: 0 });
|
|
1876
|
+
return { status: 200, payload: { project: project.id, count: subscriptions.length, summary, subscriptions } };
|
|
1877
|
+
}
|
|
1878
|
+
if (method === "POST") {
|
|
1879
|
+
const subscription = store.createNotifySubscription({
|
|
1880
|
+
projectId: project.id,
|
|
1881
|
+
taskRef: body.taskRef ?? null,
|
|
1882
|
+
sessionId: body.sessionId,
|
|
1883
|
+
mode: body.mode ?? "notify+wake",
|
|
1884
|
+
since: body.since ?? null,
|
|
1885
|
+
});
|
|
1886
|
+
emit("notify.subscribed", { projectId: project.id, subscriptionId: subscription.id, mode: subscription.mode, scope: subscription.scope });
|
|
1887
|
+
return { status: 201, payload: { subscription } };
|
|
1888
|
+
}
|
|
1889
|
+
throw new TbError("USAGE_ERROR", "notify 仅支持 GET / POST");
|
|
1890
|
+
}
|
|
1891
|
+
// 单条订阅:改(模式/会话/启停/游标)或删(默认软停用,?purge=1 才真删)
|
|
1892
|
+
const notifySubRoute = /^\/api\/notify\/([^/]+)$/.exec(pathname);
|
|
1893
|
+
if (notifySubRoute) {
|
|
1894
|
+
const id = decodeURIComponent(notifySubRoute[1]);
|
|
1895
|
+
if (method === "GET") {
|
|
1896
|
+
const sub = store.requireNotifySubscription(id);
|
|
1897
|
+
const pending = store.notifySubPending(id);
|
|
1898
|
+
return { status: 200, payload: { subscription: { ...sub, pending: { count: pending.count, cursor: pending.cursor, kinds: pending.kinds, since: pending.since } } } };
|
|
1899
|
+
}
|
|
1900
|
+
if (method === "PATCH") {
|
|
1901
|
+
const subscription = store.updateNotifySubscription(id, { mode: body.mode, active: body.active, sessionId: body.sessionId, since: body.since });
|
|
1902
|
+
emit("notify.updated", { subscriptionId: subscription.id, mode: subscription.mode, active: subscription.active });
|
|
1903
|
+
return { status: 200, payload: { subscription } };
|
|
1904
|
+
}
|
|
1905
|
+
if (method === "DELETE") {
|
|
1906
|
+
const r = store.deleteNotifySubscription(id, { purge: searchParams.get("purge") === "1" });
|
|
1907
|
+
emit("notify.updated", { subscriptionId: r.subscription.id, active: r.subscription.active });
|
|
1908
|
+
return { status: 200, payload: r };
|
|
1909
|
+
}
|
|
1910
|
+
throw new TbError("USAGE_ERROR", "notify/:id 仅支持 GET / PATCH / DELETE");
|
|
1911
|
+
}
|
|
1912
|
+
const teamRoute = /^\/api\/teams\/([^/]+)$/.exec(pathname);
|
|
1913
|
+
if (teamRoute) {
|
|
1914
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "团队路由仅支持 GET");
|
|
1915
|
+
const id = decodeURIComponent(teamRoute[1]);
|
|
1916
|
+
const run = store.getTeamRun(id);
|
|
1917
|
+
if (!run) throw new TbError("TEAM_NOT_FOUND", `团队不存在:${id}`, { teamId: id });
|
|
1918
|
+
return { status: 200, payload: { team: run, members: store.listTeamMembers(id), tasks: store.listTeamTasks(id) } };
|
|
1919
|
+
}
|
|
1920
|
+
const teamMemberRoute = /^\/api\/teams\/([^/]+)\/members$/.exec(pathname);
|
|
1921
|
+
if (teamMemberRoute) {
|
|
1922
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "members 仅支持 POST");
|
|
1923
|
+
return { status: 201, payload: { member: store.addTeamMember({ teamId: decodeURIComponent(teamMemberRoute[1]), role: body.role, model: body.model, executor: body.executor }) } };
|
|
1924
|
+
}
|
|
1925
|
+
const teamTaskRoute = /^\/api\/teams\/([^/]+)\/tasks$/.exec(pathname);
|
|
1926
|
+
if (teamTaskRoute) {
|
|
1927
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "team tasks 仅支持 POST");
|
|
1928
|
+
const tt = store.acquireTeamTask({ teamId: decodeURIComponent(teamTaskRoute[1]), task: body.task, member: body.member, kind: body.kind });
|
|
1929
|
+
emit("task.updated", { taskId: tt.taskId, status: "in_progress" });
|
|
1930
|
+
return { status: 201, payload: { teamTask: tt } };
|
|
1931
|
+
}
|
|
1932
|
+
const teamOutcomeRoute = /^\/api\/teams\/([^/]+)\/tasks\/([^/]+)\/outcome$/.exec(pathname);
|
|
1933
|
+
if (teamOutcomeRoute) {
|
|
1934
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "outcome 仅支持 POST");
|
|
1935
|
+
const task = store.applyTeamTaskOutcome(decodeURIComponent(teamOutcomeRoute[2]), { outcome: body.outcome, reviewPassed: body.reviewPassed, evidence: body.evidence });
|
|
1936
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1937
|
+
return { status: 200, payload: { task } };
|
|
1938
|
+
}
|
|
1939
|
+
const teamProgressRoute = /^\/api\/teams\/([^/]+)\/progress$/.exec(pathname);
|
|
1940
|
+
if (teamProgressRoute) {
|
|
1941
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "progress 仅支持 POST");
|
|
1942
|
+
const r = store.applyTeamRunProgress(decodeURIComponent(teamProgressRoute[1]), body.outcomes ?? []);
|
|
1943
|
+
emit("team.updated", { teamId: r.teamId, status: r.status });
|
|
1944
|
+
return { status: 200, payload: r };
|
|
1945
|
+
}
|
|
1946
|
+
const teamFinishRoute = /^\/api\/teams\/([^/]+)\/finish$/.exec(pathname);
|
|
1947
|
+
if (teamFinishRoute) {
|
|
1948
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "finish 仅支持 POST");
|
|
1949
|
+
const status = store.finishTeamRun(decodeURIComponent(teamFinishRoute[1]));
|
|
1950
|
+
emit("team.updated", { teamId: decodeURIComponent(teamFinishRoute[1]), status });
|
|
1951
|
+
return { status: 200, payload: { status } };
|
|
1952
|
+
}
|
|
1953
|
+
const taskLockRoute = /^\/api\/tasks\/([^/]+)\/lock$/.exec(pathname);
|
|
1954
|
+
if (taskLockRoute) {
|
|
1955
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "lock 仅支持 GET");
|
|
1956
|
+
return { status: 200, payload: { lock: store.getTaskLock(decodeURIComponent(taskLockRoute[1])) } };
|
|
1957
|
+
}
|
|
1958
|
+
const taskTeamStatusRoute = /^\/api\/tasks\/([^/]+)\/team-status$/.exec(pathname);
|
|
1959
|
+
if (taskTeamStatusRoute) {
|
|
1960
|
+
if (method !== "POST") throw new TbError("USAGE_ERROR", "team-status 仅支持 POST");
|
|
1961
|
+
const task = store.teamSetTaskStatus(decodeURIComponent(taskTeamStatusRoute[1]), { status: body.status, actor: body.actor ?? "team" });
|
|
1962
|
+
emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
|
|
1963
|
+
return { status: 200, payload: { task } };
|
|
1964
|
+
}
|
|
1965
|
+
if (pathname === "/api/governance/audit") {
|
|
1966
|
+
if (method !== "GET") throw new TbError("USAGE_ERROR", "audit 仅支持 GET");
|
|
1967
|
+
const audit = store.listGovernanceAudit({ action: searchParams.get("action") ?? undefined });
|
|
1968
|
+
return { status: 200, payload: { audit, count: audit.length } };
|
|
1969
|
+
}
|
|
1970
|
+
throw new TbError("NOT_FOUND", `未知接口:${pathname}`);
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
return { route };
|
|
1974
|
+
}
|