dsh-workplan 1.12.3 → 2.0.2

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/src/plan.ts CHANGED
@@ -12,6 +12,7 @@ import { createHash, randomUUID } from 'node:crypto'
12
12
  import { DEPARTMENT_CAPABILITIES, departmentCapability } from './departments.js'
13
13
  import { MAX_TASK_ANCHOR_CHARS } from './understanding.js'
14
14
  import { isMappingDigest, verifyMappingDigest } from './supersede-digest.js'
15
+ import { phaseSummaryLine, threePhasePromptLines, validatePhaseEvidence } from './three-phase.js'
15
16
 
16
17
  export const PLAN_VERSION = 1
17
18
 
@@ -104,7 +105,7 @@ export const UPDATE_MARKER_END = '<!-- DSH-WORKPLAN-UPDATE:END -->'
104
105
  /** Upper bound for the run-time conversation window (single truncation point). */
105
106
  export const MAX_CONVERSATION_CHARS = 7000
106
107
  /** Upper bound for one child evidence block; longer blocks are truncated. */
107
- export const MAX_EVIDENCE_BLOCK_CHARS = 8000
108
+ export const MAX_EVIDENCE_BLOCK_CHARS = 12000
108
109
  export const MAX_EVIDENCE_ACCEPTANCE = 20
109
110
  export const MAX_EVIDENCE_ARTIFACTS = 20
110
111
  export const MAX_EVIDENCE_NEEDS = 10
@@ -1955,7 +1956,7 @@ const BLOCKED_LINE = /^\s*(BLOCKED|受阻|无法完成)\s*[::]\s*/i
1955
1956
  * the acceptance table cannot drift apart between the runtime and the replay.
1956
1957
  * It never invents evidence and never upgrades a failed self-check to done.
1957
1958
  */
1958
- export function adjudicateResult({ output, strict = true, expectedAcceptance = [] }: any) {
1959
+ export function adjudicateResult({ output, strict = true, expectedAcceptance = [], requirePhases = true }: any) {
1959
1960
  const text = typeof output === 'string' ? output : ''
1960
1961
  const parsed = parseEvidenceBlock(text)
1961
1962
  if (!strict) {
@@ -2096,6 +2097,30 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2096
2097
  .map((item: string) => truncate(String(item), 120)).slice(0, 5).join(';')}。请按计划验收逐条给出证据后再回报。`,
2097
2098
  }
2098
2099
  }
2100
+ /*
2101
+ * [1.13.0] 完成前必须交出三阶段证据(用户 2026-11-05 的强制要求)。
2102
+ *
2103
+ * 这是「先规划后执行」从口号变成契约的唯一落点:子 Agent 只在提示词里
2104
+ * 被要求时,仍可以先动手、最后补一句「已规划」;只有把规划内容做成
2105
+ * 收尾证据的一部分并在这里校验,缺规划/缺验证的结果才不可能被记成 done。
2106
+ *
2107
+ * 兼容边界:`requirePhases:false` 保留给历史回放与明确关闭该门禁的部署;
2108
+ * `strict:false` 的旧语义不受影响(前面已经返回)。
2109
+ */
2110
+ const phaseCheck = requirePhases === false
2111
+ ? null
2112
+ : validatePhaseEvidence(payload.phases, expectedAcceptance)
2113
+ if (phaseCheck && !phaseCheck.ok) {
2114
+ return {
2115
+ status: 'blocked',
2116
+ verification: 'unverified',
2117
+ acceptance,
2118
+ artifacts,
2119
+ needs,
2120
+ error: `三阶段证据不完整(未按「规划→执行→验证」回报):${phaseCheck.errors.slice(0, 6).join(';')}`,
2121
+ phases: null,
2122
+ }
2123
+ }
2099
2124
  return {
2100
2125
  status: 'done',
2101
2126
  verification: hasUnverified ? 'unverified' : 'structured',
@@ -2103,6 +2128,8 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2103
2128
  artifacts,
2104
2129
  needs,
2105
2130
  error: null,
2131
+ phases: phaseCheck?.phases ?? null,
2132
+ phaseSummary: phaseCheck?.phases ? phaseSummaryLine(phaseCheck.phases) : null,
2106
2133
  }
2107
2134
  }
2108
2135
 
@@ -3651,6 +3678,7 @@ export function buildChildPrompt({
3651
3678
  conversationContext = '',
3652
3679
  statuses = null,
3653
3680
  previousFailure = null,
3681
+ lessonsBrief = '',
3654
3682
  }: any) {
3655
3683
  /*
3656
3684
  * Every field below is read defensively.
@@ -3816,6 +3844,11 @@ export function buildChildPrompt({
3816
3844
  ...(resumeHint ? [resumeHint] : []),
3817
3845
  ...(pendingInstruction ? [pendingInstruction] : []),
3818
3846
  '',
3847
+ ...threePhasePromptLines(),
3848
+ ...(typeof lessonsBrief === 'string' && lessonsBrief.trim() !== ''
3849
+ ? ['', lessonsBrief.trim(), '']
3850
+ : []),
3851
+ '',
3819
3852
  '执行要求:',
3820
3853
  '- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',
3821
3854
  '- 你没有派发权限,也不能重启或安装任何服务;遇到这类步骤,必须先上报(见下方「遇阻上报」),再停止推进等待指示,不要空转。',
@@ -3835,13 +3868,13 @@ export function buildChildPrompt({
3835
3868
  '',
3836
3869
  '结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
3837
3870
  EVIDENCE_MARKER_BEGIN,
3838
- '{"status":"done","blockedReason":"","acceptance":[{"criterion":"A1 把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[],"question":"","options":[]}',
3871
+ '{"status":"done","blockedReason":"","phases":{"planning":{"problemAnalysis":["要解决的问题 1(含现状/约束/未知/主要矛盾)"],"constraints":["..."],"unknowns":["..."],"approach":["第 1 步:做什么 → 产出什么 → 如何证明"]},"execution":{"steps":["实际执行的步骤"],"deviations":[]},"verification":{"allPassed":true,"checks":[{"criterion":"A1","method":"怎么验证","evidence":"命令输出/文件/引用"}],"requirementCheck":"逐条核对用户原要求的结果","retrospective":{"problems":["本次遇到的问题(现象+根因)"],"detours":["走过的弯路/返工/无效尝试;确实没有就写 []"],"resolutions":["最终是如何解决的"],"prevention":["以后如何预防再犯:遇到…先…"]}}},"acceptance":[{"criterion":"A1 把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[],"question":"","options":[]}',
3839
3872
  EVIDENCE_MARKER_END,
3840
3873
  '- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',
3841
3874
  '- acceptance 必须逐条覆盖上面的验收标准:criterion 以 A1、A2… 开头对号入座(编号不可省略);result 只能是 pass / fail / unverified。无法确认就写 unverified,不要写 pass。',
3842
3875
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
3843
3876
  '- needs 写需要其他部门配合的事项,每条写清「哪个部门 + 需要什么 + 用来做什么」;它会被登记为待处理需求,主 Agent 必须处置后计划才能交付。不要直连其他子 Agent。',
3844
3877
  '- question/options 只在受阻上报时填写;done 时保持空字符串/空数组。',
3845
- '- 整块不超过 8000 字符;不要把这段模板本身抄进结果块。',
3878
+ '- 整块不超过 12000 字符;不要把这段模板本身抄进结果块。',
3846
3879
  ].join('\n'))
3847
3880
  }
package/src/runtime.ts CHANGED
@@ -70,9 +70,19 @@ import {
70
70
  DEPARTMENTS,
71
71
  DEPARTMENT_IDS,
72
72
  MAX_HANDOFF_RESPONSE_CHARS,
73
+ findSubtask,
73
74
  } from './plan.js'
74
75
  import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
75
76
  import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js'
77
+ import { phaseGateFromErrors, phaseSummaryLine, validatePhaseEvidence } from './three-phase.js'
78
+ import {
79
+ lessonStats,
80
+ rankLessons,
81
+ readLessons,
82
+ recordLesson,
83
+ renderLessonsBrief,
84
+ resolveLessonsFile,
85
+ } from './lessons.js'
76
86
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
77
87
  import { supersedePlanRecord } from './supersede.js'
78
88
  import { createProgressWatchdog, describeError } from './watchdog.js'
@@ -826,11 +836,39 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
826
836
  const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists)
827
837
  const escalated = verdict.status === 'blocked'
828
838
  && typeof verdict.question === 'string' && verdict.question.trim() !== ''
839
+ /*
840
+ * [2.0.0] 自我学习闭环的出口:完成且带复盘证据时,立刻写入永久记忆。
841
+ *
842
+ * 写入失败不改变本次判定(教训没记住是记忆层的问题,不能把已经做完的工作
843
+ * 判成未完成),但会把失败原因写进本条状态,避免「以为记住了其实没写」。
844
+ */
845
+ let lessonNote = ''
846
+ if (verdict.status === 'done' && verdict.phases?.verification?.retrospective) {
847
+ try {
848
+ const saved = recordLesson({
849
+ file: resolveLessonsFile(),
850
+ planId: String(record.plan?.planId ?? ''),
851
+ subtaskId: subtask.id,
852
+ department: String(subtask.department ?? ''),
853
+ title: `${subtask.id} ${subtask.title}`,
854
+ cwd: typeof options.cwd === 'string' ? options.cwd : '',
855
+ retrospective: verdict.phases.verification.retrospective,
856
+ now: Date.now(),
857
+ })
858
+ if (saved) {
859
+ lessonNote = saved.mode === 'repeated'
860
+ ? `已记住同类教训(第 ${saved.record.occurrences} 次,永久记忆)`
861
+ : '复盘已写入永久教训记忆'
862
+ }
863
+ } catch (error) {
864
+ lessonNote = `复盘记忆写入失败:${truncate(error instanceof Error ? error.message : String(error), 120)}`
865
+ }
866
+ }
829
867
  writeSubtaskStatus(record, subtask.id, {
830
868
  status: verdict.status,
831
869
  progress: 100,
832
870
  finishedAt: Date.now(),
833
- summary: truncate(output, 3000),
871
+ summary: truncate(lessonNote ? `${output}\n[自我学习] ${lessonNote}` : output, 3000),
834
872
  error: verdict.error,
835
873
  verification: verdict.verification,
836
874
  acceptance: verdict.acceptance,
@@ -959,6 +997,23 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
959
997
  if (child.controller.signal.aborted) {
960
998
  throw child.controller.signal.reason ?? abortError()
961
999
  }
1000
+ /*
1001
+ * [2.0.0] 自我学习闭环的入口:把与本子任务最相关的历史教训注入提示词。
1002
+ *
1003
+ * 记忆读取失败不能影响本次派发(宁可不带教训,也不能因此不做任务),
1004
+ * 所以整段用 try/catch 兜底;文件不存在时 renderLessonsBrief 返回空串。
1005
+ */
1006
+ let lessonsBrief = ''
1007
+ try {
1008
+ lessonsBrief = renderLessonsBrief({
1009
+ department: subtask.department,
1010
+ title: subtask.title,
1011
+ objective: subtask.objective,
1012
+ cwd: options.cwd,
1013
+ })
1014
+ } catch {
1015
+ lessonsBrief = ''
1016
+ }
962
1017
  activation = await ctx.subagents.startActivation({
963
1018
  provider: 'spawn',
964
1019
  label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
@@ -991,6 +1046,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
991
1046
  conversationContext,
992
1047
  statuses: record.statuses,
993
1048
  previousFailure: attempt > 1 ? lastFailure : null,
1049
+ lessonsBrief,
994
1050
  }),
995
1051
  }],
996
1052
  parent: options.agent,
@@ -4044,6 +4100,87 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
4044
4100
  }
4045
4101
  }
4046
4102
 
4103
+ /**
4104
+ * [1.13.0] 阶段三(验证阶段)的插件核验入口(用户 2026-11-05)。
4105
+ *
4106
+ * 「按提交内容判阶段」:
4107
+ * - 只有 planning + execution 证据齐全,才会进入阶段三核验;
4108
+ * - 缺 planning/execution 的调用以 PHASE_GATE 拒绝并列出待补项 —— 这是一道
4109
+ * 证据门禁,不是对插件的全局禁用(「阶段一、二禁用插件」只是 2026-11-05
4110
+ * 当次优化会话的过程约束,2.0.2 起不再作为所有会话的产品规则);
4111
+ * - 阶段三核验会逐条检查:问题梳理/可执行思路是否有实质内容、执行步骤
4112
+ * 是否记录、验证是否全部通过、验证记录是否覆盖全部验收标准。
4113
+ *
4114
+ * 它不写状态、不替子 Agent 宣称完成:最终是否 done 仍由 `adjudicateResult`
4115
+ * 对同一份 phases 再判一次,避免「核验工具说通过」与「结果块没写」两套真相。
4116
+ */
4117
+ async function verifySubtask(agent: any, args: any) {
4118
+ const childSession = agent?.session
4119
+ if (!childSession?.id) {
4120
+ return { ok: false, code: 'NO_SESSION', passed: false, error: '只能在部门子会话内做阶段三核验' }
4121
+ }
4122
+ const parentId = childSession.header?.parentSession
4123
+ if (!parentId) {
4124
+ return {
4125
+ ok: false,
4126
+ code: 'NOT_CHILD_SESSION',
4127
+ passed: false,
4128
+ error: '当前不是子会话,无法反查父计划;三阶段核验只对已派发的部门子任务开放',
4129
+ }
4130
+ }
4131
+ let record = state.records.get(parentId)
4132
+ if (!record?.plan) {
4133
+ const parent = (ctx as any).sessions?.get?.(parentId)
4134
+ if (parent) {
4135
+ try {
4136
+ record = reconstructFromSession(parent)
4137
+ } catch (error) {
4138
+ pushRecordError({ errors: [] } as any, error)
4139
+ }
4140
+ }
4141
+ }
4142
+ if (!record?.plan) {
4143
+ return { ok: false, code: 'NO_PLAN', passed: false, error: '父会话没有可关联的计划,无法核验' }
4144
+ }
4145
+ const row = (record.statuses ?? []).find((item: any) => item?.childId === childSession.id)
4146
+ if (!row) {
4147
+ return { ok: false, code: 'NO_SUBTASK', passed: false, error: '计划里找不到与本子会话关联的子任务(childId 未登记)' }
4148
+ }
4149
+ if (row.status === 'done') {
4150
+ return { ok: false, code: 'ALREADY_DONE', passed: false, subtaskId: row.subtaskId, error: '该子任务已标记完成,无需再次核验' }
4151
+ }
4152
+ const found = findSubtask(record.plan, row.subtaskId)
4153
+ const expectedAcceptance = Array.isArray(found?.subtask?.acceptance) ? found.subtask.acceptance : []
4154
+ const rawPhases = isRecord(args?.phases)
4155
+ ? args.phases
4156
+ : { planning: args?.planning, execution: args?.execution, verification: args?.verification }
4157
+ const check = validatePhaseEvidence(rawPhases, expectedAcceptance)
4158
+ if (!check.ok || !check.phases) {
4159
+ const gate = phaseGateFromErrors(check.errors)
4160
+ return {
4161
+ ok: false,
4162
+ passed: false,
4163
+ code: gate === 'phase-1-2' ? 'PHASE_GATE' : 'VERIFICATION_INCOMPLETE',
4164
+ phase: gate,
4165
+ planId: record.plan.planId,
4166
+ subtaskId: row.subtaskId,
4167
+ gaps: check.errors,
4168
+ error: gate === 'phase-1-2'
4169
+ ? `阶段三核验缺少前两阶段证据:先完成「梳理问题 → 形成可执行思路」并实际执行,再提交阶段三核验。${check.errors.slice(0, 5).join(';')}`
4170
+ : `阶段三核验未通过:${check.errors.slice(0, 5).join(';')}`,
4171
+ }
4172
+ }
4173
+ return {
4174
+ ok: true,
4175
+ passed: true,
4176
+ phase: 'verification',
4177
+ planId: record.plan.planId,
4178
+ subtaskId: row.subtaskId,
4179
+ summary: phaseSummaryLine(check.phases),
4180
+ message: '插件核验通过:三阶段证据齐全、验证全部通过。现在把同一份 phases 写进结果块并提交。',
4181
+ }
4182
+ }
4183
+
4047
4184
  /**
4048
4185
  * [1.11.0] 子 → 父的唯一反向通道(T4 C-09 / T6 M5)。
4049
4186
  *
@@ -5684,6 +5821,50 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5684
5821
  }
5685
5822
  }
5686
5823
 
5824
+ /**
5825
+ * [2.0.0] 只读的「永久教训记忆」入口。
5826
+ *
5827
+ * 用户要求这些经验必须能被复核。主 Agent 在阶段三可以用它查:记住了什么、
5828
+ * 哪些同类错误在重复发生、文件到底写在哪。它只读文件,不改任何计划状态。
5829
+ */
5830
+ async function lessonsTool(_agent: any, args: any) {
5831
+ const parsed = isRecord(args) ? args : {}
5832
+ const action = String(parsed.action ?? 'list')
5833
+ const file = resolveLessonsFile()
5834
+ try {
5835
+ if (action === 'stats') {
5836
+ return { ok: true, ...lessonStats(file) }
5837
+ }
5838
+ if (action === 'search') {
5839
+ const query = String(parsed.query ?? '').trim()
5840
+ const rows = query
5841
+ ? readLessons(file).filter((item) =>
5842
+ `${item.title} ${item.problems.join(' ')} ${item.detours.join(' ')} ${item.prevention.join(' ')}`
5843
+ .toLowerCase()
5844
+ .includes(query.toLowerCase()))
5845
+ : readLessons(file)
5846
+ const limit = Math.min(Math.max(Number(parsed.limit) || 10, 1), 50)
5847
+ return { ok: true, file, total: rows.length, lessons: rows.slice(-limit).reverse() }
5848
+ }
5849
+ const department = typeof parsed.department === 'string' ? parsed.department.trim() : ''
5850
+ const limit = Math.min(Math.max(Number(parsed.limit) || 10, 1), 50)
5851
+ const lessons = department
5852
+ ? readLessons(file).filter((item) => item.department === department)
5853
+ : readLessons(file)
5854
+ const ranked = department
5855
+ ? rankLessons(lessons, { department, limit, now: Date.now() })
5856
+ : lessons.slice(-limit).reverse()
5857
+ return { ok: true, file, total: lessons.length, lessons: ranked }
5858
+ } catch (error) {
5859
+ return {
5860
+ ok: false,
5861
+ file,
5862
+ error: truncate(error instanceof Error ? error.message : String(error), 300),
5863
+ lessons: [],
5864
+ }
5865
+ }
5866
+ }
5867
+
5687
5868
  function dispose() {
5688
5869
  // [1.10.4] 定时器不能吊住进程,也不能在记录清空后复活一个已销毁的计划。
5689
5870
  for (const record of state.records.values()) clearAutoResumeTimer(record, 'dispose')
@@ -5706,6 +5887,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5706
5887
  statusTool,
5707
5888
  followupTool,
5708
5889
  escalateTool,
5890
+ verifyTool: verifySubtask,
5891
+ lessonsTool,
5709
5892
  instructTool,
5710
5893
  handoffTool,
5711
5894
  replanPlan,