dsh-workplan 2.3.2 → 3.0.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/lib/client.js CHANGED
@@ -23,7 +23,6 @@ window.__ModuleLoader__.load({
23
23
  "groupEnded": "已结束",
24
24
  "groupLiveHint": "还没结束,正在或即将推进",
25
25
  "groupDoneHint": "已全部完成并收尾",
26
- "groupEndedHint": "这一轮已经停了,没有东西在跑;说「续跑」可继续推进",
27
26
  "groupCollapse": "收起",
28
27
  "groupExpand": "展开",
29
28
  "groupNeeds": "需处理",
@@ -93,6 +92,17 @@ window.__ModuleLoader__.load({
93
92
  "closed": "无需动作"
94
93
  },
95
94
  "handoffs": "跨部门需求",
95
+ "delegates": "第三层(全球顶尖专家)",
96
+ "delegateExpert": "专家",
97
+ "delegateMember": "专家",
98
+ "delegateStatus": {
99
+ "running": "执行中",
100
+ "done": "已完成",
101
+ "failed": "失败",
102
+ "timeout": "超时",
103
+ "rejected": "派发被拒",
104
+ "blocked": "受阻"
105
+ },
96
106
  "dept": {
97
107
  "engineering": "工程研发",
98
108
  "research": "研究分析",
@@ -235,6 +245,11 @@ window.__ModuleLoader__.load({
235
245
  "noticeChannelAwaiting": "等待观测",
236
246
  "noticeChannelNotObserved": "未观测到送达",
237
247
  "reason": "原因",
248
+ "leaderEstimateFull": "负责人任务时长=全部下属开工预估之和:{minutes} 分钟({reported}/{expected} 已上报)|判据层完成目标 ≤10 分钟:达标须同时满足事前预估之和与事后单次尝试墙钟均 ≤10 分钟",
249
+ "leaderEstimatePartial": "下属开工预估部分和:{minutes} 分钟({reported}/{expected} 已上报{gaps})|预估未报齐只显示部分和,不得视为「简单判据达标」(判据层完成目标 ≤10 分钟)",
250
+ "leaderEstimateOver": "⚠ 超简单判据:事前预估 {minutes} 分钟 > 10 分钟完成目标——请事前拆分,或经用户明确批准并留痕(无留痕=未批准,不得视为达标)",
251
+ "leaderEstimateMissing": ",缺:{names}",
252
+ "leaderEstimateFailed": ",报送失败:{names}",
238
253
  },
239
254
  "en": {
240
255
  "groupLive": "In progress",
@@ -295,6 +310,7 @@ window.__ModuleLoader__.load({
295
310
  "paused": "Paused (budget spent)",
296
311
  "degraded": "Planning failed",
297
312
  "cancelled": "Cancelled",
313
+ "superseded": "Taken over by another plan",
298
314
  "ended": "Ended (resumable)"
299
315
  },
300
316
  "status": {
@@ -310,6 +326,17 @@ window.__ModuleLoader__.load({
310
326
  "closed": "No action"
311
327
  },
312
328
  "handoffs": "Cross-team needs",
329
+ "delegates": "Third tier (experts/members)",
330
+ "delegateExpert": "expert",
331
+ "delegateMember": "member",
332
+ "delegateStatus": {
333
+ "running": "running",
334
+ "done": "done",
335
+ "failed": "failed",
336
+ "timeout": "timeout",
337
+ "rejected": "rejected",
338
+ "blocked": "blocked"
339
+ },
313
340
  "dept": {
314
341
  "engineering": "Engineering",
315
342
  "research": "Research",
@@ -452,6 +479,11 @@ window.__ModuleLoader__.load({
452
479
  "noticeChannelAwaiting": "Awaiting observation",
453
480
  "noticeChannelNotObserved": "Delivery not observed",
454
481
  "reason": "reason",
482
+ "leaderEstimateFull": "Leader task duration = sum of all delegate start estimates: {minutes} min ({reported}/{expected} reported) | Criterion layer: completion target <= 10 min, met only when both the ex-ante estimate sum and the ex-post single-attempt wall clock are <= 10 min",
483
+ "leaderEstimatePartial": "Partial sum of delegate start estimates: {minutes} min ({reported}/{expected} reported{gaps}) | Estimates incomplete: partial sum only, never a met criterion (completion target <= 10 min)",
484
+ "leaderEstimateOver": "OVER criterion: ex-ante estimate {minutes} min > 10 min completion target - split the work or obtain explicit user approval with an audit trail (no trail = not approved, never a met criterion)",
485
+ "leaderEstimateMissing": ", missing: {names}",
486
+ "leaderEstimateFailed": ", delivery failed: {names}",
455
487
  }
456
488
  };
457
489
  function flattenLocale(source, prefix = '', out = {}) {
@@ -1547,7 +1579,9 @@ window.__ModuleLoader__.load({
1547
1579
  * - 计划定义:estimateMinutes(预估)、timeoutMs(协商上限)、reasoningEffort(推理等级);
1548
1580
  * - 状态行:startedAt/deadlineAt(协商截止)、timeJournal(延期/预告历史)、
1549
1581
  * timeNotice(开工预告)、timeWarning(到点预警)、noticeChannel(子→主通道是否送达)、
1550
- * pendingAdjudication(到点后的待裁决标记)。
1582
+ * pendingAdjudication(到点后的待裁决标记);
1583
+ * [T7] leaderEstimate(负责人时长聚合,服务端读时派生:全员 sent 表述完整等式,
1584
+ * 否则部分和+缺口名单;null/缺失整块不渲染,客户端严禁求和)。
1551
1585
  *
1552
1586
  * 客户端不推导状态机、不补造字段:任何字段缺失就少显示一行;全部缺失整块不渲染,
1553
1587
  * 绝不出现 undefined / [object Object]。
@@ -1576,7 +1610,20 @@ window.__ModuleLoader__.load({
1576
1610
  const warning = item?.timeWarning && typeof item.timeWarning === 'object' ? item.timeWarning : null;
1577
1611
  const channel = item?.noticeChannel && typeof item.noticeChannel === 'object' ? item.noticeChannel : null;
1578
1612
  const pending = item?.pendingAdjudication === true;
1579
- if (!estimate && !ceiling && !deadlineAt && !notice && !warning && !channel && !pending && extensions.length === 0) {
1613
+ /*
1614
+ * [T7][J2/J6] 负责人任务时长聚合:只渲染服务端下发的 leaderEstimate
1615
+ * (plan.ts deriveLeaderEstimate 读时派生,经 serialisePlan→derivePlanSnapshot
1616
+ * 同源下发)。客户端严禁求和、不推导状态机:reported===expected 仅作
1617
+ * 措辞选择(J1:全员 sent 才表述完整等式)。totalMinutes=0 合法(F3
1618
+ * 部分和 0),故用 ≥0 守卫而非 positiveNumber;字段缺失/null(J8 空
1619
+ * roster/replanned 旧行/越界 fail-closed)⇒ 不渲染本块。
1620
+ */
1621
+ const leaderEstimate = item?.leaderEstimate && typeof item.leaderEstimate === 'object' ? item.leaderEstimate : null;
1622
+ const leaderExpected = leaderEstimate && Number.isInteger(leaderEstimate.expected) && leaderEstimate.expected > 0 ? leaderEstimate.expected : null;
1623
+ const leaderReported = leaderEstimate && Number.isInteger(leaderEstimate.reported) && leaderEstimate.reported >= 0 ? leaderEstimate.reported : null;
1624
+ const leaderMinutes = leaderEstimate && Number.isFinite(Number(leaderEstimate.totalMinutes)) && Number(leaderEstimate.totalMinutes) >= 0 ? Number(leaderEstimate.totalMinutes) : null;
1625
+ const leaderShown = leaderEstimate !== null && leaderExpected !== null && leaderReported !== null && leaderMinutes !== null;
1626
+ if (!estimate && !ceiling && !deadlineAt && !notice && !warning && !channel && !pending && extensions.length === 0 && !leaderShown) {
1580
1627
  return null;
1581
1628
  }
1582
1629
  const remainingMs = deadlineAt ? Math.max(0, deadlineAt - Date.now()) : null;
@@ -1620,6 +1667,29 @@ window.__ModuleLoader__.load({
1620
1667
  }
1621
1668
  if (pending)
1622
1669
  notes.push(`${t('pendingAdjudication')}:${t('pendingAdjudicationHint')}`);
1670
+ /*
1671
+ * [T7][J1 方案 A] 全员 sent(reported===expected)才表述完整等式
1672
+ * 「负责人任务时长=全部下属开工预估之和」;否则必须按「部分和(X/Y)」
1673
+ * 标注并如实列出缺口名单。名单 join 只是展示拼接,不是求和;数值全部
1674
+ * 来自服务端下发的 leaderEstimate,客户端不做任何算术。
1675
+ */
1676
+ if (leaderShown) {
1677
+ const missingNames = Array.isArray(leaderEstimate.missing) ? leaderEstimate.missing.filter((name) => typeof name === 'string' && name !== '') : [];
1678
+ const failedNames = Array.isArray(leaderEstimate.failed) ? leaderEstimate.failed.filter((name) => typeof name === 'string' && name !== '') : [];
1679
+ const gaps = (missingNames.length > 0 ? fill(t('leaderEstimateMissing'), { names: missingNames.join('、') }) : '')
1680
+ + (failedNames.length > 0 ? fill(t('leaderEstimateFailed'), { names: failedNames.join('、') }) : '');
1681
+ notes.push(leaderReported === leaderExpected
1682
+ ? fill(t('leaderEstimateFull'), { minutes: leaderMinutes, reported: leaderReported, expected: leaderExpected })
1683
+ : fill(t('leaderEstimatePartial'), { minutes: leaderMinutes, reported: leaderReported, expected: leaderExpected, gaps }));
1684
+ /*
1685
+ * [SCv2-T4][Q4-B/C21] 超判据告警:只读服务端下发的布尔
1686
+ * leaderEstimateOverCriterion(normaliseStatusEntry 派生),客户端
1687
+ * 严禁自行算术(client.ts 既定约定)。部分和 >10 同样告警(AC-Q4-2)。
1688
+ */
1689
+ if (item?.leaderEstimateOverCriterion === true) {
1690
+ notes.push(fill(t('leaderEstimateOver'), { minutes: leaderMinutes }));
1691
+ }
1692
+ }
1623
1693
  return h('div', { className: 'dsh-wp-time' }, h('div', { className: 'dsh-wp-time-title' }, t('timeNegotiation')), facts.length > 0
1624
1694
  ? h('div', { className: 'dsh-wp-time-row' }, facts.map((fact, factIndex) => h('span', { key: String(factIndex) }, fact)))
1625
1695
  : null, notes.map((note, noteIndex) => h('p', { key: String(noteIndex), className: 'dsh-wp-time-note' }, note)));
@@ -1678,6 +1748,11 @@ window.__ModuleLoader__.load({
1678
1748
  * [2.2.7][T2/五档] UI Pill 白名单:与 plan.ts 的 REASONING_EFFORTS
1679
1749
  * (low / medium / high / xhigh / max)逐值同步。浏览器包无法 import
1680
1750
  * 宿主常量,此处为唯二事实源之一——漏改会让新档位在任务卡片上静默消失。
1751
+ * [2.3.9][T3] 模型家族收窄口径:qwen 系仅 low/medium/xhigh、其余仅
1752
+ * low/high/max 的**事前约束**发生在规划校验(validatePlan allowedEfforts)
1753
+ * 与派发入口(runtime 静态收窄+qwen-rule 留痕);计划字段本身是存储全集
1754
+ * 五档(旧计划/他模型计划可在本会话回放展示),故 Pill 继续按五档显示、
1755
+ * 不得按家族删档——家族合法性以发送前的收窄/拒绝为准,不靠 UI 过滤兜底。
1681
1756
  */
1682
1757
  const effort = typeof subtask?.reasoningEffort === 'string' && ['low', 'medium', 'high', 'xhigh', 'max'].includes(subtask.reasoningEffort)
1683
1758
  ? subtask.reasoningEffort
@@ -1693,6 +1768,31 @@ window.__ModuleLoader__.load({
1693
1768
  + `${handoff?.department ? ` → ${deptName(t, handoff.department)}` : ''}`
1694
1769
  + `|${handoffStatusText(t, handoff?.status)}`
1695
1770
  + `${handoff?.response ? `:${String(handoff.response)}` : ''}`))))
1771
+ : null,
1772
+ /*
1773
+ * [2.3.9][T4b] 第三层派发看板(用户要求 4/5):部门负责人分配给
1774
+ * 全球顶尖专家的每位下级、其推理等级(含越界钳制留痕)与实时状态
1775
+ * 必须对用户与主 Agent 可见,否则「第三层派给了谁、跑没跑完」只存在
1776
+ * 负责人子会话里。数据源 = 状态行 delegates(applyStatus 消毒 +
1777
+ * durable workplan-update 回放,刷新/重启不丢),客户端不推导状态。
1778
+ */
1779
+ Array.isArray(item?.delegates) && item.delegates.length
1780
+ ? h('div', { className: 'dsh-wp-subtask-body' }, h('div', null, h('strong', null, `${t('delegates')}:`)), h('ul', { className: 'dsh-wp-muted' }, item.delegates.map((member, memberIndex) => h('li', { key: `${String(member?.childId ?? member?.member ?? '')}-${memberIndex}` }, `└ ${String(member?.member ?? '?')}`
1781
+ + `(${member?.role === 'expert' ? t('delegateExpert') : t('delegateMember')})`
1782
+ + `|${t('reasoningEffort')}:${String(member?.effort ?? '?')}`
1783
+ + (member?.requested && member.requested !== member.effort ? `(越界钳制自 ${String(member.requested)})` : '')
1784
+ + (member?.selfEffort ? `|自配档 ${String(member.selfEffort)}${member?.selfEffortRequested && member.selfEffortRequested !== member.selfEffort ? `(钳制自 ${String(member.selfEffortRequested)})` : ''}` : '|自配档 待自配')
1785
+ + `|${t(`delegateStatus.${String(member?.status ?? 'running')}`)}`
1786
+ /*
1787
+ * [2.5.6] 第三层闭环可见性:叶子的「待指示/已给指示/已回应」
1788
+ * 与第一层同一套 closure 文案(服务端下发,客户端不推导),
1789
+ * 请示问题随待指示标记一并展示,负责人/用户一眼看到谁在等谁。
1790
+ */
1791
+ + (member?.escalation ? `|${t('closureEscalated')}${member.escalation.question ? `:${String(member.escalation.question)}` : ''}` : '')
1792
+ + (member?.lastInstruction ? `|${t('closureInstructed')}` : '')
1793
+ + (member?.closure === 'acknowledged' ? `|${t('closureAcknowledged')}` : '')
1794
+ + (member?.instructionOverdue ? `|${t('closureNoAck')}` : '')
1795
+ + (member?.summary ? `:${String(member.summary)}` : '')))))
1696
1796
  : null, status !== 'blocked' && item?.summary ? h('p', { className: 'dsh-wp-muted' }, `${t('summary')}:${plainError(item.summary)}`) : null,
1697
1797
  /*
1698
1798
  * [1.10.0] R-02:「卡住原因」只属于没做完的行。
@@ -17,8 +17,17 @@
17
17
  * - 与既有门禁正交:解析失败、验收缺口、三阶段缺失仍由原门禁先拦,
18
18
  * 本门禁只负责把「其它门禁都过了、但格式仍不合规」的 done 退回。
19
19
  */
20
- /** 格式规范版本,随规范内容变更递增。 */
21
- export const COMM_FORMAT_VERSION = 1;
20
+ import { checkDepartmentSummary, checkExpertReport, renderDepartmentSummarySpec, renderExpertReportSpec, } from './v3-contract.js';
21
+ /**
22
+ * 格式规范版本,随规范内容变更递增。
23
+ *
24
+ * [3.0.0] 1 → 2:用户 2026-11-14 第 7、10 条要求为结果格式增加了两条
25
+ * 结构化精简契约(F10 专家 JSON 汇报、F11 部门 JSON 汇总)。F1–F9 的
26
+ * 文本与判据一字未改(只增不改),新增条目由调用方按接收者层级开关:
27
+ * 专家结果查 F10,部门负责人结果查 F11,未声明层级时两条都不查
28
+ * (历史回放与其它调用点零回归)。
29
+ */
30
+ export const COMM_FORMAT_VERSION = 2;
22
31
  /**
23
32
  * 统一沟通交流格式规范定义(F1-F9,冻结不可变)。
24
33
  */
@@ -33,7 +42,7 @@ export const COMM_FORMAT_SPEC = Object.freeze({
33
42
  description: '证据块必须是合法 JSON 对象,顶层必须含 status 字段,取值只能是 done / blocked / partial',
34
43
  rationale: 'status 是交付门禁的入口条件,缺失或非法则无法判定完成与否' }),
35
44
  Object.freeze({ id: 'F3', category: 'phases',
36
- description: '必须包含三阶段证据:phases.planning(问题分析与可执行思路)、phases.execution(实际执行步骤)、phases.verification(逐项验证)',
45
+ description: '必须包含三阶段证据:phases.planning(两轮深度思考:第一轮任务深研 problemAnalysis + 第二轮方法流程步骤 approach + 第二轮依据 approachBasis)、phases.execution(实际执行步骤)、phases.verification(逐项验证)',
37
46
  rationale: '三阶段是质量闭环的基础,缺任一阶段等于跳过对应质控环节' }),
38
47
  Object.freeze({ id: 'F4', category: 'acceptance',
39
48
  description: '验收结果必须逐条回应计划的验收标准(A1、A2…),且每条 result=pass 必须附带具体证据(命令输出/文件路径/引用),禁止空证据 pass',
@@ -53,6 +62,16 @@ export const COMM_FORMAT_SPEC = Object.freeze({
53
62
  Object.freeze({ id: 'F9', category: 'integrity',
54
63
  description: '不得编造、虚构或伪造任何证据、文件路径、命令输出或验收结果;无法确认的项目必须写 unverified',
55
64
  rationale: '虚假证据一旦通过交付门禁,用户拿到的就是不可信的成品' }),
65
+ /*
66
+ * [3.0.0] F10/F11:用户 2026-11-14 第 7、10 条要求。F1–F9 是 2.1.0 起的
67
+ * 冻结条目,本次只增不改;两条新条目按接收者层级启用(见 check 的 tier)。
68
+ */
69
+ Object.freeze({ id: 'F10', category: 'report',
70
+ description: '专家(第三层执行者)结果必须包含 report 对象,只允许 keyResults/keyInfo/importantInfo/leadRequirements 四个字符串数组字段,至少各有 1 条非空内容(keyInfo/important 可为空数组但须存在),每数组最多 6 条、每条最多 200 字符,内部与跨字段不得出现重复表述',
71
+ rationale: '用户要求 7:专家成果必须非常精简地汇报给部门负责人,只要关键信息、关键成果、重要信息和负责人要求的东西,并以 JSON mode 结构化输出' }),
72
+ Object.freeze({ id: 'F11', category: 'report',
73
+ description: '部门负责人结果必须包含 departmentSummary 对象,只允许 keyResults/keyInfo/importantInfo/sources 四个字符串数组字段,keyResults 至少 1 条非空、sources 必须覆盖本部门全部已派发专家,每数组最多 6 条、每条最多 200 字符,内部与跨字段不得出现重复表述',
74
+ rationale: '用户要求 8/10/11:部门负责人必须全面汇总全部专家汇报,汇总报告必须精简、禁止累赘重复,并以 JSON mode 结构化直接交回主 Agent' }),
56
75
  ]),
57
76
  /*
58
77
  * [2.2.0][T3/O-2c] 结果块可选字段(方案 §2.4:「模板增加 timeSpentMinutes、
@@ -78,8 +97,12 @@ export const COMM_FORMAT_SPEC = Object.freeze({
78
97
  * @param parsed - 已解析的证据块 payload(parseEvidenceBlock 的 payload,可为 null)
79
98
  * @param rawOutput - 子 Agent 原始输出全文
80
99
  * @param expectedAcceptanceCount - 计划定义的验收标准条数
100
+ * @param options.tier - 接收者层级:'expert' 追加 F10(专家 JSON 汇报),
101
+ * 'leader' 追加 F11(部门 JSON 汇总);省略则两条都不查(历史回放、
102
+ * 旧调用点零回归)
103
+ * @param options.expectedExperts - 本部门已派发的专家名单(F11 覆盖度核对用)
81
104
  */
82
- export function checkCommFormatCompliance(parsed, rawOutput, expectedAcceptanceCount) {
105
+ export function checkCommFormatCompliance(parsed, rawOutput, expectedAcceptanceCount, options = {}) {
83
106
  const violations = [];
84
107
  const text = typeof rawOutput === 'string' ? rawOutput : '';
85
108
  // F1: 证据块标记必须成对出现(rescueEvidence 捞到的豁免——主 Agent 已能解析)
@@ -168,19 +191,48 @@ export function checkCommFormatCompliance(parsed, rawOutput, expectedAcceptanceC
168
191
  violations.push({ ruleId: 'F8', category: 'blocked',
169
192
  message: 'status 为 blocked 但 question 为空:须写清卡在哪一步、已尝试什么、需要谁做什么决定' });
170
193
  }
194
+ /*
195
+ * F10/F11(用户 2026-11-14 第 7、10、11 条):按接收者层级启用。
196
+ * 只拦 done 路径——受阻结果已有更针对性的诊断(F8/三阶段),
197
+ * 不再叠加精简性条目,避免一条 blocked 被反复退回在格式上。
198
+ */
199
+ if (options.tier === 'expert' && parsed.status === 'done') {
200
+ const report = checkExpertReport(parsed.report);
201
+ for (const item of report.violations) {
202
+ violations.push({ ruleId: 'F10', category: 'report', message: item });
203
+ }
204
+ }
205
+ if (options.tier === 'leader' && parsed.status === 'done') {
206
+ const summary = checkDepartmentSummary(parsed.departmentSummary, options.expectedExperts ?? []);
207
+ for (const item of summary.violations) {
208
+ violations.push({ ruleId: 'F11', category: 'report', message: item });
209
+ }
210
+ }
171
211
  return { compliant: violations.length === 0, violations, version: COMM_FORMAT_VERSION };
172
212
  }
173
213
  /**
174
214
  * 把格式规范渲染为嵌入子 Agent 提示词的文本。
175
215
  * 这是「派发工作时附带统一沟通交流格式要求」的具体实现。
216
+ *
217
+ * @param tier - 接收者层级:'expert' 附带专家 JSON 汇报契约(F10),
218
+ * 'leader' 附带部门 JSON 汇总契约(F11);省略时两条都不带。
176
219
  */
177
- export function renderCommFormatSpec() {
220
+ export function renderCommFormatSpec(tier) {
178
221
  const lines = [
179
222
  '沟通交流格式规范(v' + String(COMM_FORMAT_VERSION) + ',主 Agent 与部门人员双方认可的结果格式契约):',
180
223
  ];
181
- for (const req of COMM_FORMAT_SPEC.requirements) {
224
+ const scoped = tier === 'expert'
225
+ ? COMM_FORMAT_SPEC.requirements.filter((req) => req.id !== 'F11')
226
+ : tier === 'leader'
227
+ ? COMM_FORMAT_SPEC.requirements.filter((req) => req.id !== 'F10')
228
+ : COMM_FORMAT_SPEC.requirements;
229
+ for (const req of scoped) {
182
230
  lines.push(`- 【${req.id}】${req.description}`);
183
231
  }
232
+ if (tier === 'expert')
233
+ lines.push('', renderExpertReportSpec());
234
+ if (tier === 'leader')
235
+ lines.push('', renderDepartmentSummarySpec());
184
236
  lines.push('不合规的后果:主 Agent 收到结果后按本规范逐条核验;任一不合规,结果立刻退回,你将收到列明不合规条目的退回通知,须全部修正后重新提交完整结果。');
185
237
  return lines.join('\n');
186
238
  }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * [SCv2-T4] 「简单」判据 v2 · 判据层(criterion layer)单一真源模块。
3
+ *
4
+ * 口径来源(逐字冻结,不改写):
5
+ * - reports/simple-criterion-v2-spec.md(用户 2026-11-13 裁决 B/B/B/B/A/A/B):
6
+ * S-Q1-1..6 / S-Q2-1..4 / S-Q3-1..4 / S-Q4-1..5 / S-Q5-1..5 / S-Q6-1..5 / S-Q7-1..5,
7
+ * §3.5 唯一判定链(met / exception-approved / unmet 三选一)。
8
+ * - reports/simple-criterion-v2-touchpoints.md C05–C10 / C22 / C29(机制落点)。
9
+ * - reports/simple-criterion-v2-open-decisions.md D-1~D-4 推荐项(均选 A,
10
+ * **待用户裁定**;本模块按推荐实现,裁定前不得据以宣称达标)。
11
+ *
12
+ * 分层纪律(Q7-B,红线):
13
+ * - 本模块只承载**判据层**(完成目标 ≤10 分钟);**运行层**安全兜底
14
+ * (CHILD_TIMEOUT_MS=900000 / MAX_CHILD_TIMEOUT_MS=7200000 /
15
+ * deriveSubtaskTimeoutMs 公式 / L4 结算)数值与公式一律不改。
16
+ * - 判据层不改变运行层时限;运行层允许延长不等于判据层达标。
17
+ *
18
+ * 生效边界(Q5-A 不回溯 + D-1 三重门,推荐项 A,待裁定):
19
+ * - 默认**完全关闭**:未设置环境变量时所有函数对既有行为零影响
20
+ * (在途计划与历史任务按旧规则,既有回归零改动)。
21
+ * - 主 Agent 在「补丁部署+用户重启+T8 复核通过」后设置:
22
+ * DSH_WORKPLAN_CRITERION_V2=1
23
+ * DSH_WORKPLAN_CRITERION_V2_SINCE=<生效起点,epoch 毫秒或 ISO 时间>
24
+ * 仅对 createdAt >= 起点 的**新创建计划**生效(fail-closed:任一缺失/非法
25
+ * 一律视为未生效,绝不用尚不存在的机制审判在途任务)。
26
+ *
27
+ * 本模块不 import plan.ts / runtime.ts(避免循环依赖):聚合结果
28
+ * (LeaderEstimateSummary 形状)由调用方以参数传入。
29
+ */
30
+ /** 判据层完成目标(分钟)。用户裁决 Q1-B:默认必须达成;唯一例外=用户批准留痕。 */
31
+ export const CRITERION_TARGET_MINUTES = 10;
32
+ /** 结算判据三选一(spec §3.5 第 4 步)。 */
33
+ export const CRITERION_RESULTS = ['met', 'unmet', 'exception-approved'];
34
+ function isRecord(value) {
35
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
36
+ }
37
+ /**
38
+ * fail-closed 消毒(与 sanitizeDelegateEstimate 同风格):任一必填项缺失/非法
39
+ * ⇒ 整个批准丢弃(返回 null),绝不入库脏值、绝不把「未批准」洗成「已批准」。
40
+ */
41
+ export function sanitizeCriterionException(value) {
42
+ if (!isRecord(value))
43
+ return null;
44
+ if (value.approvedBy !== 'user')
45
+ return null;
46
+ const at = Number(value.at);
47
+ if (!Number.isFinite(at) || at <= 0)
48
+ return null;
49
+ const reason = typeof value.reason === 'string' ? value.reason.trim() : '';
50
+ if (reason === '')
51
+ return null;
52
+ if (value.scope !== 'task' && value.scope !== 'plan')
53
+ return null;
54
+ const extendedMs = Number(value.extendedMs);
55
+ const extendedMinutes = Number(value.extendedMinutes);
56
+ return {
57
+ approvedBy: 'user',
58
+ at,
59
+ reason: reason.slice(0, 2000),
60
+ ...(typeof value.source === 'string' && value.source.trim() !== ''
61
+ ? { source: value.source.trim().slice(0, 500) }
62
+ : {}),
63
+ scope: value.scope,
64
+ ...(Number.isFinite(extendedMs) && extendedMs > 0 ? { extendedMs: Math.floor(extendedMs) } : {}),
65
+ ...(Number.isFinite(extendedMinutes) && extendedMinutes > 0
66
+ ? { extendedMinutes: Math.round(extendedMinutes * 100) / 100 }
67
+ : {}),
68
+ };
69
+ }
70
+ /**
71
+ * [SCv2-T4][D-1 推荐 A] 判据 v2 是否对该计划生效(三重门的运行态落点)。
72
+ *
73
+ * 全部条件 fail-closed:开关未开 / 起点缺失或非法 / 计划创建时间缺失或非法
74
+ * ⇒ 一律 false(旧规则)。只有「开关=1/true 且 createdAt >= SINCE」才 true。
75
+ */
76
+ export function criterionV2Active(planCreatedAt, env = process.env) {
77
+ const flag = String(env.DSH_WORKPLAN_CRITERION_V2 ?? '').trim().toLowerCase();
78
+ if (flag !== '1' && flag !== 'true')
79
+ return false;
80
+ const sinceRaw = String(env.DSH_WORKPLAN_CRITERION_V2_SINCE ?? '').trim();
81
+ if (sinceRaw === '')
82
+ return false;
83
+ const since = /^\d+$/.test(sinceRaw) ? Number(sinceRaw) : Date.parse(sinceRaw);
84
+ if (!Number.isFinite(since) || since <= 0)
85
+ return false;
86
+ const created = Number(planCreatedAt);
87
+ if (!Number.isFinite(created) || created <= 0)
88
+ return false;
89
+ return created >= since;
90
+ }
91
+ /**
92
+ * [SCv2-T4][Q6-A/C28/C29] 单次尝试墙钟(毫秒)=结算时间 − 尝试起点。
93
+ *
94
+ * 数据源只认 journal 时间戳(startedAt/finishedAt),绝不采用模型自报分钟数
95
+ * (S-Q6-3)。已知陷阱(touchpoints C29 ⚠):预算重置会清空 startedAt/finishedAt
96
+ * ——缺失时返回 null(「未验证」),**绝不返回 0**(否则把「计时被清空」误判成
97
+ * 「0 分钟完成」)。每次尝试独立计量,不跨尝试累计(S-Q6-1/2)。
98
+ */
99
+ export function attemptWallClockMsOf(row) {
100
+ if (!isRecord(row))
101
+ return null;
102
+ // null/undefined 必须显式拒绝:Number(null)===0 会把「计时被重置清空」
103
+ // 误判成「0 分钟完成」(Q6-A 唯一实现陷阱,touchpoints C29 ⚠)。
104
+ if (row.startedAt === null || row.startedAt === undefined)
105
+ return null;
106
+ if (row.finishedAt === null || row.finishedAt === undefined)
107
+ return null;
108
+ const started = Number(row.startedAt);
109
+ const finished = Number(row.finishedAt);
110
+ if (!Number.isFinite(started) || !Number.isFinite(finished))
111
+ return null;
112
+ return Math.max(0, finished - started);
113
+ }
114
+ /**
115
+ * [SCv2-T4][Q4-B/D-2 推荐 A/D-3 推荐 A] 部门行事前预估口径。
116
+ *
117
+ * - 有叶子(leaderEstimate 非 null):事前值=全部叶子最新 sent 预估之和;
118
+ * reported===expected 才算「齐」(部分和不得视为达标,S-Q4-5/D-3)。
119
+ * - 无叶子直做(leaderEstimate null):事前值=负责人自身开工预估
120
+ * (row.timeNotice.declaredMinutes,D-2 推荐 A,对称于叶子之和);缺失⇒不齐。
121
+ * 绝不因「没有叶子」而自动豁免(S-Q4-4)。
122
+ *
123
+ * leaderEstimate 由调用方传 plan.ts deriveLeaderEstimate 的结果(形状兼容),
124
+ * 本模块不重复求和、不反写台账(F6/J8 同纪律)。
125
+ */
126
+ export function criterionExAnte(row, leaderEstimate) {
127
+ if (leaderEstimate && Number.isFinite(Number(leaderEstimate.totalMinutes))) {
128
+ return {
129
+ minutes: Number(leaderEstimate.totalMinutes),
130
+ complete: leaderEstimate.reported === leaderEstimate.expected && leaderEstimate.expected > 0,
131
+ };
132
+ }
133
+ const notice = isRecord(row) && isRecord(row.timeNotice) ? row.timeNotice : null;
134
+ const declared = notice ? Number(notice.declaredMinutes) : NaN;
135
+ if (Number.isFinite(declared) && declared > 0)
136
+ return { minutes: declared, complete: true };
137
+ return { minutes: null, complete: false };
138
+ }
139
+ /**
140
+ * [SCv2-T4][spec §3.5 第 4 步 / S-Q6-5 / D-4 推荐 A] 判据层结算判定(纯函数)。
141
+ *
142
+ * 达标(met)=事前预估之和 ≤10 **且** 事后单次尝试墙钟 ≤10(双条件同时满足);
143
+ * 任一不满足且无有效用户批准 ⇒ unmet(不得 done、记违规、转接替行);
144
+ * 有有效用户批准 ⇒ exception-approved(可 done、留例外、不生成接替行)。
145
+ *
146
+ * 批准时机(C-4 推荐 A,待裁定):批准必须不晚于本次结算(at <= settledAt);
147
+ * 结算后追认一律无效(防「事后洗白」),只能批准接替行。
148
+ *
149
+ * 严格口径(D-3 推荐 A,待裁定):事前预估未齐 / 墙钟缺失(被重置清空)
150
+ * ⇒ 不得宣称达标,按 unmet 处理并如实给出 reasons;受平台缺陷影响的行
151
+ * 可经 Q1 例外审批留痕后豁免(exception-approved 分支)。
152
+ */
153
+ export function evaluateCriterion(input) {
154
+ const reasons = [];
155
+ let over = false;
156
+ if (!input.exAnteComplete) {
157
+ over = true;
158
+ reasons.push('ex-ante-incomplete:事前预估未齐或缺失(D-3 严格口径,不得视为达标)');
159
+ }
160
+ else if (input.exAnteMinutes !== null && input.exAnteMinutes > CRITERION_TARGET_MINUTES) {
161
+ over = true;
162
+ reasons.push(`ex-ante-over:事前预估 ${input.exAnteMinutes} 分钟 > ${CRITERION_TARGET_MINUTES} 分钟目标`);
163
+ }
164
+ if (input.wallClockMs === null) {
165
+ over = true;
166
+ reasons.push('wall-clock-unverified:单次尝试墙钟缺失(计时被重置或无时间戳),不得按 0 分钟判达标(Q6-A)');
167
+ }
168
+ else if (input.wallClockMs > CRITERION_TARGET_MINUTES * 60_000) {
169
+ over = true;
170
+ reasons.push(`wall-clock-over:本次尝试墙钟 ${(input.wallClockMs / 60_000).toFixed(2)} 分钟 > ${CRITERION_TARGET_MINUTES} 分钟目标`);
171
+ }
172
+ if (!over) {
173
+ return { criterionResult: 'met', canBeDone: true, needsReplacement: false, exceptionRecorded: false, reasons };
174
+ }
175
+ const exception = input.exception ?? null;
176
+ if (exception) {
177
+ const settledAt = Number.isFinite(Number(input.settledAt)) ? Number(input.settledAt) : Date.now();
178
+ if (exception.at <= settledAt) {
179
+ return {
180
+ criterionResult: 'exception-approved',
181
+ canBeDone: true,
182
+ needsReplacement: false,
183
+ exceptionRecorded: true,
184
+ reasons: [...reasons, 'user-exception:用户明确批准并留痕(Q1-B 唯一例外通道)'],
185
+ };
186
+ }
187
+ reasons.push('approval-after-settlement:批准时间晚于本次结算,事后追认无效(C-4 推荐 A)');
188
+ }
189
+ return { criterionResult: 'unmet', canBeDone: false, needsReplacement: true, exceptionRecorded: false, reasons };
190
+ }
191
+ /**
192
+ * [SCv2-T4] T5 参考实现 referenceQ3Settlement 的同口径生产适配器(分钟入参)。
193
+ * 生产接线落盘后 T5 只需把 referenceQ3* 替换为本导出,断言口径保持不变。
194
+ */
195
+ export function q3SettlementVerdict(input) {
196
+ const exception = input.userApproved === true
197
+ ? { approvedBy: 'user', at: 1, reason: 'user-approved(参考夹具口径)', scope: 'task' }
198
+ : null;
199
+ return evaluateCriterion({
200
+ exAnteMinutes: Number(input.declaredMinutes ?? 0),
201
+ exAnteComplete: true,
202
+ wallClockMs: Number(input.wallClockMinutes ?? 0) * 60_000,
203
+ exception,
204
+ settledAt: Date.now(),
205
+ });
206
+ }
207
+ /**
208
+ * [SCv2-T4][D-4 推荐 A] 判据违规审计条目(append-only,绝不抹除)。
209
+ * 行级最终结果取最后一次(接替)尝试;原始未批准超时保留在本数组供审计,
210
+ * 防「续跑洗白」。上限 20 条与 timeJournal 同纪律。
211
+ */
212
+ export function appendCriterionViolation(existing, entry) {
213
+ const list = Array.isArray(existing) ? existing.filter(isRecord) : [];
214
+ return [...list, { ...entry, kind: 'criterion-overrun' }].slice(-20);
215
+ }