dsh-workplan 2.3.9 → 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.
@@ -18,8 +18,23 @@
18
18
  * 本门禁只负责把「其它门禁都过了、但格式仍不合规」的 done 退回。
19
19
  */
20
20
 
21
- /** 格式规范版本,随规范内容变更递增。 */
22
- export const COMM_FORMAT_VERSION = 1
21
+ import {
22
+ checkDepartmentSummary,
23
+ checkExpertReport,
24
+ renderDepartmentSummarySpec,
25
+ renderExpertReportSpec,
26
+ } from './v3-contract.js'
27
+
28
+ /**
29
+ * 格式规范版本,随规范内容变更递增。
30
+ *
31
+ * [3.0.0] 1 → 2:用户 2026-11-14 第 7、10 条要求为结果格式增加了两条
32
+ * 结构化精简契约(F10 专家 JSON 汇报、F11 部门 JSON 汇总)。F1–F9 的
33
+ * 文本与判据一字未改(只增不改),新增条目由调用方按接收者层级开关:
34
+ * 专家结果查 F10,部门负责人结果查 F11,未声明层级时两条都不查
35
+ * (历史回放与其它调用点零回归)。
36
+ */
37
+ export const COMM_FORMAT_VERSION = 2
23
38
 
24
39
  /** 单条不合规项。 */
25
40
  export interface CommFormatViolation {
@@ -55,7 +70,7 @@ export const COMM_FORMAT_SPEC = Object.freeze({
55
70
  description: '证据块必须是合法 JSON 对象,顶层必须含 status 字段,取值只能是 done / blocked / partial',
56
71
  rationale: 'status 是交付门禁的入口条件,缺失或非法则无法判定完成与否' }),
57
72
  Object.freeze({ id: 'F3', category: 'phases',
58
- description: '必须包含三阶段证据:phases.planning(问题分析与可执行思路)、phases.execution(实际执行步骤)、phases.verification(逐项验证)',
73
+ description: '必须包含三阶段证据:phases.planning(两轮深度思考:第一轮任务深研 problemAnalysis + 第二轮方法流程步骤 approach + 第二轮依据 approachBasis)、phases.execution(实际执行步骤)、phases.verification(逐项验证)',
59
74
  rationale: '三阶段是质量闭环的基础,缺任一阶段等于跳过对应质控环节' }),
60
75
  Object.freeze({ id: 'F4', category: 'acceptance',
61
76
  description: '验收结果必须逐条回应计划的验收标准(A1、A2…),且每条 result=pass 必须附带具体证据(命令输出/文件路径/引用),禁止空证据 pass',
@@ -75,6 +90,16 @@ export const COMM_FORMAT_SPEC = Object.freeze({
75
90
  Object.freeze({ id: 'F9', category: 'integrity',
76
91
  description: '不得编造、虚构或伪造任何证据、文件路径、命令输出或验收结果;无法确认的项目必须写 unverified',
77
92
  rationale: '虚假证据一旦通过交付门禁,用户拿到的就是不可信的成品' }),
93
+ /*
94
+ * [3.0.0] F10/F11:用户 2026-11-14 第 7、10 条要求。F1–F9 是 2.1.0 起的
95
+ * 冻结条目,本次只增不改;两条新条目按接收者层级启用(见 check 的 tier)。
96
+ */
97
+ Object.freeze({ id: 'F10', category: 'report',
98
+ description: '专家(第三层执行者)结果必须包含 report 对象,只允许 keyResults/keyInfo/importantInfo/leadRequirements 四个字符串数组字段,至少各有 1 条非空内容(keyInfo/important 可为空数组但须存在),每数组最多 6 条、每条最多 200 字符,内部与跨字段不得出现重复表述',
99
+ rationale: '用户要求 7:专家成果必须非常精简地汇报给部门负责人,只要关键信息、关键成果、重要信息和负责人要求的东西,并以 JSON mode 结构化输出' }),
100
+ Object.freeze({ id: 'F11', category: 'report',
101
+ description: '部门负责人结果必须包含 departmentSummary 对象,只允许 keyResults/keyInfo/importantInfo/sources 四个字符串数组字段,keyResults 至少 1 条非空、sources 必须覆盖本部门全部已派发专家,每数组最多 6 条、每条最多 200 字符,内部与跨字段不得出现重复表述',
102
+ rationale: '用户要求 8/10/11:部门负责人必须全面汇总全部专家汇报,汇总报告必须精简、禁止累赘重复,并以 JSON mode 结构化直接交回主 Agent' }),
78
103
  ]),
79
104
  /*
80
105
  * [2.2.0][T3/O-2c] 结果块可选字段(方案 §2.4:「模板增加 timeSpentMinutes、
@@ -101,11 +126,16 @@ export const COMM_FORMAT_SPEC = Object.freeze({
101
126
  * @param parsed - 已解析的证据块 payload(parseEvidenceBlock 的 payload,可为 null)
102
127
  * @param rawOutput - 子 Agent 原始输出全文
103
128
  * @param expectedAcceptanceCount - 计划定义的验收标准条数
129
+ * @param options.tier - 接收者层级:'expert' 追加 F10(专家 JSON 汇报),
130
+ * 'leader' 追加 F11(部门 JSON 汇总);省略则两条都不查(历史回放、
131
+ * 旧调用点零回归)
132
+ * @param options.expectedExperts - 本部门已派发的专家名单(F11 覆盖度核对用)
104
133
  */
105
134
  export function checkCommFormatCompliance(
106
135
  parsed: any,
107
136
  rawOutput: string,
108
137
  expectedAcceptanceCount: number,
138
+ options: { tier?: 'leader' | 'expert'; expectedExperts?: readonly string[] } = {},
109
139
  ): CommFormatCheckResult {
110
140
  const violations: CommFormatViolation[] = []
111
141
  const text = typeof rawOutput === 'string' ? rawOutput : ''
@@ -198,20 +228,48 @@ export function checkCommFormatCompliance(
198
228
  message: 'status 为 blocked 但 question 为空:须写清卡在哪一步、已尝试什么、需要谁做什么决定' })
199
229
  }
200
230
 
231
+ /*
232
+ * F10/F11(用户 2026-11-14 第 7、10、11 条):按接收者层级启用。
233
+ * 只拦 done 路径——受阻结果已有更针对性的诊断(F8/三阶段),
234
+ * 不再叠加精简性条目,避免一条 blocked 被反复退回在格式上。
235
+ */
236
+ if (options.tier === 'expert' && parsed.status === 'done') {
237
+ const report = checkExpertReport(parsed.report)
238
+ for (const item of report.violations) {
239
+ violations.push({ ruleId: 'F10', category: 'report', message: item })
240
+ }
241
+ }
242
+ if (options.tier === 'leader' && parsed.status === 'done') {
243
+ const summary = checkDepartmentSummary(parsed.departmentSummary, options.expectedExperts ?? [])
244
+ for (const item of summary.violations) {
245
+ violations.push({ ruleId: 'F11', category: 'report', message: item })
246
+ }
247
+ }
248
+
201
249
  return { compliant: violations.length === 0, violations, version: COMM_FORMAT_VERSION }
202
250
  }
203
251
 
204
252
  /**
205
253
  * 把格式规范渲染为嵌入子 Agent 提示词的文本。
206
254
  * 这是「派发工作时附带统一沟通交流格式要求」的具体实现。
255
+ *
256
+ * @param tier - 接收者层级:'expert' 附带专家 JSON 汇报契约(F10),
257
+ * 'leader' 附带部门 JSON 汇总契约(F11);省略时两条都不带。
207
258
  */
208
- export function renderCommFormatSpec(): string {
259
+ export function renderCommFormatSpec(tier?: 'leader' | 'expert'): string {
209
260
  const lines: string[] = [
210
261
  '沟通交流格式规范(v' + String(COMM_FORMAT_VERSION) + ',主 Agent 与部门人员双方认可的结果格式契约):',
211
262
  ]
212
- for (const req of COMM_FORMAT_SPEC.requirements) {
263
+ const scoped = tier === 'expert'
264
+ ? COMM_FORMAT_SPEC.requirements.filter((req: any) => req.id !== 'F11')
265
+ : tier === 'leader'
266
+ ? COMM_FORMAT_SPEC.requirements.filter((req: any) => req.id !== 'F10')
267
+ : COMM_FORMAT_SPEC.requirements
268
+ for (const req of scoped) {
213
269
  lines.push(`- 【${req.id}】${req.description}`)
214
270
  }
271
+ if (tier === 'expert') lines.push('', renderExpertReportSpec())
272
+ if (tier === 'leader') lines.push('', renderDepartmentSummarySpec())
215
273
  lines.push('不合规的后果:主 Agent 收到结果后按本规范逐条核验;任一不合规,结果立刻退回,你将收到列明不合规条目的退回通知,须全部修正后重新提交完整结果。')
216
274
  return lines.join('\n')
217
275
  }
@@ -0,0 +1,262 @@
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
+
31
+ /** 判据层完成目标(分钟)。用户裁决 Q1-B:默认必须达成;唯一例外=用户批准留痕。 */
32
+ export const CRITERION_TARGET_MINUTES = 10
33
+
34
+ /** 结算判据三选一(spec §3.5 第 4 步)。 */
35
+ export const CRITERION_RESULTS = ['met', 'unmet', 'exception-approved'] as const
36
+ export type CriterionResult = (typeof CRITERION_RESULTS)[number]
37
+
38
+ /**
39
+ * [SCv2-T4][Q1-B/S-Q1-2] 用户例外批准留痕(最终定名 criterionException)。
40
+ *
41
+ * 5 项口径(spec S-Q1-2):任务 ID(由所在状态行 subtaskId 承载)、批准原文/来源
42
+ * (reason + 可选 source)、批准时间(at,epoch 毫秒;展示按 Asia/Shanghai)、
43
+ * 放宽后的分钟数(extendedMinutes / extendedMs,延期场景由 runtime 回填)、
44
+ * 适用范围(scope:仅本任务 task / 本计划 plan)。无留痕=未批准。
45
+ */
46
+ export interface CriterionException {
47
+ readonly approvedBy: 'user'
48
+ readonly at: number
49
+ readonly reason: string
50
+ readonly source?: string
51
+ readonly scope: 'task' | 'plan'
52
+ readonly extendedMs?: number
53
+ readonly extendedMinutes?: number
54
+ }
55
+
56
+ function isRecord(value: unknown): value is Record<string, any> {
57
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
58
+ }
59
+
60
+ /**
61
+ * fail-closed 消毒(与 sanitizeDelegateEstimate 同风格):任一必填项缺失/非法
62
+ * ⇒ 整个批准丢弃(返回 null),绝不入库脏值、绝不把「未批准」洗成「已批准」。
63
+ */
64
+ export function sanitizeCriterionException(value: unknown): CriterionException | null {
65
+ if (!isRecord(value)) return null
66
+ if (value.approvedBy !== 'user') return null
67
+ const at = Number(value.at)
68
+ if (!Number.isFinite(at) || at <= 0) return null
69
+ const reason = typeof value.reason === 'string' ? value.reason.trim() : ''
70
+ if (reason === '') return null
71
+ if (value.scope !== 'task' && value.scope !== 'plan') return null
72
+ const extendedMs = Number(value.extendedMs)
73
+ const extendedMinutes = Number(value.extendedMinutes)
74
+ return {
75
+ approvedBy: 'user',
76
+ at,
77
+ reason: reason.slice(0, 2000),
78
+ ...(typeof value.source === 'string' && value.source.trim() !== ''
79
+ ? { source: value.source.trim().slice(0, 500) }
80
+ : {}),
81
+ scope: value.scope,
82
+ ...(Number.isFinite(extendedMs) && extendedMs > 0 ? { extendedMs: Math.floor(extendedMs) } : {}),
83
+ ...(Number.isFinite(extendedMinutes) && extendedMinutes > 0
84
+ ? { extendedMinutes: Math.round(extendedMinutes * 100) / 100 }
85
+ : {}),
86
+ }
87
+ }
88
+
89
+ /**
90
+ * [SCv2-T4][D-1 推荐 A] 判据 v2 是否对该计划生效(三重门的运行态落点)。
91
+ *
92
+ * 全部条件 fail-closed:开关未开 / 起点缺失或非法 / 计划创建时间缺失或非法
93
+ * ⇒ 一律 false(旧规则)。只有「开关=1/true 且 createdAt >= SINCE」才 true。
94
+ */
95
+ export function criterionV2Active(
96
+ planCreatedAt: unknown,
97
+ env: Record<string, string | undefined> = process.env,
98
+ ): boolean {
99
+ const flag = String(env.DSH_WORKPLAN_CRITERION_V2 ?? '').trim().toLowerCase()
100
+ if (flag !== '1' && flag !== 'true') return false
101
+ const sinceRaw = String(env.DSH_WORKPLAN_CRITERION_V2_SINCE ?? '').trim()
102
+ if (sinceRaw === '') return false
103
+ const since = /^\d+$/.test(sinceRaw) ? Number(sinceRaw) : Date.parse(sinceRaw)
104
+ if (!Number.isFinite(since) || since <= 0) return false
105
+ const created = Number(planCreatedAt)
106
+ if (!Number.isFinite(created) || created <= 0) return false
107
+ return created >= since
108
+ }
109
+
110
+ /**
111
+ * [SCv2-T4][Q6-A/C28/C29] 单次尝试墙钟(毫秒)=结算时间 − 尝试起点。
112
+ *
113
+ * 数据源只认 journal 时间戳(startedAt/finishedAt),绝不采用模型自报分钟数
114
+ * (S-Q6-3)。已知陷阱(touchpoints C29 ⚠):预算重置会清空 startedAt/finishedAt
115
+ * ——缺失时返回 null(「未验证」),**绝不返回 0**(否则把「计时被清空」误判成
116
+ * 「0 分钟完成」)。每次尝试独立计量,不跨尝试累计(S-Q6-1/2)。
117
+ */
118
+ export function attemptWallClockMsOf(row: unknown): number | null {
119
+ if (!isRecord(row)) return null
120
+ // null/undefined 必须显式拒绝:Number(null)===0 会把「计时被重置清空」
121
+ // 误判成「0 分钟完成」(Q6-A 唯一实现陷阱,touchpoints C29 ⚠)。
122
+ if (row.startedAt === null || row.startedAt === undefined) return null
123
+ if (row.finishedAt === null || row.finishedAt === undefined) return null
124
+ const started = Number(row.startedAt)
125
+ const finished = Number(row.finishedAt)
126
+ if (!Number.isFinite(started) || !Number.isFinite(finished)) return null
127
+ return Math.max(0, finished - started)
128
+ }
129
+
130
+ /** 事前条件输入(分钟);complete=false 表示预估未齐/缺失(D-3 推荐 A 严格口径)。 */
131
+ export interface CriterionExAnte {
132
+ readonly minutes: number | null
133
+ readonly complete: boolean
134
+ }
135
+
136
+ /**
137
+ * [SCv2-T4][Q4-B/D-2 推荐 A/D-3 推荐 A] 部门行事前预估口径。
138
+ *
139
+ * - 有叶子(leaderEstimate 非 null):事前值=全部叶子最新 sent 预估之和;
140
+ * reported===expected 才算「齐」(部分和不得视为达标,S-Q4-5/D-3)。
141
+ * - 无叶子直做(leaderEstimate null):事前值=负责人自身开工预估
142
+ * (row.timeNotice.declaredMinutes,D-2 推荐 A,对称于叶子之和);缺失⇒不齐。
143
+ * 绝不因「没有叶子」而自动豁免(S-Q4-4)。
144
+ *
145
+ * leaderEstimate 由调用方传 plan.ts deriveLeaderEstimate 的结果(形状兼容),
146
+ * 本模块不重复求和、不反写台账(F6/J8 同纪律)。
147
+ */
148
+ export function criterionExAnte(
149
+ row: unknown,
150
+ leaderEstimate: { totalMinutes: number; reported: number; expected: number } | null | undefined,
151
+ ): CriterionExAnte {
152
+ if (leaderEstimate && Number.isFinite(Number(leaderEstimate.totalMinutes))) {
153
+ return {
154
+ minutes: Number(leaderEstimate.totalMinutes),
155
+ complete: leaderEstimate.reported === leaderEstimate.expected && leaderEstimate.expected > 0,
156
+ }
157
+ }
158
+ const notice = isRecord(row) && isRecord(row.timeNotice) ? row.timeNotice : null
159
+ const declared = notice ? Number(notice.declaredMinutes) : NaN
160
+ if (Number.isFinite(declared) && declared > 0) return { minutes: declared, complete: true }
161
+ return { minutes: null, complete: false }
162
+ }
163
+
164
+ /** 判据结算输出(与 T5 参考实现 referenceQ3Settlement 同形,供生产绑定)。 */
165
+ export interface CriterionEvaluation {
166
+ readonly criterionResult: CriterionResult
167
+ readonly canBeDone: boolean
168
+ readonly needsReplacement: boolean
169
+ readonly exceptionRecorded: boolean
170
+ readonly reasons: string[]
171
+ }
172
+
173
+ /**
174
+ * [SCv2-T4][spec §3.5 第 4 步 / S-Q6-5 / D-4 推荐 A] 判据层结算判定(纯函数)。
175
+ *
176
+ * 达标(met)=事前预估之和 ≤10 **且** 事后单次尝试墙钟 ≤10(双条件同时满足);
177
+ * 任一不满足且无有效用户批准 ⇒ unmet(不得 done、记违规、转接替行);
178
+ * 有有效用户批准 ⇒ exception-approved(可 done、留例外、不生成接替行)。
179
+ *
180
+ * 批准时机(C-4 推荐 A,待裁定):批准必须不晚于本次结算(at <= settledAt);
181
+ * 结算后追认一律无效(防「事后洗白」),只能批准接替行。
182
+ *
183
+ * 严格口径(D-3 推荐 A,待裁定):事前预估未齐 / 墙钟缺失(被重置清空)
184
+ * ⇒ 不得宣称达标,按 unmet 处理并如实给出 reasons;受平台缺陷影响的行
185
+ * 可经 Q1 例外审批留痕后豁免(exception-approved 分支)。
186
+ */
187
+ export function evaluateCriterion(input: {
188
+ exAnteMinutes: number | null
189
+ exAnteComplete: boolean
190
+ wallClockMs: number | null
191
+ exception?: CriterionException | null
192
+ settledAt?: number
193
+ }): CriterionEvaluation {
194
+ const reasons: string[] = []
195
+ let over = false
196
+ if (!input.exAnteComplete) {
197
+ over = true
198
+ reasons.push('ex-ante-incomplete:事前预估未齐或缺失(D-3 严格口径,不得视为达标)')
199
+ } else if (input.exAnteMinutes !== null && input.exAnteMinutes > CRITERION_TARGET_MINUTES) {
200
+ over = true
201
+ reasons.push(`ex-ante-over:事前预估 ${input.exAnteMinutes} 分钟 > ${CRITERION_TARGET_MINUTES} 分钟目标`)
202
+ }
203
+ if (input.wallClockMs === null) {
204
+ over = true
205
+ reasons.push('wall-clock-unverified:单次尝试墙钟缺失(计时被重置或无时间戳),不得按 0 分钟判达标(Q6-A)')
206
+ } else if (input.wallClockMs > CRITERION_TARGET_MINUTES * 60_000) {
207
+ over = true
208
+ reasons.push(`wall-clock-over:本次尝试墙钟 ${(input.wallClockMs / 60_000).toFixed(2)} 分钟 > ${CRITERION_TARGET_MINUTES} 分钟目标`)
209
+ }
210
+ if (!over) {
211
+ return { criterionResult: 'met', canBeDone: true, needsReplacement: false, exceptionRecorded: false, reasons }
212
+ }
213
+ const exception = input.exception ?? null
214
+ if (exception) {
215
+ const settledAt = Number.isFinite(Number(input.settledAt)) ? Number(input.settledAt) : Date.now()
216
+ if (exception.at <= settledAt) {
217
+ return {
218
+ criterionResult: 'exception-approved',
219
+ canBeDone: true,
220
+ needsReplacement: false,
221
+ exceptionRecorded: true,
222
+ reasons: [...reasons, 'user-exception:用户明确批准并留痕(Q1-B 唯一例外通道)'],
223
+ }
224
+ }
225
+ reasons.push('approval-after-settlement:批准时间晚于本次结算,事后追认无效(C-4 推荐 A)')
226
+ }
227
+ return { criterionResult: 'unmet', canBeDone: false, needsReplacement: true, exceptionRecorded: false, reasons }
228
+ }
229
+
230
+ /**
231
+ * [SCv2-T4] T5 参考实现 referenceQ3Settlement 的同口径生产适配器(分钟入参)。
232
+ * 生产接线落盘后 T5 只需把 referenceQ3* 替换为本导出,断言口径保持不变。
233
+ */
234
+ export function q3SettlementVerdict(input: {
235
+ declaredMinutes?: number
236
+ wallClockMinutes?: number
237
+ userApproved?: boolean
238
+ }): CriterionEvaluation {
239
+ const exception: CriterionException | null = input.userApproved === true
240
+ ? { approvedBy: 'user', at: 1, reason: 'user-approved(参考夹具口径)', scope: 'task' }
241
+ : null
242
+ return evaluateCriterion({
243
+ exAnteMinutes: Number(input.declaredMinutes ?? 0),
244
+ exAnteComplete: true,
245
+ wallClockMs: Number(input.wallClockMinutes ?? 0) * 60_000,
246
+ exception,
247
+ settledAt: Date.now(),
248
+ })
249
+ }
250
+
251
+ /**
252
+ * [SCv2-T4][D-4 推荐 A] 判据违规审计条目(append-only,绝不抹除)。
253
+ * 行级最终结果取最后一次(接替)尝试;原始未批准超时保留在本数组供审计,
254
+ * 防「续跑洗白」。上限 20 条与 timeJournal 同纪律。
255
+ */
256
+ export function appendCriterionViolation(
257
+ existing: unknown,
258
+ entry: { at: number; attempt: number; wallClockMs: number | null; exAnteMinutes: number | null; reasons: string[] },
259
+ ): Array<Record<string, unknown>> {
260
+ const list = Array.isArray(existing) ? existing.filter(isRecord) : []
261
+ return [...list, { ...entry, kind: 'criterion-overrun' }].slice(-20)
262
+ }