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,773 @@
1
+ /**
2
+ * human-review.mjs —— 人工校验任务的判定与草案构造(FR-85)。
3
+ *
4
+ * 定位:FR-85 要求"自动化无法自决"时**必须**自动派发一条人工校验任务(人在环升级门),
5
+ * 携带四要素——判定类别 / 证据 / 候选处置 / 阻塞边界;且执行侧**不得认领、不得置 done**。
6
+ *
7
+ * 本模块是这门"升级门"的**地基**:把四类判定与草案收敛成**可穷举的纯函数**,
8
+ * 便于单测覆盖、便于在不碰 store/api 的前提下先定口径。**不 import 任何既有模块**(零依赖)。
9
+ *
10
+ * 四类判据(显式,逐条可查):
11
+ * 1. real-bug-blocked 真实 bug 阻塞:**同一 bug 重复复发**(复发 ≥ 2 次,或 block_loop /
12
+ * repeated_crash / repeated_failure 诊断)**且**有**失败证据**(退出码 ≠ 0 或栈)
13
+ * 2. requirement-drift 需求异化:**任务描述与需求条目 / 上游 FR 条款相互矛盾**(矛盾证据显式申报)
14
+ * 3. architecture-change 架构变化:**实现需要改动基线架构或跨模块契约**
15
+ * 4. upstream-mismatch 与上游需求不符:**验收口径无法满足**或**需求已被取代/作废**
16
+ *
17
+ * 判定纪律:**证据不足一律 `confident=false` 且 `category=null`,绝不臆断**。
18
+ * 多类同时命中时按 `HUMAN_REVIEW_CATEGORIES` 的顺序取**首命中**(客观硬证据优先:先看"同一 bug 反复砸",
19
+ * 再看契约层冲突)。
20
+ *
21
+ * 依赖关系:FR-79(诊断条目)/ FR-80(阻断分类与复发计数)/ FR-76(待决策项)/ FR-86(阻塞影响域)。
22
+ * 本模块只做纯函数;**派发任务、置受阻、写审计**等写库动作留给后续接线(不改本文件之外的口径)。
23
+ */
24
+
25
+ /** 四类判定类别(**顺序即优先级**:多类同时命中时取首命中)。 */
26
+ export const HUMAN_REVIEW_CATEGORIES = Object.freeze([
27
+ "real-bug-blocked",
28
+ "requirement-drift",
29
+ "architecture-change",
30
+ "upstream-mismatch",
31
+ ]);
32
+
33
+ /** 类别 → 中文标签(看板呈现与人读草案均用它)。键集必须与 HUMAN_REVIEW_CATEGORIES 完全一致。 */
34
+ export const HUMAN_REVIEW_CATEGORY_LABELS = Object.freeze({
35
+ "real-bug-blocked": "真实 bug 阻塞",
36
+ "requirement-drift": "需求异化",
37
+ "architecture-change": "技术架构变化",
38
+ "upstream-mismatch": "与上游需求不符",
39
+ });
40
+
41
+ /** 类别的中文标签;未知类别回落到类别本身(不抛错,便于前端容错)。 */
42
+ export function categoryLabel(category) {
43
+ return HUMAN_REVIEW_CATEGORY_LABELS[String(category ?? "")] ?? (category == null ? null : String(category));
44
+ }
45
+
46
+ /** 复发阈值:同一 bug 复发到这个次数才算"反复砸"(沿用 FR-80 的人工兜底口径)。 */
47
+ export const HUMAN_REVIEW_RECURRENCE_THRESHOLD = 2;
48
+
49
+ /** 已"退出历史舞台"的需求/条款状态:命中即视为"与上游需求不符"。 */
50
+ export const SUPERSEDED_REQUIREMENT_STATUSES = Object.freeze([
51
+ "superseded", "obsolete", "deprecated", "replaced", "cancelled", "canceled", "rejected",
52
+ ]);
53
+
54
+ /** 执行侧红线(草案正文必须原样写明)。 */
55
+ export const EXECUTION_RED_LINE =
56
+ "执行侧约束:本任务为人工校验任务,执行侧**不得认领**、**不得写 done**;结论只能由人给出。";
57
+
58
+ /**
59
+ * 人工校验任务的**任务类型标记**(FR-85b:执行侧不可认领、不可置 done 的判定依据)。
60
+ * 落库口径:`tasks.labels` 里带该标签(幂等迁移不新增列,老库无需回填)。
61
+ */
62
+ export const HUMAN_REVIEW_LABEL = "human_review";
63
+
64
+ /** 判定该任务是否为人工校验任务(标签判定;传入 task 或 labels 数组均可)。 */
65
+ export function isHumanReviewTask(taskOrLabels) {
66
+ const labels = Array.isArray(taskOrLabels) ? taskOrLabels : (taskOrLabels?.labels ?? []);
67
+ return Array.isArray(labels) && labels.some((l) => String(l ?? "").trim() === HUMAN_REVIEW_LABEL);
68
+ }
69
+
70
+ /** 人工结论取值(FR-85 的三个出口)。 */
71
+ export const HUMAN_REVIEW_CONCLUSIONS = Object.freeze(["continue", "change-requirement", "close"]);
72
+
73
+ /** 结论 → 中文标签。 */
74
+ export const HUMAN_REVIEW_CONCLUSION_LABELS = Object.freeze({
75
+ continue: "继续(按原口径放行下游)",
76
+ "change-requirement": "变更需求(按新口径重开原任务)",
77
+ close: "关闭(不再推进该任务)",
78
+ });
79
+
80
+ /** 结论标签;未知结论回落为原值(不抛错,便于前端容错)。 */
81
+ export function conclusionLabel(conclusion) {
82
+ const key = String(conclusion ?? "");
83
+ return HUMAN_REVIEW_CONCLUSION_LABELS[key] ?? (key || null);
84
+ }
85
+
86
+ /** 结论校验:必须在三值之内。 */
87
+ export function assertConclusion(value) {
88
+ const v = String(value ?? "").trim().toLowerCase();
89
+ if (!HUMAN_REVIEW_CONCLUSIONS.includes(v)) {
90
+ throw new Error(`人工结论必须是 ${HUMAN_REVIEW_CONCLUSIONS.join(" / ")} 之一,收到:${JSON.stringify(value)}`);
91
+ }
92
+ return v;
93
+ }
94
+
95
+ /** 结论 → 原任务/下游的放行方式(**纯函数**:接线侧照此写库,口径只此一处)。 */
96
+ export function conclusionOutcome(conclusion) {
97
+ const key = String(conclusion ?? "").trim().toLowerCase();
98
+ if (key === "continue") {
99
+ return { conclusion: key, reopenOriginal: true, target: "todo", closeOriginal: false, releaseDownstream: true, note: "按原口径继续:原任务退回「可开工」重派,下游解除人工校验门。" };
100
+ }
101
+ if (key === "change-requirement") {
102
+ return { conclusion: key, reopenOriginal: true, target: "todo", closeOriginal: false, releaseDownstream: false, note: "需求变更:原任务**不自动重开**(需按新口径改写需求条目/任务描述后由人重开),下游保持受阻直到按新口径放行。" };
103
+ }
104
+ if (key === "close") {
105
+ return { conclusion: key, reopenOriginal: false, target: "canceled", closeOriginal: false, releaseDownstream: false, note: "关闭:原任务不推进(保持当前状态),下游保持受阻,等人工另行处置。" };
106
+ }
107
+ return { conclusion: null, reopenOriginal: false, target: null, closeOriginal: false, releaseDownstream: false, note: "未识别的结论:不做任何放行动作。" };
108
+ }
109
+
110
+ /** 默认阻塞边界(未显式给出影响域时的兜底;FR-86 的"关键阻塞只叫停影响域"由调用方补 downstream)。 */
111
+ export const DEFAULT_BLOCK_BOUNDARY = Object.freeze({
112
+ scope: "self-and-downstream",
113
+ description: "该任务自身及其下游依赖任务保持受阻;人工校验任务出结论之前,不得自动重派、不得静默推进。",
114
+ downstream: Object.freeze([]),
115
+ autoRetry: false,
116
+ autoAdvance: false,
117
+ });
118
+
119
+ /**
120
+ * 失败证据的文本特征(栈 / 断言失败 / 崩溃信号等)。
121
+ *
122
+ * **刻意不含「退出码 / exit code」**:退出码不能只看关键字、必须**看值**——
123
+ * `退出码 0` 是成功。退出码一律交给下面的 `exitCodeVerdict()` 判。
124
+ * (-75 P1:旧版把关键字当判据,「退出码 0」被判成失败证据 → 误升级。)
125
+ */
126
+ const FAILURE_TEXT_RE =
127
+ /(失败|报错|错误|异常|栈|堆栈|stack|traceback|assertionerror|npm\s+err|not\s+ok|segfault|panic|SIGSEGV|SIGKILL|ENOENT|EACCES)/i;
128
+ /**
129
+ * 裸栈 / 异常名(-75 P3):栈的常见形态就是**没有** `stack:` 前缀的
130
+ * `TypeError: x is not a function`,以及 `at fn (file.mjs:12:3)` 这样的帧。
131
+ * 只认**首字母大写**的 `XxxError|XxxException`,避免误伤 `noError`/`onError`/`hasError` 这类标识符。
132
+ */
133
+ const BARE_STACK_RE =
134
+ /(?:^|[\s("'`])[A-Z][A-Za-z0-9_$]*(?:Error|Exception)\b|\bat\s+(?:[^\s()]*\s*\()?[^\s():]*\.[A-Za-z0-9]{1,8}:\d+(?::\d+)?/;
135
+ /** 退出码(-75 P1/P2):**带值**解析——值才是判据,别把 `退出码 0` 读成失败。 */
136
+ const EXIT_CODE_RE = /(?:退出码|退出状态|exit\s*code|exit\s*status|returncode|return\s*code|exit)\s*[::==]?\s*(-?\d+)/gi;
137
+ /** "同一 bug 重复复发"的文本特征。 */
138
+ const RECURRENCE_TEXT_RE = /(复发|重复(出现|发生|报错)|再次出现|又(一次)?出现|recurr|repeat(ed|ing)?|again|第二次|第三次)/i;
139
+ /** 需求矛盾 / 冲突的文本特征。 */
140
+ const CONTRADICTION_TEXT_RE =
141
+ /(矛盾|相悖|冲突|与需求.{0,8}不符|与(上游|需求)条款.{0,8}(不符|背离)|contradict|conflict(s|ing)?\s+with)/i;
142
+ /** 基线架构 / 跨模块契约改动的文本特征。 */
143
+ const ARCHITECTURE_TEXT_RE =
144
+ /(架构(变化|变更|改动|调整|重设计)|基线架构|跨模块(契约|接口|边界)?|改(动|变|写).{0,6}契约|ADR|breaking\s+change)/i;
145
+ /** 验收口径不可满足 / 需求被取代的文本特征。 */
146
+ const UPSTREAM_TEXT_RE =
147
+ /(验收口径.{0,10}(无法|不能|不可|难以)满足|需求.{0,8}(已被取代|已作废|已废弃|已变更)|上游(需求|口径|条款).{0,8}(不符|已变|变更|取代)|supersed|deprecat|obsolet)/i;
148
+
149
+ const collapsed = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
150
+
151
+ const firstString = (...vals) => {
152
+ for (const v of vals) {
153
+ if (typeof v === "string" && v.trim()) return v.trim();
154
+ }
155
+ return null;
156
+ };
157
+
158
+ /** 把任意值安全转成有限数字(拿不到返回 null)。 */
159
+ function asNumber(v) {
160
+ if (typeof v === "number" && Number.isFinite(v)) return v;
161
+ if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) return Number(v);
162
+ return null;
163
+ }
164
+
165
+ /**
166
+ * 归一化一条"证据/信号"。
167
+ * 接受字符串(自由文本)或对象;对象可带 kind/type、summary、ref、exitCode、stack、contradicts 等。
168
+ */
169
+ function normalizeEntry(entry, source) {
170
+ if (entry == null) return null;
171
+ if (typeof entry === "string") {
172
+ const text = collapsed(entry);
173
+ if (!text) return null;
174
+ return { kind: "note", summary: text, text, ref: null, at: null, exitCode: null, stack: null, contradicts: [], source };
175
+ }
176
+ if (typeof entry !== "object") {
177
+ const text = collapsed(entry);
178
+ if (!text) return null;
179
+ return { kind: "note", summary: text, text, ref: null, at: null, exitCode: null, stack: null, contradicts: [], source };
180
+ }
181
+ const kind = collapsed(entry.kind ?? entry.type ?? entry.category ?? "note") || "note";
182
+ const summary =
183
+ firstString(entry.summary, entry.title, entry.message, entry.detail, entry.reason, entry.body, entry.text, entry.note) ??
184
+ `(${kind} 证据,未提供摘要)`;
185
+ const parts = [summary, entry.detail, entry.reason, entry.message, entry.body, entry.text, entry.note]
186
+ .filter((v) => typeof v === "string" && v.trim())
187
+ .map(collapsed);
188
+ const contradictsRaw = entry.contradicts ?? entry.conflictsWith ?? entry.contradictsWith ?? null;
189
+ const contradicts = Array.isArray(contradictsRaw)
190
+ ? contradictsRaw.map((v) => collapsed(v)).filter(Boolean)
191
+ : (contradictsRaw ? [collapsed(contradictsRaw)] : []);
192
+ return {
193
+ kind: kind.toLowerCase(),
194
+ summary,
195
+ text: [...new Set(parts)].join(" · "),
196
+ ref: firstString(entry.ref, entry.identifier, entry.taskRef, entry.id, entry.source),
197
+ at: firstString(entry.at, entry.createdAt, entry.observedAt, entry.timestamp),
198
+ exitCode: asNumber(entry.exitCode ?? entry.exit_code ?? entry.status_code ?? entry.code),
199
+ stack: firstString(entry.stack, entry.stackTrace, entry.trace, entry.errorStack),
200
+ contradicts,
201
+ source,
202
+ };
203
+ }
204
+
205
+ /** 归一化一个列表(丢掉空项 + 按 kind|summary 去重)。 */
206
+ function normalizeList(list, source) {
207
+ if (!Array.isArray(list)) return [];
208
+ const out = [];
209
+ const seen = new Set();
210
+ for (const raw of list) {
211
+ const e = normalizeEntry(raw, source);
212
+ if (!e) continue;
213
+ const key = `${e.kind}|${e.summary}`;
214
+ if (seen.has(key)) continue;
215
+ seen.add(key);
216
+ out.push(e);
217
+ }
218
+ return out;
219
+ }
220
+
221
+ /** 归一化诊断条目(FR-79):接受单条对象或数组。 */
222
+ function normalizeDiagnoses(diagnosis) {
223
+ const list = Array.isArray(diagnosis) ? diagnosis : (diagnosis ? [diagnosis] : []);
224
+ return list
225
+ .filter((d) => d && typeof d === "object")
226
+ .map((d) => ({
227
+ // 诊断 kind 统一成连字符形式:FR-79 用下划线(block_loop / repeated_crash),FR-85 类别用连字符。
228
+ kind: collapsed(d.kind ?? d.type ?? "").toLowerCase().replace(/_/g, "-"),
229
+ title: firstString(d.title, d.summary) ?? "",
230
+ detail: firstString(d.detail, d.reason) ?? "",
231
+ count: asNumber(d.count ?? d.recurrences ?? d.recurrence),
232
+ ref: firstString(d.ref, d.taskRef, d.identifier),
233
+ raw: d,
234
+ }))
235
+ .filter((d) => d.kind || d.title || d.detail);
236
+ }
237
+
238
+ /** 组装判定上下文(所有取数都做防御,任意字段缺失都不抛错)。 */
239
+ export function buildHumanReviewContext(input = {}) {
240
+ const src = input && typeof input === "object" ? input : {};
241
+ const evidence = normalizeList(src.evidence, "evidence");
242
+ const signals = normalizeList(src.signals ?? src.signal, "signals");
243
+ // -75 P2:**结构化退出码字段**是一等证据。上游(CLI 执行器 / 尝试记录)本来就是数字,
244
+ // 不能要求接线方「先把数字写成一句带值的话」——那是靠约定,不是靠代码。
245
+ // 这里把 `exitCode` / `exitCodes`(数字或数字数组)折成结构证据;
246
+ // kind 用中性的 `exit-code`(**不用** `failure`),否则 `退出码 0` 会被"kind=failure"直接当失败,绕回 P1。
247
+ const exitEvidence = normalizeExitCodes(
248
+ src.exitCode ?? src.exitCodes ?? src.exit_code ?? src.exit_codes ?? src.status_code ?? src.statusCode ?? src.code,
249
+ ).map((code) => ({ kind: "exit-code", summary: `退出码 ${code}`, text: `退出码 ${code}`, ref: null, at: null, exitCode: code, stack: null, contradicts: [], source: "exit-code" }));
250
+ const pool = [...evidence, ...signals, ...exitEvidence];
251
+ const task = src.task && typeof src.task === "object" ? src.task : {};
252
+ const requirementItem = src.requirementItem && typeof src.requirementItem === "object" ? src.requirementItem : null;
253
+ const upstreamClauses = Array.isArray(src.upstreamClauses)
254
+ ? src.upstreamClauses.filter((c) => c && typeof c === "object")
255
+ : [];
256
+ return {
257
+ task,
258
+ requirementItem,
259
+ upstreamClauses,
260
+ diagnoses: normalizeDiagnoses(src.diagnosis ?? src.diagnoses),
261
+ evidence,
262
+ signals,
263
+ pool,
264
+ blockKind: src.blockKind != null ? collapsed(src.blockKind) || null : (task.blockKind ?? null),
265
+ blockRecurrences: asNumber(src.blockRecurrences ?? src.recurrences ?? task.blockRecurrences) ?? 0,
266
+ downstream: normalizeRefs(src.downstream ?? src.blockedDownstream ?? src.downstreamRefs),
267
+ crossModuleContracts: normalizeRefs(src.crossModuleContracts),
268
+ // FR-85(2026-10-18):**显式申报**的类别(来自升级门读到的结构化声明,见 diagnostics.declarationEvidence)。
269
+ // 它是"判定成立"的直接依据 —— 申报了哪一类,就按那一类出结论(不让关键词误判把类别抢走)。
270
+ declaration: HUMAN_REVIEW_CATEGORIES.includes(collapsed(src.declaration ?? "").toLowerCase().replace(/_/g, "-"))
271
+ ? collapsed(src.declaration).toLowerCase().replace(/_/g, "-")
272
+ : null,
273
+ flags: {
274
+ contradiction: src.contradiction === true || src.requirementDrift === true,
275
+ architecture: src.touchesBaselineArchitecture === true,
276
+ crossModuleContracts: normalizeRefs(src.crossModuleContracts).length > 0,
277
+ upstream: src.acceptanceUnsatisfiable === true,
278
+ },
279
+ };
280
+ }
281
+
282
+ function normalizeRefs(list) {
283
+ if (!Array.isArray(list)) return [];
284
+ return [...new Set(list.map((v) => collapsed(v)).filter(Boolean))];
285
+ }
286
+
287
+ /** 归一化退出码入参:接受单个数字 / 数字字符串 / 数组;丢掉非数字项(不做"猜")。 */
288
+ function normalizeExitCodes(raw) {
289
+ if (raw == null) return [];
290
+ const list = Array.isArray(raw) ? raw : [raw];
291
+ return list
292
+ .map((v) => (v && typeof v === "object" ? (v.exitCode ?? v.code ?? v.status_code ?? null) : v))
293
+ .map((v) => asNumber(v))
294
+ .filter((v) => v != null);
295
+ }
296
+
297
+ const hasText = (entry, re) => re.test(entry.text);
298
+ const kindIn = (entry, kinds) => kinds.includes(entry.kind);
299
+ const mentions = (entries, re) => entries.filter((e) => hasText(e, re));
300
+
301
+ /** 由非证据来源(诊断/状态/显式标志)合成一条证据,保证"有判定必有证据"。 */
302
+ function synth(kind, summary, { ref = null, at = null, exitCode = null } = {}) {
303
+ return { kind, summary, text: summary, ref, at, exitCode, stack: null, contradicts: [], source: "synthesized" };
304
+ }
305
+
306
+ /**
307
+ * 退出码判定(-75 P1/P2)。
308
+ *
309
+ * @returns {boolean|null} `true`=非零(=失败证据)· `false`=**显式为零**(成功,绝不当作失败证据)· `null`=未提及(交给其它判据)
310
+ *
311
+ * 结构化 `exitCode` 数值字段优先(上游执行器 / 尝试记录本来就是数字);
312
+ * 文本路径必须**带值**才算数 —— 只有"出现退出码这个词"不构成失败证据。
313
+ */
314
+ function exitCodeVerdict(entry) {
315
+ if (entry?.exitCode != null) return Number(entry.exitCode) !== 0;
316
+ const text = String(entry?.text ?? "");
317
+ EXIT_CODE_RE.lastIndex = 0;
318
+ let m;
319
+ let sawAny = false;
320
+ let sawNonZero = false;
321
+ while ((m = EXIT_CODE_RE.exec(text)) !== null) {
322
+ sawAny = true;
323
+ if (Number(m[1]) !== 0) sawNonZero = true;
324
+ }
325
+ if (!sawAny) return null;
326
+ return sawNonZero;
327
+ }
328
+
329
+ /**
330
+ * ① 真实 bug 阻塞:同一 bug 重复复发 **且** 有失败证据(退出码 / 栈)。
331
+ * 只有一边(只复发没证据 / 只有一次失败)→ 不命中,走"证据不足"降级。
332
+ */
333
+ function detectRealBugBlocked(ctx) {
334
+ // kind 比对用**连字符**形态:`normalizeDiagnoses` 已把 FR-79 的下划线写法(block_loop / …)归一化成连字符,
335
+ // 此处**不要**再反向归一化一次(2026-10-18 复核:那一层是冗余的)。
336
+ const recDiag = ctx.diagnoses.filter((d) => ["block-loop", "repeated-crash", "repeated-failure"].includes(d.kind));
337
+ const recEntries = ctx.pool.filter(
338
+ (e) =>
339
+ kindIn(e, ["recurrence", "repeat", "repeated", "same-bug", "block-loop", "repeat-failure"]) ||
340
+ hasText(e, RECURRENCE_TEXT_RE),
341
+ );
342
+ const recurrence = [];
343
+ if (ctx.blockRecurrences >= HUMAN_REVIEW_RECURRENCE_THRESHOLD) {
344
+ recurrence.push(
345
+ synth("recurrence", `同一 bug 已复发 ${ctx.blockRecurrences} 次(阈值 ${HUMAN_REVIEW_RECURRENCE_THRESHOLD})${ctx.blockKind ? `,阻断类型=${ctx.blockKind}` : ""}`),
346
+ );
347
+ }
348
+ for (const d of recDiag) {
349
+ const n = d.count ?? null;
350
+ recurrence.push(
351
+ synth(
352
+ "recurrence",
353
+ `诊断「${d.kind}」${n != null && n >= HUMAN_REVIEW_RECURRENCE_THRESHOLD ? `计数 ${n}` : ""}${d.title ? `:${d.title}` : ""}${d.detail ? `(${collapsed(d.detail)})` : ""}`.trim(),
354
+ { ref: d.ref },
355
+ ),
356
+ );
357
+ }
358
+ recurrence.push(...recEntries);
359
+
360
+ const failure = ctx.pool.filter(
361
+ (e) =>
362
+ exitCodeVerdict(e) === true || // -75 P1/P2:退出码**非零**才算失败(结构化字段或带值文本)
363
+ Boolean(e.stack) ||
364
+ BARE_STACK_RE.test(String(e.text ?? "")) || // -75 P3:裸栈/异常名(`TypeError: ...`、`at f (x.mjs:1:2)`)
365
+ kindIn(e, ["failure", "error", "crash", "failed-test", "test-failure", "exception"]) ||
366
+ hasText(e, FAILURE_TEXT_RE),
367
+ );
368
+ const failDiag = ctx.diagnoses.filter((d) => ["repeated-crash", "repeated-failure"].includes(d.kind));
369
+ for (const d of failDiag) {
370
+ failure.push(synth("failure", `诊断「${d.kind}」为失败类:${d.title || collapsed(d.detail) || d.kind}`, { ref: d.ref }));
371
+ }
372
+
373
+ const matched = recurrence.length > 0 && failure.length > 0;
374
+ return {
375
+ category: "real-bug-blocked",
376
+ matched,
377
+ evidence: dedupe([...recurrence, ...failure]),
378
+ reasons: matched
379
+ ? [
380
+ `同一 bug 重复复发(${recurrence.length} 条复发证据)`,
381
+ `有失败证据(${failure.length} 条:退出码/栈/失败记录)`,
382
+ ]
383
+ : [],
384
+ missing: [
385
+ ...(recurrence.length ? [] : [`同一 bug 重复复发(复发 ≥ ${HUMAN_REVIEW_RECURRENCE_THRESHOLD} 次,或 block_loop/repeated_crash/repeated_failure 诊断)`]),
386
+ ...(failure.length ? [] : ["失败证据(退出码 ≠ 0 或栈)"]),
387
+ ],
388
+ observed: { recurrence: recurrence.length, failure: failure.length },
389
+ };
390
+ }
391
+
392
+ /** ② 需求异化:任务描述与需求条目 / 上游 FR 条款**相互矛盾**(矛盾必须是显式申报的证据)。 */
393
+ function detectRequirementDrift(ctx) {
394
+ const contradiction = ctx.pool.filter(
395
+ (e) => kindIn(e, ["contradiction", "conflict", "requirement-drift", "drift", "mismatch"]) || e.contradicts.length > 0 || hasText(e, CONTRADICTION_TEXT_RE),
396
+ );
397
+ const driftDiag = ctx.diagnoses.filter((d) => d.kind === "requirement-drift");
398
+ const evidence = [...contradiction];
399
+ for (const d of driftDiag) {
400
+ evidence.push(synth("contradiction", `诊断「requirement_drift」:${d.title || collapsed(d.detail) || "需求异化"}`, { ref: d.ref }));
401
+ }
402
+ if (ctx.flags.contradiction) {
403
+ evidence.push(synth("contradiction", "调用方显式申报:任务口径与需求条目相互矛盾"));
404
+ }
405
+ const itemRef = ctx.requirementItem?.identifier ?? ctx.requirementItem?.ref ?? null;
406
+ const matched = evidence.length > 0;
407
+ return {
408
+ category: "requirement-drift",
409
+ matched,
410
+ evidence: dedupe(evidence),
411
+ reasons: matched
412
+ ? [`任务描述与需求条目/上游 FR 条款相互矛盾(${evidence.length} 条矛盾证据${itemRef ? `,涉及需求条目 ${itemRef}` : ""})`]
413
+ : [],
414
+ missing: matched ? [] : ["任务描述与需求条目/上游 FR 条款相互矛盾(需显式矛盾证据:contradicts 字段或矛盾类信号)"],
415
+ observed: { contradiction: contradiction.length },
416
+ };
417
+ }
418
+
419
+ /** ③ 架构变化:实现需要改动**基线架构**或**跨模块契约**。 */
420
+ function detectArchitectureChange(ctx) {
421
+ const arch = ctx.pool.filter(
422
+ (e) => kindIn(e, ["architecture", "architecture-change", "baseline-architecture", "cross-module-contract", "contract-change", "structural"]) || hasText(e, ARCHITECTURE_TEXT_RE),
423
+ );
424
+ const diag = ctx.diagnoses.filter((d) => d.kind === "architecture-change");
425
+ const evidence = [...arch];
426
+ for (const d of diag) {
427
+ evidence.push(synth("architecture", `诊断「architecture_change」:${d.title || collapsed(d.detail) || "架构变化"}`, { ref: d.ref }));
428
+ }
429
+ if (ctx.flags.architecture) evidence.push(synth("architecture", "调用方显式申报:实现需要改动基线架构"));
430
+ if (ctx.flags.crossModuleContracts) {
431
+ evidence.push(synth("cross-module-contract", `涉及跨模块契约改动:${(ctx.crossModuleContracts ?? []).join("、")}`.trim()));
432
+ }
433
+ const matched = evidence.length > 0;
434
+ return {
435
+ category: "architecture-change",
436
+ matched,
437
+ evidence: dedupe(evidence),
438
+ reasons: matched ? [`实现需要改动基线架构或跨模块契约(${evidence.length} 条架构证据)`] : [],
439
+ missing: matched ? [] : ["实现需要改动基线架构或跨模块契约"],
440
+ observed: { architecture: arch.length },
441
+ };
442
+ }
443
+
444
+ /** ④ 与上游需求不符:**验收口径无法满足**或**需求已被取代**。 */
445
+ function detectUpstreamMismatch(ctx) {
446
+ const up = ctx.pool.filter(
447
+ (e) => kindIn(e, ["upstream-mismatch", "acceptance-unsatisfiable", "superseded", "replaced", "obsolete", "deprecated"]) || hasText(e, UPSTREAM_TEXT_RE),
448
+ );
449
+ const diag = ctx.diagnoses.filter((d) => d.kind === "upstream-mismatch");
450
+ const evidence = [...up];
451
+ for (const d of diag) {
452
+ evidence.push(synth("upstream-mismatch", `诊断「upstream_mismatch」:${d.title || collapsed(d.detail) || "与上游需求不符"}`, { ref: d.ref }));
453
+ }
454
+ if (ctx.flags.upstream) evidence.push(synth("acceptance-unsatisfiable", "调用方显式申报:验收口径无法满足"));
455
+
456
+ const itemStatus = collapsed(ctx.requirementItem?.status ?? "").toLowerCase();
457
+ if (SUPERSEDED_REQUIREMENT_STATUSES.includes(itemStatus)) {
458
+ evidence.push(
459
+ synth("superseded", `需求条目 ${ctx.requirementItem.identifier ?? ctx.requirementItem.id ?? ""} 状态为 ${itemStatus}(已被取代/作废)`.trim()),
460
+ );
461
+ }
462
+ for (const c of ctx.upstreamClauses) {
463
+ const st = collapsed(c.status ?? "").toLowerCase();
464
+ if (!SUPERSEDED_REQUIREMENT_STATUSES.includes(st)) continue;
465
+ evidence.push(synth("superseded", `上游条款 ${c.ref ?? c.identifier ?? c.id ?? ""} 状态为 ${st}(已被取代/作废)`.trim()));
466
+ }
467
+
468
+ const matched = evidence.length > 0;
469
+ return {
470
+ category: "upstream-mismatch",
471
+ matched,
472
+ evidence: dedupe(evidence),
473
+ reasons: matched ? [`验收口径无法满足或需求已被取代(${evidence.length} 条上游不符证据)`] : [],
474
+ missing: matched ? [] : ["验收口径无法满足或需求已被取代(含需求/条款状态为 superseded)"],
475
+ observed: { upstream: up.length },
476
+ };
477
+ }
478
+
479
+ function dedupe(entries) {
480
+ const out = [];
481
+ const seen = new Set();
482
+ for (const e of entries) {
483
+ if (!e || !e.summary) continue;
484
+ const key = `${e.kind}|${e.summary}`;
485
+ if (seen.has(key)) continue;
486
+ seen.add(key);
487
+ out.push(e);
488
+ }
489
+ return out;
490
+ }
491
+
492
+ /** 四类判据的求值顺序(= HUMAN_REVIEW_CATEGORIES 顺序 = 优先级)。 */
493
+ const DETECTORS = Object.freeze([
494
+ detectRealBugBlocked,
495
+ detectRequirementDrift,
496
+ detectArchitectureChange,
497
+ detectUpstreamMismatch,
498
+ ]);
499
+
500
+ /** 类别 → 候选处置(候选**不是**自动动作:全部 needsHuman=true,等人拍板)。 */
501
+ export const CANDIDATE_ACTIONS = Object.freeze({
502
+ "real-bug-blocked": Object.freeze([
503
+ { id: "fix-then-reopen", label: "人确认修复方案后重开原任务", detail: "先定位同一 bug 的根因并给出修复方案,人确认后清复发计数、重开原任务。", needsHuman: true },
504
+ { id: "change-approach", label: "更换实现路径或降级依赖", detail: "同一路径反复失败时,改走等价实现或换依赖版本,避免在死路上重试。", needsHuman: true },
505
+ { id: "adjust-acceptance", label: "调整验收口径(若 bug 系环境导致)", detail: "若失败证据表明是环境/工具链问题而非真实 bug,需人改验收口径后重开。", needsHuman: true },
506
+ { id: "escalate-capability", label: "转派给具备该能力的执行者", detail: "若属能力缺口(capability),换执行者或换执行器后重开。", needsHuman: true },
507
+ ]),
508
+ "requirement-drift": Object.freeze([
509
+ { id: "follow-requirement", label: "以需求条目为准,改写任务描述后重开", detail: "任务口径偏离需求条目:按需求条目改写任务描述(保留原始证据)再重开。", needsHuman: true },
510
+ { id: "amend-requirement", label: "以任务为准,修订需求条目并留变更记录", detail: "若实现过程中确认需求该变,走需求变更(新增变更记录、不改历史条款原文)后重开。", needsHuman: true },
511
+ { id: "split-conflict", label: "把冲突部分拆成新任务", detail: "原任务先按无争议部分推进,冲突部分单独立项后再定。", needsHuman: true },
512
+ ]),
513
+ "architecture-change": Object.freeze([
514
+ { id: "approve-architecture", label: "先立项架构变更,再回填任务", detail: "改动基线架构/跨模块契约需先出方案(ADR/评审)并获人批准,之后按新口径重开任务。", needsHuman: true },
515
+ { id: "narrow-scope", label: "缩小实现范围以绕开架构改动", detail: "在不动基线架构的前提下找到最小可用实现,作为过渡方案。", needsHuman: true },
516
+ { id: "review-then-reopen", label: "走评审门后再重开", detail: "把架构改动提交评审;评审通过前该任务及其下游保持受阻。", needsHuman: true },
517
+ ]),
518
+ "upstream-mismatch": Object.freeze([
519
+ { id: "reopen-under-upstream", label: "按上游新口径重开原任务(保留原始证据)", detail: "上游条款已变更/被取代:按新口径重建验收标准后重开,旧的尝试与证据只做保留不做删除。", needsHuman: true },
520
+ { id: "request-clarification", label: "请求上游澄清或等待上游定稿", detail: "上游口径本身未定:向人(上游)发起澄清,未定稿前不自动推进。", needsHuman: true },
521
+ { id: "close-as-superseded", label: "关闭任务并标注取代关系", detail: "若该任务已被上游需求取代,标注取代关系后关闭(不置 done,走人工结论)。", needsHuman: true },
522
+ ]),
523
+ });
524
+
525
+ /** 取某类别的候选处置(拷贝,避免调用方改到常量)。 */
526
+ export function candidateActionsFor(category) {
527
+ const list = CANDIDATE_ACTIONS[String(category ?? "")] ?? [];
528
+ return list.map((a) => ({ ...a, category: String(category) }));
529
+ }
530
+
531
+ /** 由判定上下文求"阻塞边界"(保留调用方给的 downstream;缺省见 DEFAULT_BLOCK_BOUNDARY)。 */
532
+ export function resolveBlockBoundary(input = {}) {
533
+ const src = input && typeof input === "object" ? input : {};
534
+ const downstream = normalizeRefs(src.downstream ?? src.blockedDownstream ?? src.downstreamRefs);
535
+ const explicit = typeof src.blockBoundary === "string" ? collapsed(src.blockBoundary) : (src.blockBoundary && typeof src.blockBoundary === "object" ? src.blockBoundary : null);
536
+ const base = {
537
+ scope: explicit?.scope ?? (downstream.length ? "self-and-downstream" : DEFAULT_BLOCK_BOUNDARY.scope),
538
+ description: explicit?.description ?? DEFAULT_BLOCK_BOUNDARY.description,
539
+ downstream,
540
+ autoRetry: false,
541
+ autoAdvance: false,
542
+ };
543
+ if (explicit?.autoRetry === true || explicit?.autoAdvance === true) {
544
+ // 人工校验未结论前**不允许**自动重派/推进:显式要求也被拒绝(红线优先)。
545
+ base.rejectedAutoFlags = true;
546
+ }
547
+ return base;
548
+ }
549
+
550
+ /** 阻塞边界 → 可读文本(草案正文第四段)。 */
551
+ export function blockBoundaryText(boundary) {
552
+ const b = boundary && typeof boundary === "object" ? boundary : {};
553
+ const downstream = Array.isArray(b.downstream) ? b.downstream.filter(Boolean) : [];
554
+ const lines = [
555
+ `影响域=${b.scope ?? DEFAULT_BLOCK_BOUNDARY.scope}`,
556
+ collapsed(b.description) || DEFAULT_BLOCK_BOUNDARY.description,
557
+ downstream.length ? `被卡住的下游任务:${downstream.join("、")}` : "被卡住的下游任务:以依赖图解析(本草案未携带明细)",
558
+ "自动重派:禁止;自动推进:禁止;人工校验出结论后由人放行。",
559
+ ];
560
+ return lines.join("\n");
561
+ }
562
+
563
+ /**
564
+ * 四类判定(纯函数)。
565
+ *
566
+ * @param {object} input
567
+ * · diagnosis FR-79 诊断条目(对象或数组)
568
+ * · blockKind FR-80 阻断分类
569
+ * · signals 自由文本/证据数组(字符串或对象)
570
+ * · evidence 证据列表(对象:kind/summary/ref/exitCode/stack/contradicts…)
571
+ * · 可选:task / requirementItem / upstreamClauses / blockRecurrences / downstream /
572
+ * contradiction / touchesBaselineArchitecture / crossModuleContracts / acceptanceUnsatisfiable
573
+ * @returns {{category:string|null, confident:boolean, confidenceReason:string, evidence:object[], candidateActions:object[], categoryLabel:string|null, missing:string[], observed:object}}
574
+ */
575
+ export function classifyHumanReview(input = {}) {
576
+ const ctx = buildHumanReviewContext(input);
577
+ const evaluations = DETECTORS.map((fn) => fn(ctx));
578
+ // FR-85(2026-10-18):**显式申报优先** —— 申报本身即"判定成立",
579
+ // 按申报类别出结论,避免申报正文里的关键词把类别判到别的 detector 去(例如"架构变化"正文里写了"矛盾")。
580
+ const declared = ctx.declaration ? (evaluations.find((e) => e.category === ctx.declaration) ?? null) : null;
581
+ const hit = declared
582
+ ? { ...declared, matched: true, reasons: [`人工校验显式申报:${categoryLabel(declared.category)}`, ...declared.reasons], missing: [] }
583
+ : (evaluations.find((e) => e.matched && e.evidence.length > 0) ?? null);
584
+
585
+ if (!hit) {
586
+ const observed = {
587
+ failure: evaluations[0].observed.failure,
588
+ recurrence: evaluations[0].observed.recurrence,
589
+ contradiction: evaluations[1].observed.contradiction,
590
+ architecture: evaluations[2].observed.architecture,
591
+ upstream: evaluations[3].observed.upstream,
592
+ };
593
+ const seenAnything = Object.values(observed).some((n) => n > 0);
594
+ const confidenceReason = [
595
+ "证据不足:四类判据均未命中,category=null(不臆断)。",
596
+ seenAnything
597
+ ? `已观察到:失败证据 ${observed.failure} 条 / 复发证据 ${observed.recurrence} 条 / 需求矛盾证据 ${observed.contradiction} 条 / 架构证据 ${observed.architecture} 条 / 上游不符证据 ${observed.upstream} 条。`
598
+ : "输入未提供任何可用证据或信号。",
599
+ `未满足的关键条件:${evaluations.map((e) => `${categoryLabel(e.category)}=${e.missing[0]}`).join(";")}。`,
600
+ ].join(" ");
601
+ return {
602
+ category: null,
603
+ categoryLabel: null,
604
+ confident: false,
605
+ confidenceReason,
606
+ evidence: dedupe(ctx.pool),
607
+ candidateActions: [],
608
+ missing: evaluations.flatMap((e) => e.missing),
609
+ observed,
610
+ };
611
+ }
612
+
613
+ const otherHits = evaluations.filter((e) => e.matched && e.category !== hit.category).map((e) => categoryLabel(e.category));
614
+ const confidenceReason = [
615
+ `判为「${categoryLabel(hit.category)}」:${hit.reasons.join(";")}。`,
616
+ otherHits.length ? `另有同类命中(未取用,按优先级取首命中):${otherHits.join("、")}。` : "",
617
+ hit.category === "real-bug-blocked" && ctx.blockKind ? `阻断类型=${ctx.blockKind}(FR-80)。` : "",
618
+ ]
619
+ .filter(Boolean)
620
+ .join(" ");
621
+
622
+ return {
623
+ category: hit.category,
624
+ categoryLabel: categoryLabel(hit.category),
625
+ confident: true,
626
+ confidenceReason,
627
+ evidence: hit.evidence,
628
+ candidateActions: candidateActionsFor(hit.category),
629
+ missing: [],
630
+ observed: {
631
+ failure: evaluations[0].observed.failure,
632
+ recurrence: evaluations[0].observed.recurrence,
633
+ contradiction: evaluations[1].observed.contradiction,
634
+ architecture: evaluations[2].observed.architecture,
635
+ upstream: evaluations[3].observed.upstream,
636
+ },
637
+ };
638
+ }
639
+
640
+ /** 证据 → 草案正文行。 */
641
+ function evidenceLines(evidence) {
642
+ const list = Array.isArray(evidence) ? evidence : [];
643
+ if (!list.length) return ["(无)"];
644
+ return list.map((e, i) => {
645
+ const bits = [`[${e.kind ?? "note"}]`, e.summary ?? collapsed(e.text) ?? "(无摘要)"];
646
+ if (e.ref) bits.push(`来源=${e.ref}`);
647
+ if (e.at) bits.push(`时间=${e.at}`);
648
+ if (e.exitCode != null) bits.push(`退出码=${e.exitCode}`);
649
+ if (e.stack) bits.push(`栈=${collapsed(e.stack).slice(0, 160)}`);
650
+ return `${i + 1}. ${bits.join(" ")}`;
651
+ });
652
+ }
653
+
654
+ /** 候选处置 → 草案正文行。 */
655
+ function actionLines(actions) {
656
+ const list = Array.isArray(actions) ? actions : [];
657
+ if (!list.length) return ["(无)"];
658
+ return list.map((a, i) => `${i + 1}. ${a.label ?? a.id}${a.detail ? `:${a.detail}` : ""}(需人决策)`);
659
+ }
660
+
661
+ /**
662
+ * 构造 `human_review` 任务草案(纯函数,不落库)。
663
+ *
664
+ * `input` 可直接是 classifyHumanReview 的入参(内含 task/description 等),
665
+ * 也可显式传 `input.classification`(已判定结果)以复用同一次判定。
666
+ * **判定不置信时抛错**——证据不足不得构造人工校验任务(FR-85:绝不臆断)。
667
+ *
668
+ * @returns {{title:string, description:string, category:string, categoryLabel:string,
669
+ * evidence:object[], candidateActions:object[], blockBoundary:object, forbiddenForExecution:true}}
670
+ */
671
+ export function buildHumanReviewDraft(input = {}) {
672
+ const src = input && typeof input === "object" ? input : {};
673
+ const classification = src.classification && typeof src.classification === "object" ? src.classification : classifyHumanReview(src);
674
+ if (!classification.confident || !classification.category) {
675
+ throw new Error(`证据不足,不得构造人工校验任务草案:${classification.confidenceReason ?? "四类判据均未命中"}`);
676
+ }
677
+ const category = classification.category;
678
+ const label = categoryLabel(category);
679
+ const task = src.task && typeof src.task === "object" ? src.task : {};
680
+ const taskRef = firstString(task.identifier, src.taskRef, src.identifier, src.ref) ?? "(未标明任务)";
681
+ const taskTitle = firstString(task.title, src.title, src.taskTitle) ?? "";
682
+ const evidence = dedupe(Array.isArray(classification.evidence) ? classification.evidence : []);
683
+ const candidateActions = Array.isArray(classification.candidateActions) && classification.candidateActions.length
684
+ ? classification.candidateActions
685
+ : candidateActionsFor(category);
686
+ const blockBoundary = resolveBlockBoundary({ ...src, blockBoundary: src.blockBoundary ?? src.boundary });
687
+
688
+ const title = `【人工校验】${label} · ${taskRef}${taskTitle ? ` ${taskTitle}` : ""}`;
689
+ const description = [
690
+ "【人工校验任务(FR-85 人在环升级门)】",
691
+ `原任务:${taskRef}${taskTitle ? `(${taskTitle})` : ""}`,
692
+ `判定结论:${label}(category=${category})`,
693
+ "",
694
+ "一、判定类别",
695
+ `${label}(category=${category})`,
696
+ `判定依据:${classification.confidenceReason}`,
697
+ "",
698
+ "二、证据",
699
+ evidenceLines(evidence).join("\n"),
700
+ "",
701
+ "三、候选处置",
702
+ actionLines(candidateActions).join("\n"),
703
+ "",
704
+ "四、阻塞边界",
705
+ blockBoundaryText(blockBoundary),
706
+ "",
707
+ EXECUTION_RED_LINE,
708
+ "人工校验出结论后,请据结论放行原任务(保留原始证据,不删除既有尝试记录)。",
709
+ ].join("\n");
710
+
711
+ return {
712
+ title,
713
+ description,
714
+ category,
715
+ categoryLabel: label,
716
+ evidence,
717
+ candidateActions,
718
+ blockBoundary,
719
+ forbiddenForExecution: true,
720
+ };
721
+ }
722
+
723
+ const nonEmptyStr = (v) => typeof v === "string" && v.trim().length > 0;
724
+
725
+ /**
726
+ * 校验 `human_review` 草案四要素(FR-85 验收)。
727
+ * 缺**类别 / 证据 / 候选处置 / 阻塞边界**任一项即 `ok=false` 且 errors 说明缺哪一项。
728
+ *
729
+ * @returns {{ok:boolean, errors:string[]}}
730
+ */
731
+ export function validateHumanReviewDraft(draft) {
732
+ if (!draft || typeof draft !== "object" || Array.isArray(draft)) {
733
+ return { ok: false, errors: ["draft 必须是对象"] };
734
+ }
735
+ const errors = [];
736
+ const category = String(draft.category ?? "").trim();
737
+ if (!category) errors.push("缺少判定类别:category 必填");
738
+ else if (!HUMAN_REVIEW_CATEGORIES.includes(category)) {
739
+ errors.push(`判定类别非法:category 必须是 ${HUMAN_REVIEW_CATEGORIES.join(" / ")} 之一(当前 ${category})`);
740
+ }
741
+
742
+ const evidence = Array.isArray(draft.evidence)
743
+ ? draft.evidence.filter((e) => (nonEmptyStr(e) ? true : Boolean(e && typeof e === "object" && (nonEmptyStr(e.summary) || nonEmptyStr(e.text) || nonEmptyStr(e.kind)))))
744
+ : [];
745
+ if (evidence.length === 0) errors.push("缺少证据:evidence 至少 1 条(判定不得无凭)");
746
+
747
+ const actions = Array.isArray(draft.candidateActions)
748
+ ? draft.candidateActions.filter((a) => a && typeof a === "object" && (nonEmptyStr(a.id) || nonEmptyStr(a.label)))
749
+ : [];
750
+ if (actions.length === 0) errors.push("缺少候选处置:candidateActions 至少 1 条");
751
+
752
+ const boundary = draft.blockBoundary;
753
+ const boundaryOk =
754
+ nonEmptyStr(boundary) ||
755
+ (Boolean(boundary) && typeof boundary === "object" && !Array.isArray(boundary) && (nonEmptyStr(boundary.description) || nonEmptyStr(boundary.scope)));
756
+ if (!boundaryOk) errors.push("缺少阻塞边界:blockBoundary 必须是非空字符串,或含 description/scope 的对象");
757
+
758
+ if (draft.forbiddenForExecution === false) {
759
+ errors.push("执行侧红线被破坏:forbiddenForExecution 不得为 false(执行侧不得认领、不得置 done)");
760
+ }
761
+
762
+ return { ok: errors.length === 0, errors };
763
+ }
764
+
765
+ /** 便捷入口:判定 + 构造 + 校验一次到位(判定不置信时抛错,同 buildHumanReviewDraft)。 */
766
+ export function planHumanReview(input = {}) {
767
+ const classification = classifyHumanReview(input);
768
+ const draft = buildHumanReviewDraft({ ...input, classification });
769
+ const validation = validateHumanReviewDraft(draft);
770
+ return { classification, draft, validation };
771
+ }
772
+
773
+ export default { classifyHumanReview, buildHumanReviewDraft, validateHumanReviewDraft, planHumanReview };