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.
Files changed (50) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/LICENSE +21 -0
  3. package/README.md +121 -2
  4. package/cli/tb.mjs +314 -0
  5. package/cordis.patch.yml +5 -0
  6. package/index.js +633 -0
  7. package/lib/client.js +522 -0
  8. package/package.json +83 -4
  9. package/spec//345/233/242/351/230/237agent.md +171 -0
  10. package/src/core/advance.mjs +192 -0
  11. package/src/core/agent-teams.mjs +48 -0
  12. package/src/core/binding.mjs +44 -0
  13. package/src/core/config.mjs +22 -0
  14. package/src/core/debug-dispatch.mjs +94 -0
  15. package/src/core/delivery.mjs +93 -0
  16. package/src/core/deps.mjs +53 -0
  17. package/src/core/diagnostics.mjs +648 -0
  18. package/src/core/domain.mjs +235 -0
  19. package/src/core/empty-state.mjs +240 -0
  20. package/src/core/errors.mjs +139 -0
  21. package/src/core/executor.mjs +645 -0
  22. package/src/core/human-review.mjs +773 -0
  23. package/src/core/intake.mjs +116 -0
  24. package/src/core/kickoff.mjs +147 -0
  25. package/src/core/loop.mjs +498 -0
  26. package/src/core/memory.mjs +193 -0
  27. package/src/core/next-step.mjs +377 -0
  28. package/src/core/notify.mjs +183 -0
  29. package/src/core/owner.mjs +41 -0
  30. package/src/core/requirements.mjs +262 -0
  31. package/src/core/review.mjs +82 -0
  32. package/src/core/session-naming.mjs +64 -0
  33. package/src/core/split-ask.mjs +107 -0
  34. package/src/core/store.mjs +3103 -0
  35. package/src/core/team.mjs +170 -0
  36. package/src/core/verify.mjs +170 -0
  37. package/src/core/watchdog.mjs +144 -0
  38. package/src/host/ai-elaborator.mjs +26 -0
  39. package/src/host/team-engine.mjs +125 -0
  40. package/src/host/tool-surface.mjs +205 -0
  41. package/src/server/api.mjs +1974 -0
  42. package/src/server/events.mjs +32 -0
  43. package/src/server/kickoff.mjs +46 -0
  44. package/src/server/server.mjs +211 -0
  45. package/src/server/verify.mjs +112 -0
  46. package/tools/env-check.mjs +35 -0
  47. package/tools/seed.mjs +67 -0
  48. package/web/app.js +5237 -0
  49. package/web/index.html +15 -0
  50. package/web/tokens.css +1139 -0
@@ -0,0 +1,170 @@
1
+ /**
2
+ * team.mjs —— 切片3 团队领域纯函数层(FR-42/43)。
3
+ * 只描述数据形状与状态映射;不调 agent-teams / 宿主运行时(那属宿主集成期)。
4
+ *
5
+ * 唯一权威原则:本项目库 = 任务记录权威;团队状态 = 执行权威;用 teamId + attemptId 关联;
6
+ * **done 永不由执行侧写**(由治理层拦截,见 store 的 teamSetTaskStatus)。
7
+ */
8
+ import { invalidField, TbError } from "./errors.mjs";
9
+
10
+ export const TEAM_RUN_STATUSES = Object.freeze(["staged", "running", "completed", "failed", "cancelled"]);
11
+ export const TEAM_MEMBER_STATUSES = Object.freeze(["ready", "idle", "running", "done"]);
12
+ export const TEAM_TASK_STATUSES = Object.freeze(["open", "running", "completed", "failed", "cancelled"]);
13
+ export const TEAM_TASK_KINDS = Object.freeze(["work", "review"]);
14
+ export const TEAM_ATTEMPT_RESULTS = Object.freeze(["passed", "failed"]);
15
+
16
+ export function assertOneOf(value, allowed, field) {
17
+ if (!allowed.includes(value)) throw invalidField(field, `${field} 必须是 ${allowed.join(" / ")} 之一,收到:${JSON.stringify(value)}`);
18
+ return value;
19
+ }
20
+
21
+ /**
22
+ * 状态映射表:本项目 7 状态 ↔ 团队(agent-teams 视觉/执行)状态。
23
+ * 说明:`backlog` 不派发(未授权开工);`done` 由人工置,执行侧不可写。
24
+ *
25
+ * 语义约定(2026-10-13 裁决):**部分完成 = run.status = "completed" 且存在 blocked 子任务**;
26
+ * 不引入独立 partial 状态,不加新状态、不改本映射。
27
+ */
28
+ export const STATUS_MAPPING = Object.freeze({
29
+ projectToTeam: Object.freeze({
30
+ backlog: null, // 不派发
31
+ todo: "open", // 就绪可领取
32
+ in_progress: "running",
33
+ in_review: "completed", // 已提交,待人工验收
34
+ done: "completed", // 终态(人工确认)
35
+ blocked: "failed", // 受阻
36
+ canceled: "cancelled",
37
+ }),
38
+ teamToProject: Object.freeze({
39
+ open: "todo",
40
+ running: "in_progress",
41
+ completed: "in_review", // 执行侧完成 → 只到"待验收"
42
+ failed: "blocked",
43
+ cancelled: "canceled",
44
+ }),
45
+ });
46
+
47
+ /** 执行侧允许写入的项目状态(**不含 done**)。 */
48
+ export const TEAM_WRITABLE_STATUSES = Object.freeze(["in_progress", "in_review", "blocked", "canceled"]);
49
+
50
+ /**
51
+ * FR-50:团队模板的**角色集合**——权威来源是 `spec/团队agent.md` §一 的角色表(id 列)。
52
+ * 只认这 6 个派发角色;用于创建团队时校验模板里出现的角色名。
53
+ */
54
+ export const TEAM_ROLES = Object.freeze(["lead", "planner", "engineer", "tester", "reviewer", "archivist"]);
55
+
56
+ /** FR-50:单角色**默认数量**(模板未写 `count` 时按 `spec/团队agent.md` 的默认编制取 1)。 */
57
+ export const DEFAULT_ROLE_COUNT = 1;
58
+
59
+ /**
60
+ * FR-50:单角色数量的**上限**(防止模板写一个大数把一次建队放大成海量成员行)。
61
+ * 契约里的角色只有 6 个、编制都是个位数量级,正常模板永远碰不到这条;
62
+ * 超过上限一律按「模板非法」拒绝(reason=`role-count-too-large`),**不静默截断**。
63
+ */
64
+ export const MAX_ROLE_COUNT = 50;
65
+
66
+ /**
67
+ * FR-50:**质量门顺序**的契约集合——权威来源是 `spec/团队agent.md` §二 第 4 项
68
+ * 「quality gates:质量门顺序(默认 `需求→实现→验证→审查→集成`)」。
69
+ *
70
+ * 该数组顺序即**默认链路**(未配置时回落它);配置值只允许取自这 5 个门名。
71
+ */
72
+ export const QUALITY_GATES = Object.freeze(["需求", "实现", "验证", "审查", "集成"]);
73
+
74
+ /**
75
+ * FR-50:解析模板里的**质量门顺序**(纯函数,无副作用)。
76
+ *
77
+ * 口径(与裁定口径一致):
78
+ * · **未配置 ⇒ 不算非法**:`undefined` / `null` / 空数组一律视作"未配置",
79
+ * 回落 `QUALITY_GATES` 默认链,`source = "default"`(向后兼容,老模板不受影响)。
80
+ * · 已配置 ⇒ 顺序**完全等于数组声明顺序**(不做去重、不重排、不补默认项),`source = "configured"`。
81
+ * · 宽容之处:条目两端空白会被 trim(`" 需求 "` 视同 `"需求"`)。
82
+ * 返回 `{ gates, source }`;**合法性**由 `assertTeamTemplate` 判定(本函数不抛错)。
83
+ */
84
+ export function normalizeQualityGates(tpl) {
85
+ const raw = tpl?.qualityGates;
86
+ if (!Array.isArray(raw) || raw.length === 0) return { gates: [...QUALITY_GATES], source: "default" };
87
+ const gates = raw.map((g) => (typeof g === "string" ? g.trim() : g));
88
+ return { gates, source: "configured" };
89
+ }
90
+
91
+ /** FR-50:`normalizeQualityGates` 产物的**合法**判定(已配置但取值越界 ⇒ 非法)。 */
92
+ export function assertQualityGates(tpl) {
93
+ const { gates, source } = normalizeQualityGates(tpl);
94
+ if (source === "default") return { gates, source };
95
+ gates.forEach((gate, index) => {
96
+ if (!QUALITY_GATES.includes(gate)) {
97
+ throw new TbError("INVALID_TEAM_TEMPLATE", `团队模板非法:第 ${index + 1} 个质量门 ${JSON.stringify(gate ?? null)} 不在契约集合内(${QUALITY_GATES.join(" / ")})`, { reason: "quality-gate-unknown", field: `qualityGates[${index}]`, gate: gate ?? null, allowed: [...QUALITY_GATES] });
98
+ }
99
+ });
100
+ return { gates, source };
101
+ }
102
+
103
+ /**
104
+ * FR-50 验收第三条(模板非法 ⇒ 拒绝):`assertTeamTemplate(tpl)`。
105
+ *
106
+ * 纯函数,**不产生任何副作用**(不写库、不建 run)——调用方须在**建团队之前**调用它。
107
+ * 校验三条(全部命中即抛 `INVALID_TEAM_TEMPLATE`,`details.reason` 指明是哪一条):
108
+ * ① `roles` 缺失或为空数组 ⇒ 拒绝(reason=`roles-missing-or-empty`);
109
+ * ② 任一角色 `count` 不是正整数(`0` / 负数 / 非数 / 小数)⇒ 拒绝(reason=`role-count-invalid`);
110
+ * ②b 任一角色 `count` **超过 `MAX_ROLE_COUNT`**(50)⇒ 拒绝(reason=`role-count-too-large`;防放大);
111
+ * ③ 角色名不在 `TEAM_ROLES`(即 `spec/团队agent.md` 定义的角色集合)内 ⇒ 拒绝(reason=`role-unknown`);
112
+ * ④ `qualityGates` **已配置但取值越界** ⇒ 拒绝(reason=`quality-gate-unknown`;**未配置不算非法**,见 `assertQualityGates`)。
113
+ *
114
+ * 宽容之处(与团队契约的默认编制一致,不算非法):`count` 缺省视为 `DEFAULT_ROLE_COUNT`(1);
115
+ * 角色条目允许是字符串(`"engineer"`)或对象(`{ role, count, model, executor }`)。
116
+ * 返回**规范化**后的角色列表 `[{ role, count }]`,供调用方装配成员(不改变入参对象)。
117
+ */
118
+ export function assertTeamTemplate(tpl) {
119
+ const roles = tpl?.roles;
120
+ if (!Array.isArray(roles) || roles.length === 0) {
121
+ throw new TbError("INVALID_TEAM_TEMPLATE", "团队模板非法:roles 缺失或为空(FR-50:角色缺失 ⇒ 拒绝建队)", { reason: "roles-missing-or-empty", field: "roles" });
122
+ }
123
+ const normalized = [];
124
+ roles.forEach((entry, index) => {
125
+ const role = typeof entry === "string" ? entry : entry?.role;
126
+ if (!TEAM_ROLES.includes(role)) {
127
+ throw new TbError("INVALID_TEAM_TEMPLATE", `团队模板非法:第 ${index + 1} 个角色的名字 ${JSON.stringify(role ?? null)} 不在团队契约的角色集合内(${TEAM_ROLES.join(" / ")})`, { reason: "role-unknown", field: `roles[${index}].role`, role: role ?? null, allowed: [...TEAM_ROLES] });
128
+ }
129
+ const rawCount = typeof entry === "string" ? undefined : entry?.count;
130
+ const count = rawCount === undefined || rawCount === null ? DEFAULT_ROLE_COUNT : rawCount;
131
+ if (!Number.isInteger(count) || count <= 0) {
132
+ throw new TbError("INVALID_TEAM_TEMPLATE", `团队模板非法:角色 ${role} 的数量 ${JSON.stringify(rawCount ?? count)} 不是正整数(FR-50:数量为 0 ⇒ 拒绝建队)`, { reason: "role-count-invalid", field: `roles[${index}].count`, role, count: rawCount ?? count });
133
+ }
134
+ if (count > MAX_ROLE_COUNT) {
135
+ throw new TbError("INVALID_TEAM_TEMPLATE", `团队模板非法:角色 ${role} 的数量 ${count} 超过上限 ${MAX_ROLE_COUNT}(防止一次建队放大成海量成员行)`, { reason: "role-count-too-large", field: `roles[${index}].count`, role, count, max: MAX_ROLE_COUNT });
136
+ }
137
+ normalized.push({ role, count });
138
+ });
139
+ // ④ 质量门顺序:**已配置但越界**才拒绝(未配置回落默认链,不算非法)。
140
+ assertQualityGates(tpl);
141
+ return normalized;
142
+ }
143
+
144
+ /**
145
+ * FR-50 验收第一条(**装配计划**,纯函数,无副作用):
146
+ * 「Given 一份团队模板,When 创建团队,Then 按模板生成成员(角色 / 模型 / 执行器)」。
147
+ *
148
+ * 把**已校验**的模板角色表展开成「一个成员一行」的计划:
149
+ * · `count` 缺省 ⇒ `DEFAULT_ROLE_COUNT`(1);`count:2` ⇒ **同角色 2 个成员**(不是 1 个);
150
+ * · `model` / `executor` 逐字带下去(字符串条目 ⇒ 两者为 `null`="未配置");
151
+ * · **顺序 = 模板声明顺序**(同一角色内部按 1..count 排),调用方按序 insert 即可。
152
+ *
153
+ * 与 `assertTeamTemplate` 的分工:**合法性由门判**(本函数不抛错,也不放宽门);
154
+ * `count` 非法时这里兜底为 1,只用于「门已被绕过」的极端情形,不放大成员数。
155
+ * 返回 `[{ role, model, executor }]`(**不改动入参对象**)。
156
+ */
157
+ export function planTeamMembers(roles) {
158
+ const plan = [];
159
+ for (const entry of Array.isArray(roles) ? roles : []) {
160
+ const role = typeof entry === "string" ? entry : entry?.role;
161
+ if (role === undefined || role === null || role === "") continue;
162
+ const rawCount = typeof entry === "string" ? undefined : entry?.count;
163
+ const count = rawCount === undefined || rawCount === null ? DEFAULT_ROLE_COUNT : rawCount;
164
+ const times = Number.isInteger(count) && count > 0 ? count : DEFAULT_ROLE_COUNT;
165
+ const model = typeof entry === "string" ? null : (entry?.model ?? null);
166
+ const executor = typeof entry === "string" ? null : (entry?.executor ?? null);
167
+ for (let i = 0; i < times; i += 1) plan.push({ role: String(role), model, executor });
168
+ }
169
+ return plan;
170
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * FR-90「评审前的自动复核证据」(纯函数)。
3
+ *
4
+ * 真机反馈(2026-10-22):「**判断为无法人工校验的任务,理应有自动复核或者已自动跑过测试的
5
+ * 返回结论以供人员评审任务通过使用**」——评审人不能只看到「评审通过 / 请求返工」两个按钮,
6
+ * 必须拿到**机器产出的结论**,否则只能凭感觉点按钮。
7
+ *
8
+ * 本模块只做两件事(都不碰状态、不跑进程):
9
+ * 1. `formatVerifyComment()` —— 把一次复核结果落成**机器可读**的证据评论(沿用本仓既有的
10
+ * 「【…】字段=值;…」惯例,见 FR-85 的【人工校验申报】);
11
+ * 2. `latestAutoReview()` / `buildReviewEvidence()` —— 把证据评论解析回来,供抽屉展示。
12
+ *
13
+ * 跑命令的 I/O 在 `../server/verify.mjs`(有超时与输出截断),本模块保持纯函数以便单测。
14
+ */
15
+
16
+ import { latestProgressComment } from "./watchdog.mjs";
17
+
18
+ /** 证据评论前缀与默认命令(项目未配置时的兜底)。 */
19
+ export const VERIFY_COMMENT_PREFIX = "【自动复核】";
20
+ export const VERIFY_DEFAULT_COMMAND = "npm test";
21
+ /** 命令长度与输出尾段上限:评论是给人看的证据,不是日志搬运。 */
22
+ export const VERIFY_MAX_COMMAND = 300;
23
+ export const VERIFY_MAX_TAIL = 4000;
24
+ /** FR-94:随证据一起落盘的「本卡验收标准」上限(给人看,长文截断即可)。 */
25
+ export const VERIFY_MAX_ACCEPTANCE = 2000;
26
+
27
+ /** 命令归一:空/非字符串 → 默认命令;超长截断(防把整段脚本塞进评论)。 */
28
+ export function normalizeVerifyCommand(raw) {
29
+ const s = String(raw ?? "").trim();
30
+ return s === "" ? VERIFY_DEFAULT_COMMAND : s.slice(0, VERIFY_MAX_COMMAND);
31
+ }
32
+
33
+ /**
34
+ * 人能读的结论(评审人第一眼看的就这一行)。
35
+ *
36
+ * 真机报障(2026-10-28 · hydro-two-ticket 的 T7-B):默认命令 `npm test` 在一个 **不是 Node 工程**
37
+ * 的工作区里跑,必然 `ENOENT package.json` ⇒ 退出码 254 ⇒ 结论被写成「失败」——**把"这条命令在这里
38
+ * 不适用"谎报成"你的测试挂了"**,评审人据此点「请求返工」是纯误伤。
39
+ * 故补第三态 `skipReason`:**不适用**既不是通过也不是失败,退出码照实落盘,不美化。
40
+ */
41
+ export function verdictLabel({ exitCode, timedOut, skipReason } = {}) {
42
+ if (skipReason) return `不适用(${skipReason})`;
43
+ if (timedOut) return "超时未完成";
44
+ return exitCode === 0 ? "通过" : `失败(退出码 ${exitCode})`;
45
+ }
46
+
47
+ /**
48
+ * 从输出里读出**可核验的信号**(真机反馈 2026-10-22:「执行结果只返回一个结果,应该在自动复核证据内
49
+ * 自动填入复核总结证据及结论」)。只做**保守解析**:认得 `node --test` 的两种 reporter
50
+ * (TAP/经典 `# tests 12 # pass 12 # fail 0`、spec `ℹ tests 458 ℹ pass 458 ℹ fail 0`)
51
+ * 与常见的 `N passed / M failed` 计数;认不出来就如实说"没有计数,以退出码为准",绝不编造结论。
52
+ *
53
+ * 真机 2026-10-22(-130 自动复核,第三次报障):本机 `npm test` 走 node 默认 spec reporter,
54
+ * 计数行是 `ℹ tests 458` / `ℹ pass 458` / `ℹ fail 0` —— 原实现要求关键词必须是行首词
55
+ * (`(?:^|\n)\s*#?\s*tests`),`ℹ` 把词顶掉了,于是 458/458 全绿却回 `counts: null`、
56
+ * 结论只剩「以退出码 0 为准」。修法 = 允许行首出现 reporter 标记符号(ℹ / · / • / * / # / -)。
57
+ */
58
+ export function summarizeVerifyOutput({ exitCode, timedOut = false, tail = "" } = {}) {
59
+ const text = String(tail ?? "");
60
+ const pick = (re) => { const m = re.exec(text); return m ? Number(m[1]) : null; };
61
+ // 行首允许出现的 reporter 标记:#(TAP)、ℹ(node spec)、·/•/*/-(各类美化输出)。
62
+ const head = "(?:^|\\n)[\\s\\u2139\\u00b7\\u2022*#-]*";
63
+ const tests = pick(new RegExp(head + "tests\\s+(\\d+)", "i"));
64
+ const passed = pick(new RegExp(head + "pass(?:ed)?\\s+(\\d+)", "i")) ?? pick(/(\d+)\s+passing/i);
65
+ const failed = pick(new RegExp(head + "fail(?:ed|ing)?\\s+(\\d+)", "i")) ?? pick(/(\d+)\s+failing/i);
66
+ const durationMs = pick(/duration_ms\s+([\d.]+)/i);
67
+ const failures = [];
68
+ for (const raw of text.split(/\r?\n/)) {
69
+ const line = raw.trim();
70
+ if (!line) continue;
71
+ if (/^✖|^not ok|^FAIL|AssertionError|Error:/.test(line)) failures.push(line.slice(0, 200));
72
+ if (failures.length >= 3) break;
73
+ }
74
+ let summary;
75
+ if (timedOut) summary = "命令未在超时前结束:没有可用结论,先人工看输出尾段。";
76
+ else if (passed !== null || tests !== null || failed !== null) {
77
+ const total = tests !== null ? tests : (passed !== null && failed !== null ? passed + failed : null);
78
+ const parts = [];
79
+ if (total !== null) parts.push(`共 ${total} 项`);
80
+ parts.push(`通过 ${passed ?? "?"}`);
81
+ parts.push(`失败 ${failed ?? 0}`);
82
+ if (durationMs !== null) parts.push(`${(durationMs / 1000).toFixed(1)}s`);
83
+ summary = `测试计数:${parts.join(" · ")}`;
84
+ } else if (exitCode === 0) summary = "输出里没有测试计数,以退出码 0 为准(建议人工扫一眼输出尾段)。";
85
+ else summary = `输出里没有测试计数,以退出码 ${exitCode} 为准。`;
86
+ return { summary, failures, counts: { tests, passed, failed, durationMs } };
87
+ }
88
+
89
+ /** 一次复核结果 → 证据评论正文(首行保持机器可读格式;总结与失败点各占一行,避免分隔符歧义)。 */
90
+ export function formatVerifyComment({ command, exitCode, durationMs = 0, timedOut = false, tail = "", summary = "", failures = [], acceptance = "", skipReason = null } = {}) {
91
+ const seconds = (Math.round(Number(durationMs) / 100) / 10).toFixed(1);
92
+ // 「未执行」只出现在「不适用」且确实没跑命令时(exitCode 为 null);跑过但结论不适用时退出码照实写。
93
+ const code = timedOut ? "超时" : (skipReason && exitCode === null ? "未执行" : exitCode);
94
+ const head = `${VERIFY_COMMENT_PREFIX}命令=${command};退出码=${code};耗时=${seconds}s;结论=${verdictLabel({ exitCode, timedOut, skipReason })}`;
95
+ const lines = [head];
96
+ if (skipReason) lines.push(`不适用原因:${skipReason}`);
97
+ // FR-94:把**本卡当初写下的验收标准**一并落进证据 —— 评审人一眼看到"按什么判定",
98
+ // 而不是只看一个退出码(真机反馈:「为了快速复核」)。未记录标准时**不写这一块**,不臆断。
99
+ const standard = String(acceptance ?? "").trim().slice(0, VERIFY_MAX_ACCEPTANCE);
100
+ if (standard) lines.push(`本卡验收标准:\n\`\`\`\n${standard}\n\`\`\``);
101
+ if (summary) lines.push(`总结:${summary}`);
102
+ if (Array.isArray(failures) && failures.length) lines.push(`失败点:\n${failures.map((f) => `- ${f}`).join("\n")}`);
103
+ const body = String(tail ?? "").trim().slice(0, VERIFY_MAX_TAIL);
104
+ if (body) lines.push(`输出尾段:\n\`\`\`\n${body}\n\`\`\``);
105
+ return lines.join("\n");
106
+ }
107
+
108
+ const VERIFY_RE = /【自动复核】命令=(.+?);退出码=(.+?);耗时=([\d.]+)s;结论=(.+)/;
109
+
110
+ /** 证据评论 → 结构化结果(不是本机制写的评论一律回 null,绝不猜)。 */
111
+ export function parseVerifyComment(body) {
112
+ const m = VERIFY_RE.exec(String(body ?? ""));
113
+ if (!m) return null;
114
+ const rawCode = m[2].trim();
115
+ const numeric = /^-?\d+$/.test(rawCode);
116
+ const exitCode = numeric ? Number(rawCode) : null;
117
+ const text = String(body ?? "");
118
+ const verdict = m[4].trim();
119
+ // 第三态:结论以「不适用」开头 ⇒ 这条命令在该工作区不适用(不是测试失败)。老评论无此态 ⇒ applicable=true。
120
+ const applicable = !verdict.startsWith("不适用");
121
+ const skipReason = applicable ? null : ((/^不适用原因:(.*)$/m.exec(text)?.[1] ?? "").trim() || null);
122
+ const summary = (/^总结:(.*)$/m.exec(text)?.[1] ?? "").trim() || null;
123
+ const failBlock = /^失败点:\n((?:- .*\n?)+)/m.exec(text)?.[1] ?? "";
124
+ const failures = failBlock.split(/\r?\n/).map((l) => l.replace(/^-\s*/, "").trim()).filter(Boolean);
125
+ const tail = /输出尾段:\n```\n([\s\S]*?)\n```/.exec(text)?.[1] ?? "";
126
+ const acceptance = /本卡验收标准:\n```\n([\s\S]*?)\n```/.exec(text)?.[1] ?? null;
127
+ return {
128
+ command: m[1],
129
+ exitCode,
130
+ timedOut: /超时/.test(rawCode), // 只有「超时」算超时;「未执行」是"不适用"的落盘形态
131
+ applicable,
132
+ skipReason,
133
+ durationMs: Math.round(Number(m[3]) * 1000),
134
+ verdict,
135
+ summary,
136
+ failures,
137
+ tail,
138
+ acceptance,
139
+ };
140
+ }
141
+
142
+ /** 最近一次自动复核(按评论时间取最新;时间缺失时按写入顺序取最后一条)。 */
143
+ export function latestAutoReview(comments = []) {
144
+ const rows = [];
145
+ for (const c of comments ?? []) {
146
+ const parsed = parseVerifyComment(c?.body);
147
+ if (parsed) rows.push({ ...parsed, at: c.createdAt ?? c.at ?? null, commentId: c.id ?? null });
148
+ }
149
+ if (rows.length === 0) return null;
150
+ const withAt = rows.filter((r) => r.at);
151
+ if (withAt.length > 0) return withAt.slice().sort((a, b) => (String(a.at) < String(b.at) ? 1 : -1))[0];
152
+ return rows[rows.length - 1];
153
+ }
154
+
155
+ /**
156
+ * 评审证据包:评审人打开抽屉时,除了「评审通过 / 请求返工」还该看到什么。
157
+ *
158
+ * - `autoReview`:最近一次**机器复核**的结论(本机制产出);
159
+ * - `progress`:最近一条**有进展意义**的评论(执行方/团队的回报,复用 FR-75 的抽取口径)——
160
+ * 「已自动跑过测试的返回结论」通常就落在这种评论里。
161
+ */
162
+ export function buildReviewEvidence({ comments = [] } = {}) {
163
+ const autoReview = latestAutoReview(comments);
164
+ const others = (comments ?? []).filter((c) => !parseVerifyComment(c?.body));
165
+ const progress = latestProgressComment(others);
166
+ return {
167
+ autoReview,
168
+ progress: progress ? { at: progress.createdAt ?? progress.at ?? null, body: String(progress.body ?? "") } : null,
169
+ };
170
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * watchdog.mjs —— 执行看护(FR-75 停滞检测 / FR-76 "下一步建议"跟进)。
3
+ *
4
+ * 纯函数 + 只读 store 访问,零依赖,便于单测;**不写库**(副作用留给调用方)。
5
+ * 判定口径(与 需求文档.md §二 N FR-75/FR-76 对齐):
6
+ * · running —— 执行**仍在进行**(会话在跑,或 CLI 执行器子进程在途)—— **永不**判停滞
7
+ * · awaiting-decision —— 会话已空闲,但最新反馈含"下一步 / 建议"等可跟进项(等人决策,不是卡死)
8
+ * · stalled —— 会话已空闲/未在线,且超过阈值无进展回报(疑似卡住)
9
+ * · idle / ok —— 其它情况(含阈值内)
10
+ *
11
+ * 2026-10-22 真机 `-122` 补口:原口径只看**会话**(`sessionState.running`),而 CLI 执行器那条路
12
+ * `sessionId` 恒为 `null` ⇒ 一路落 `session-offline`。真机现场:子进程真在跑(688s),看护却报
13
+ * `stalled/high`「疑似停滞 11 分钟」,主按钮变「退回待办(重新派发)」——人一点就与仍在写文件的
14
+ * 子进程并发同文件双写(违反 FR-86)。故补一路**与会话无关**的在途信号:当前尝试记录仍在跑
15
+ * 且心跳新鲜(CLI 执行期每 45s 一次,见 `executor.HEARTBEAT_INTERVAL_MS`)。心跳一停(子进程结束 /
16
+ * 执行器收尾),该信号自然消失 —— 不新增常驻心跳。
17
+ */
18
+ export const STALL_THRESHOLD_MS = 10 * 60 * 1000;
19
+ export const WATCHDOG_STATES = Object.freeze(["ok", "idle", "running", "awaiting-decision", "stalled"]);
20
+
21
+ /** 有"进展意义"的评论标记(进度 / 反馈 / 团队回报 / 失败证据)。 */
22
+ const PROGRESS_MARKERS = ["进度", "【反馈】", "团队回报", "执行失败", "执行记录"];
23
+ /**
24
+ * "下一步 / 建议"块的起始标记。
25
+ * 注意:**不能用 `\b`**——中日韩字符在 JS 正则里不属于 `\w`,`\b` 在"下一步"之后不成立。
26
+ */
27
+ const FOLLOWUP_HEAD = /^(后续步骤|下一步|后续|待决策|建议|next\s*step)/i;
28
+ /** 列表行(- / * / · / 1. / 1) / 1、)。 */
29
+ const LIST_ITEM = /^(?:[-*·]|\d+[.)、])\s+(.*)$/;
30
+
31
+ /**
32
+ * 取最近一次"有报告意义"的评论:命中进展标记(进度/反馈/团队回报/失败/执行记录)
33
+ * **或**含"下一步 / 建议"可跟进项(后者常以独立评论出现,未必带进展前缀)。
34
+ */
35
+ export function latestProgressComment(comments = []) {
36
+ for (let i = comments.length - 1; i >= 0; i -= 1) {
37
+ const body = String(comments[i]?.body ?? "");
38
+ if (PROGRESS_MARKERS.some((marker) => body.includes(marker))) return comments[i];
39
+ if (extractFollowups(body).length > 0) return comments[i];
40
+ }
41
+ return null;
42
+ }
43
+
44
+ /**
45
+ * 从反馈文本提取"下一步 / 建议"条目。
46
+ * 规则:命中起始标记后,收集紧随其后的列表行 / 疑问句;遇到普通段落即结束该块。
47
+ */
48
+ export function extractFollowups(text) {
49
+ const out = [];
50
+ let inBlock = false;
51
+ for (const raw of String(text ?? "").split(/\r?\n/)) {
52
+ const line = raw.trim();
53
+ if (!line) continue;
54
+ const head = FOLLOWUP_HEAD.exec(line);
55
+ if (head) {
56
+ inBlock = true;
57
+ // 标记行本身只在"非括号包裹的内联内容"时算条目(如 `下一步:直接重跑 finalize`);
58
+ // `下一步(马上做):` 这类限定语不算。
59
+ const rest = line.slice(head[0].length)
60
+ .replace(/^[\s::\-–]+/, "")
61
+ .replace(/^[((【][^))】]*[))】]\s*[::]?\s*/, "") // `下一步(马上做):X` → `X`
62
+ .replace(/[::]+$/, "")
63
+ .trim();
64
+ if (rest && !/^[((【].*[))】]$/.test(rest)) out.push(rest);
65
+ continue;
66
+ }
67
+ if (!inBlock) continue;
68
+ const item = LIST_ITEM.exec(line);
69
+ if (item) { out.push(item[1].trim()); continue; }
70
+ if (/[??]$/.test(line) || /^(要|是否|请|需要)/.test(line)) { out.push(line); continue; }
71
+ inBlock = false; // 普通段落 → 结束该块
72
+ }
73
+ return [...new Set(out.filter(Boolean))].slice(0, 10);
74
+ }
75
+
76
+ /** 反馈是否含"征询/待确认"信号(疑问句或明确请求确认)。 */
77
+ export function looksLikeQuestion(text) {
78
+ const t = String(text ?? "");
79
+ return /[??]/.test(t) || /(是否|能不能|要不要|需要我|要我现在|请确认|待确认|等你)/.test(t);
80
+ }
81
+
82
+ /**
83
+ * 在途尝试的**新鲜度**判定(纯函数):当前尝试仍在跑,且心跳不比阈值旧 ⇒ 视为"仍在推进"。
84
+ * CLI 执行器这条路的唯一在途信号(`sessionId` 恒为 null),因此这里是它不被误判停滞的着力点。
85
+ * 心跳字段缺失 / 解析不出 → 用 `startedAt` 兜底(尝试刚开始时心跳就是 `startedAt`)。
86
+ */
87
+ export function runInFlight(currentRun = null, { now = Date.now(), thresholdMs = STALL_THRESHOLD_MS } = {}) {
88
+ if (!currentRun || currentRun.status !== "running") return false;
89
+ const at = currentRun.lastHeartbeatAt ?? currentRun.startedAt ?? null;
90
+ if (!at) return true; // 在跑但没有时间戳:宁可算"在途"(误报停滞的代价更大)
91
+ return now - new Date(at).getTime() < thresholdMs;
92
+ }
93
+
94
+ /** 单任务看护评估(纯函数)。 */
95
+ export function assessTask({ task, comments = [], sessionState = null, currentRun = null, now = Date.now(), thresholdMs = STALL_THRESHOLD_MS } = {}) {
96
+ const base = { state: "ok", minutes: 0, lastProgressAt: null, followups: [], question: false, reason: null, session: sessionState ?? null };
97
+ if (!task || task.status !== "in_progress") return base;
98
+ const last = latestProgressComment(comments);
99
+ const lastAt = last?.createdAt ?? task.updatedAt ?? null;
100
+ const minutes = lastAt ? Math.max(0, Math.round((now - new Date(lastAt).getTime()) / 60000)) : 0;
101
+ const body = String(last?.body ?? "");
102
+ const followups = extractFollowups(body);
103
+ const question = followups.length > 0 && looksLikeQuestion(body);
104
+ // 会话可判(有 sessionId)时**只认会话状态**(那是精确信号,且会话路径的尝试记录要等 agent
105
+ // 回写才闭合,拿它当在途信号会把"会话已空闲、等人回话"误判成"在跑")。
106
+ // 会话**不可判**(CLI 执行器路径 sessionId 恒为 null)时才补尝试心跳这一路。
107
+ const sessionKnown = Boolean(sessionState?.sessionId);
108
+ const running = Boolean(sessionState?.running) || (!sessionKnown && runInFlight(currentRun, { now, thresholdMs }));
109
+ const live = Boolean(sessionState?.live);
110
+ const reason = running ? null : live ? "session-idle" : "session-offline";
111
+ if (running) return { ...base, state: "running", minutes, lastProgressAt: lastAt, followups, question };
112
+ // 会话已不在执行:有可跟进项 → 等人决策;否则超阈值 → 停滞
113
+ if (followups.length > 0) return { ...base, state: "awaiting-decision", minutes, lastProgressAt: lastAt, followups, question, reason };
114
+ if (minutes >= Math.ceil(thresholdMs / 60000)) return { ...base, state: "stalled", minutes, lastProgressAt: lastAt, followups, question: false, reason };
115
+ return { ...base, state: "idle", minutes, lastProgressAt: lastAt, followups, question: false, reason };
116
+ }
117
+
118
+ /** 便捷:按任务引用评估(读 store;不写)。 */
119
+ export function assessTaskRef(store, ref, options = {}) {
120
+ const task = store.requireTaskRef(ref);
121
+ return assessTask({
122
+ task,
123
+ comments: store.listComments(task.id),
124
+ sessionState: store.taskSessionState(task),
125
+ // CLI 执行器那条路 sessionId 恒为 null ⇒ 会话状态恒「不在线」。在途信号只能来自当前尝试
126
+ // (执行期每 45s 续心跳,见 `executor.HEARTBEAT_INTERVAL_MS`)—— 少这一路就会误判停滞。
127
+ currentRun: typeof store.getCurrentRun === "function" ? store.getCurrentRun(task) : null,
128
+ ...options,
129
+ });
130
+ }
131
+
132
+ /** 项目看护清单:只看需要人介入的状态(stalled / awaiting-decision),按严重度与停滞时长排序。 */
133
+ export function projectWatchdog(store, projectId, options = {}) {
134
+ const tasks = store.listTasks({ projectId, status: "in_progress" });
135
+ const rows = [];
136
+ for (const task of tasks) {
137
+ const assessed = assessTaskRef(store, task.identifier, options);
138
+ if (assessed.state === "stalled" || assessed.state === "awaiting-decision") {
139
+ rows.push({ identifier: task.identifier, title: task.title, ...assessed });
140
+ }
141
+ }
142
+ const rank = { stalled: 0, "awaiting-decision": 1 };
143
+ return rows.sort((a, b) => (rank[a.state] - rank[b.state]) || (b.minutes - a.minutes));
144
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * ai-elaborator.mjs —— DSH 宿主侧 AI 条目化(FR-36 首选路径)。
3
+ *
4
+ * T-6 结论:DSH 在 Cordis Context 上暴露 `llm` 服务(`LlmRuntime.stream`),
5
+ * **无需发起会话**即可直连一次模型调用。本模块把它包成 api 层可注入的 `aiElaborator`。
6
+ * 规则解析(`store.elaborateRequirementDoc`)保留为 fallback。
7
+ *
8
+ * 说明:真实调用依赖运行期已配置的 provider/model(【需实测】);本文件只做接线。
9
+ */
10
+ import { buildElaborationMessages, parseElaborationOutput } from "../core/requirements.mjs";
11
+
12
+ /**
13
+ * @param {{ llm?: { stream?: Function }, provider?: string, model?: string }} opts
14
+ * @returns {null | ((doc: {body: string}) => Promise<Array<object>>)}
15
+ */
16
+ export function createLlmElaborator({ llm, provider, model } = {}) {
17
+ if (!llm || typeof llm.stream !== "function" || !provider || !model) return null;
18
+ return async function elaborate(doc) {
19
+ const { system, messages } = buildElaborationMessages(doc.body);
20
+ let text = "";
21
+ for await (const chunk of llm.stream({ provider, model, system, messages })) {
22
+ if (chunk && chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
23
+ }
24
+ return parseElaborationOutput(text);
25
+ };
26
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * team-engine.mjs —— TeamEnginePort 真实 adapter(切片3 宿主集成)。
3
+ *
4
+ * 对齐 HostSessionPort 的**懒取**模式:每次调用经 getService(name) 现取服务,不 eager 注入。
5
+ * 双实现共用同一接口,差异只在 createDraft 的引擎调用:
6
+ * - instruction(P2,默认):建会话 + 把"派发指令"作为预置内容发给会话;approve 为 no-op。
7
+ * - agent-teams(P1,占位):经 tools.call('agent_teams_create', {approval:'required',...});
8
+ * 不可用时**自动降级**为 instruction 路径(mode="agent-teams-fallback")。T-5 通过后一键切换。
9
+ *
10
+ * 接口:createDraft({teamId,targetTask,targetRequirement,members,tasks}) → {teamId,draft,mode,sessionId?,presetApplied?}
11
+ * approve(teamId) · readTeamStatus(teamId) · subscribeTeamEvents(cb) · mode(getter)
12
+ */
13
+ import { normalizeQualityGates } from "../core/team.mjs";
14
+
15
+ export const TEAM_ENGINE_MODES = Object.freeze(["instruction", "agent-teams", "official"]);
16
+
17
+ /**
18
+ * 双引擎"下发对接":按引擎生成派发指令(供 P2 会话/工作台回显)。
19
+ * official = DSH 官方自带(spawn_teammate / team_task_*)
20
+ * nanmicoder = @nanmicoder/dsh-agent-teams(agent_teams_create)
21
+ * instruction = 指令降级
22
+ */
23
+ export function buildTeamDirective({ teamId, targetTask, targetRequirement, members = [], tasks = [], qualityGates = null }, engine = "instruction") {
24
+ // FR-50:质量门链**按项目配置渲染**(顺序 = 配置数组声明顺序);未配置回落契约默认链并注明来源。
25
+ const { gates, source } = normalizeQualityGates({ qualityGates });
26
+ const gateLine = `质量门(${source === "configured" ? "配置" : "默认"}):${gates.join("→")}`;
27
+ const head = engine === "official"
28
+ ? `[派发团队 · DSH官方自带] teamId=${teamId}\n请作为 Lead 用 spawn_teammate 召集成员、用 team_task_create 建任务看板。`
29
+ : engine === "nanmicoder"
30
+ ? `[派发团队 · @nanmicoder/dsh-agent-teams] teamId=${teamId}\n(引擎:agent_teams_create,approval=required)`
31
+ : `[派发团队] teamId=${teamId}`;
32
+ const lines = [head];
33
+ if (targetTask) lines.push(`目标:${targetTask}`);
34
+ if (targetRequirement) lines.push(`需求:${targetRequirement}`);
35
+ if (members.length) lines.push(`成员:${members.map((m) => (typeof m === "string" ? m : m.role ?? m.name ?? "member")).join("、")}`);
36
+ if (tasks.length) lines.push(`任务:${tasks.map((t) => (typeof t === "string" ? t : t.subject ?? t.title ?? t.task ?? t.id ?? "task")).join(";")}`);
37
+ lines.push(gateLine);
38
+ lines.push("操作指引:按依赖就绪逐个认领 → 执行 → 提交\"待验收\";审查未过不得解锁下游;不得置\"完成\"(人工确认)。");
39
+ return lines.join("\n");
40
+ }
41
+
42
+ function buildDirective({ teamId, targetTask, targetRequirement, members = [], tasks = [], qualityGates = null }) {
43
+ const lines = [`[派发团队] teamId=${teamId}`];
44
+ if (targetTask) lines.push(`目标:${targetTask}`);
45
+ if (targetRequirement) lines.push(`需求:${targetRequirement}`);
46
+ if (members.length) lines.push(`成员:${members.map((m) => (typeof m === "string" ? m : m.role ?? m.name ?? "member")).join("、")}`);
47
+ if (tasks.length) lines.push(`任务:${tasks.map((t) => (typeof t === "string" ? t : t.subject ?? t.title ?? t.id ?? "task")).join(";")}`);
48
+ // FR-50:P2 指令路径与 `buildTeamDirective` 同口径 —— 质量门链按项目配置渲染,未配置回落默认并注明来源。
49
+ // (2026-10-27 补口:此前只有建队 / 执行循环两条指令带门链,nanmicoder 走 `createDraft` 时丢链 ⇒ 三处口径不一。)
50
+ const { gates, source } = normalizeQualityGates({ qualityGates });
51
+ lines.push(`质量门(${source === "configured" ? "配置" : "默认"}):${gates.join("→")}`);
52
+ lines.push("操作指引:按依赖就绪逐个认领 → 执行 → 提交\"待验收\";审查未过不得解锁下游;不得置\"完成\"(人工确认)。");
53
+ return lines.join("\n");
54
+ }
55
+
56
+ export function createTeamEnginePort({ getService, mode = "instruction" } = {}) {
57
+ const sessions = () => getService?.("sessions");
58
+ const tools = () => getService?.("tools");
59
+
60
+ /** P2:建会话 + 预置"派发指令"(预置失败不抛错)。 */
61
+ async function instructionDraft(input) {
62
+ const directive = buildDirective(input);
63
+ let sessionId = null;
64
+ let presetApplied = false;
65
+ const api = sessions();
66
+ if (typeof api?.create === "function") {
67
+ try {
68
+ const created = await api.create({});
69
+ sessionId = typeof created === "string" ? created : (created?.sessionId ?? created?.id ?? null);
70
+ } catch {
71
+ sessionId = null;
72
+ }
73
+ if (sessionId && typeof api.sendMessage === "function") {
74
+ try {
75
+ await api.sendMessage(sessionId, directive);
76
+ presetApplied = true;
77
+ } catch {
78
+ presetApplied = false;
79
+ }
80
+ }
81
+ }
82
+ return { teamId: input.teamId, mode: "instruction", draft: { directive }, sessionId, presetApplied };
83
+ }
84
+
85
+ /** P1(占位):经 tools.call('agent_teams_create', {approval:'required'});不可用则降级 P2。 */
86
+ async function agentTeamsDraft(input) {
87
+ const t = tools();
88
+ if (typeof t?.call === "function") {
89
+ try {
90
+ const created = await t.call("agent_teams_create", {
91
+ approval: "required",
92
+ name: input.name ?? `team-${input.teamId}`,
93
+ description: input.description ?? "",
94
+ plan: { members: input.members ?? [], tasks: input.tasks ?? [] },
95
+ });
96
+ return { teamId: input.teamId, mode: "agent-teams", draft: created ?? null };
97
+ } catch {
98
+ /* 降级 */
99
+ }
100
+ }
101
+ const fallback = await instructionDraft(input);
102
+ return { ...fallback, mode: "agent-teams-fallback", fallbackReason: "agent-teams-unavailable" };
103
+ }
104
+
105
+ const implemented = mode === "agent-teams" ? agentTeamsDraft : instructionDraft;
106
+
107
+ return {
108
+ get mode() {
109
+ return mode;
110
+ },
111
+ createDraft: implemented,
112
+ /** P2:指令已发出,approve 为 no-op;P1 占位(T-5 通过后接 agent_teams_approve)。 */
113
+ async approve() {
114
+ return { approved: true, mode };
115
+ },
116
+ /** 团队状态以本项目 team_runs/team_tasks 为准(api 层读取);此处占位。 */
117
+ async readTeamStatus() {
118
+ return null;
119
+ },
120
+ /** 事件回流:本项目 SSE(api 层已 publish);此处占位。 */
121
+ subscribeTeamEvents() {
122
+ return () => {};
123
+ },
124
+ };
125
+ }