dsh-workplan 3.0.2 → 3.0.6

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/host.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  } from './runtime.js'
25
25
  import { DEPARTMENT_IDS, isRecord } from './plan.js'
26
26
  import { autoResumeEnabledFrom } from './auto-resume.js'
27
+ import { pruneJournal } from './dept-journal.js'
27
28
 
28
29
  /*
29
30
  * [1.8.14] Identity of the modules this process actually loaded (N1).
@@ -66,6 +67,14 @@ const LOADED_BUILD = (() => {
66
67
  */
67
68
  const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000)
68
69
 
70
+ /*
71
+ * [3.0.6][第 2 批] 静态图表资产只读一次。
72
+ * 旧实现每次请求都 readFileSync 210KB(看板每次加载都拉一次),在请求路径上
73
+ * 做磁盘 I/O 没有必要:vendor 文件随插件发布、运行期不会变。缓存 Buffer 后
74
+ * 后续请求直接复用;读取失败不缓存,下次仍会重试。
75
+ */
76
+ let chartVendorBytes: Buffer | null = null
77
+
69
78
  function phaseLabel(phase: any) {
70
79
  if (phase === 'paused') return '本轮预算用尽,可续跑'
71
80
  if (phase === 'blocked') return '卡住了'
@@ -84,7 +93,7 @@ export const inject = ['tools', 'systemPrompt', 'llm', 'subagents', 'sessions']
84
93
  export const PROMPT_ORDER = 40
85
94
 
86
95
  const PROMPT_SECTION = [
87
- '本会话已启用自动任务分解。系统会在每个新用户任务的第一个模型步骤前生成计划,并先把计划显示在对话里;收到【任务分解】后,必须先调用 dsh_workplan_dispatch(默认 wait 等结果;预计较久时用 mode:"async" 先开跑),再做任何其他工具调用或回答。',
96
+ '本会话已启用自动任务分解。系统会在每个新用户任务的第一个模型步骤前生成计划,并先把计划显示在对话里;看到【任务分解】计划消息后,若插件未自动派发或需要续跑/重试,再调用 dsh_workplan_dispatch(默认 wait 等结果;预计较久时用 mode:"async" 先开跑)。若只收到「任务分解已在后台生成中」而尚未看到【任务分解】,不要手动派发,先告知用户正在分配并等待计划落地。',
88
97
  /*
89
98
  * [3.0.0] 用户 2026-11-14 十三条要求的提示词侧双保险(代码侧同源门禁见
90
99
  * v3-contract / comm-format / llm-rules / runtime)。文案不做发挥,只写
@@ -94,7 +103,7 @@ const PROMPT_SECTION = [
94
103
  '3.0.0 任务书质量要求(用户要求 3/6):插件派给部门负责人的每个子任务都携带 qualityRequirements(结果质量要求),部门负责人派给专家的每条任务也必须携带 qualityRequirements。负责人→专家缺它平台直接拒绝派发(DELEGATE_QUALITY_REQUIREMENTS_MISSING);主 Agent→部门负责人缺它则该子任务在派发时被直接拒发(DISPATCH_QUALITY_REQUIREMENTS_MISSING,不启动部门 Agent),须 replan 补齐后重派。你审阅计划时先看每个子任务是否写了清楚的质量要求。',
95
104
  '3.0.0 极简任务(用户要求 5,用户裁决 A=硬门槛):部门负责人派出的每条任务必须简单到像 1+1=2——一个动作、一个主产物、一项可独立验收,单句、≤300 字符、不含「并且/同时/另外/还要/以及/分别/顺便」等并列词;不满足即被拒绝并给出拆分提示(DELEGATE_TASK_NOT_ATOMIC)。',
96
105
  '3.0.0 角色与汇报(用户要求 7/8/9/10/11/12):部门组员角色已取消,只保留部门负责人与全球顶尖专家(role 只允许 expert);专家完成后必须以 JSON 汇报(证据块里的 report:keyResults/keyInfo/importantInfo/leadRequirements,精简、禁止重复,F10);部门负责人必须全面汇总本部门全部专家汇报后,以 JSON 交回主 Agent(departmentSummary:keyResults/keyInfo/importantInfo/sources,精简、禁止累赘重复,F11);等所有部门的汇总都交回后,由你再全面、深入整理汇总成最终成果交付给用户(用户要求 12)。',
97
- '3.0.2 版本(用户要求 13):本插件当前版本为 3.0.2。涉及版本号的对外表述一律写 3.0.2。',
106
+ '3.0.6 版本(用户要求 13):本插件当前版本为 3.0.6。涉及版本号的对外表述一律写 3.0.6。',
98
107
  /*
99
108
  * [2.5.1] 主 Agent 两轮深度思考协议(用户 2026-11-11 补充要求):部门三层
100
109
  * 执行者已有结算/再分配双门禁,主 Agent 自己也必须做到同一协议——提示词
@@ -256,6 +265,19 @@ export type WorkplanConfig = {
256
265
  * 环境变量:`DSH_WORKPLAN_FAIL_CLOSED_ON_INCOMPLETE=1|0`。
257
266
  */
258
267
  failClosedOnIncomplete?: boolean | 'auto'
268
+ /**
269
+ * [3.0.6][第 3 批①] `agent/turn-stopping` 等待在途规划/派发的上限(毫秒)。
270
+ * 默认 60 分钟;0 = 无限等待(旧行为)。只约束收尾等待,不构成执行时限。
271
+ */
272
+ turnStoppingMaxWaitMs?: number
273
+ /**
274
+ * [3.0.6][第 2 批] 留痕保留天数。**0(默认)= 永久保留,不自动删除**。
275
+ *
276
+ * 审计证据默认不该被清理;只有部署方明确配置正数(或环境变量
277
+ * `DSH_WORKPLAN_JOURNAL_RETENTION_DAYS`)时,才会在启动时和之后每 24 小时
278
+ * 删除超过该天数未更新的 `<planId>.jsonl`(单次最多 200 个最旧文件)。
279
+ */
280
+ journalRetentionDays?: number
259
281
  }
260
282
 
261
283
  function createUpdateTool(runtime: any) {
@@ -748,8 +770,9 @@ function createEscalateTool(runtime: any) {
748
770
  description:
749
771
  '子 Agent 遇阻时向父会话上报请示,并把该子任务置为「待指示」。'
750
772
  + '第三层专家(叶子)同样可用:请示会经 delegate 登记落到所属部门行的第三层台账,由部门负责人用 dsh_workplan_instruct 答复。'
773
+ + '3.0.5 硬规则:第三层专家上报后,部门负责人禁止另派给其他专家,必须梳理该问题与本部门全部任务执行状态、研究方案后,用 dsh_workplan_instruct 答复原专家,原专家继续执行。'
751
774
  + '遇阻(缺权限/缺输入/依赖产物缺失/需求自相矛盾/无法验证/同一命令连续两次失败/需要主 Agent 决定方向)时,'
752
- + '第一动作是调用本工具,然后停止推进、只做只读核对,等待主 Agent 指示。'
775
+ + '第一动作是调用本工具,然后停止推进、只做只读核对,等待主 Agent/负责人指示。'
753
776
  + '不需要外部决定时不要调用;调用后不要自行选定一个选项继续。',
754
777
  parameters: {
755
778
  type: 'object',
@@ -805,7 +828,7 @@ function createEscalateTool(runtime: any) {
805
828
  `${String(result.subtaskId ?? '')} 已登记为「待指示」`
806
829
  + (result.alreadyEscalated ? '(此前已登记,未重复提交)' : '')
807
830
  + `:${String(result.question ?? '')}`
808
- + '|现在停止推进,只做只读核对;等待主 Agent 指示后再继续。',
831
+ + '|现在停止推进,只做只读核对;等待主 Agent/部门负责人指示后再继续。第三层请示在答复前禁止改派给其他专家。',
809
832
  )
810
833
  },
811
834
  },
@@ -857,7 +880,8 @@ function createDelegateTool(runtime: any) {
857
880
  + '平台按当前模型家族合法集合自动钳制越界档并留痕,等级在其任务全生命周期生效。'
858
881
  + 'action="status" 查看梳理登记与下级进度。第三层专家叶子用 action="self_effort" 自配推理等级并提交执行前两轮深度思考产物'
859
882
  + '(先配置+先思考后开工:phase-0 以 low 启动,唯一职责=评估自身任务复杂度并提交 reasoningEffort+complexityRationale+deepThink{problemAnalysis,approach,approachBasis}+开工前预估 timeNotice{declaredMinutes:正整数分钟,reason?};'
860
- + '缺交/不合格 deepThink 硬拒 DEEP_THINK_MISSING/DEEP_THINK_INCOMPLETE、不接续;两项齐全登记后平台立即以自配档接续同一任务进入 phase-1,正式执行必须按第二轮方法流程步骤进行、全程少走弯路;成员自配为权威、分工表档仅建议)。',
883
+ + '缺交/不合格 deepThink 硬拒 DEEP_THINK_MISSING/DEEP_THINK_INCOMPLETE、不接续;两项齐全登记后平台立即以自配档接续同一任务进入 phase-1,正式执行必须按第二轮方法流程步骤进行、全程少走弯路;成员自配为权威、分工表档仅建议)。'
884
+ + '3.0.5 硬规则:任一第三层成员处于待指示(escalated)时,review/dispatch/direct 一律拒绝改派、重派或降级;负责人必须梳理该成员问题与本部门全部任务状态,研究方案后用 dsh_workplan_instruct 答复原成员,原成员继续执行。',
861
885
  parameters: {
862
886
  type: 'object',
863
887
  properties: {
@@ -1032,7 +1056,7 @@ export function createVerifyTool(runtime: any) {
1032
1056
  },
1033
1057
  phases: {
1034
1058
  type: 'object',
1035
- description: '三阶段证据:planning(问题梳理 + 可执行思路)、execution(执行步骤)、verification(逐项验证)。',
1059
+ description: '五步证据:planning(第一步问题梳理 + 第二步资源/工具/方案)、preparation(第三步准备与就绪证据)、execution(第四步执行步骤)、verification(第四步逐项验证与复盘)。',
1036
1060
  properties: {
1037
1061
  planning: {
1038
1062
  type: 'object',
@@ -1042,9 +1066,20 @@ export function createVerifyTool(runtime: any) {
1042
1066
  constraints: { type: 'array', items: { type: 'string' }, description: '约束条件' },
1043
1067
  unknowns: { type: 'array', items: { type: 'string' }, description: '未知或待确认项' },
1044
1068
  approach: { type: 'array', items: { type: 'string' }, description: '第二轮 · 方法流程步骤:基于第一轮全部结果理清的具体一步步执行、完美完成任务的方法、流程和步骤(每一步做什么、产出什么、如何证明)' },
1045
- approachBasis: { type: 'array', items: { type: 'string' }, description: '第二轮依据(必填):第二轮如何基于第一轮完成好的所有结果——第一轮的哪些事实/约束/矛盾决定了第二轮的哪些方法/流程/步骤' },
1069
+ approachBasis: { type: 'array', items: { type: 'string' }, description: '第二步依据(必填):第二步的资源、工具、方案如何基于第一步完成好的所有结果——第一步的哪些事实/约束/矛盾决定了第二步的哪些资源/工具/步骤' },
1070
+ resources: { type: 'array', items: { type: 'string' }, description: '第二步 · 资源研究:完成本任务需要哪些资源(数据/文件/权限/人/知识/时间),逐项写清用途与获取方式' },
1071
+ tools: { type: 'array', items: { type: 'string' }, description: '第二步 · 工具研究:需要哪些工具、每个工具用来做什么、为什么选它' },
1046
1072
  },
1047
- required: ['problemAnalysis', 'approach', 'approachBasis'],
1073
+ required: ['problemAnalysis', 'approach', 'approachBasis', 'resources', 'tools'],
1074
+ },
1075
+ preparation: {
1076
+ type: 'object',
1077
+ description: '第三步 · 准备:把第二步研究出的资源、工具、实施方案真正备齐,并给出可复核的就绪证据。',
1078
+ properties: {
1079
+ prepared: { type: 'array', items: { type: 'string' }, description: '已准备好的资源/工具清单:准备了什么、在哪里、是否可用' },
1080
+ evidence: { type: 'array', items: { type: 'string' }, description: '就绪证据:命令输出/文件路径/配置项/版本号/引用,与 prepared 一一对应' },
1081
+ },
1082
+ required: ['prepared', 'evidence'],
1048
1083
  },
1049
1084
  execution: {
1050
1085
  type: 'object',
@@ -1086,7 +1121,7 @@ export function createVerifyTool(runtime: any) {
1086
1121
  required: ['allPassed', 'checks', 'retrospective'],
1087
1122
  },
1088
1123
  },
1089
- required: ['planning', 'execution', 'verification'],
1124
+ required: ['planning', 'preparation', 'execution', 'verification'],
1090
1125
  },
1091
1126
  },
1092
1127
  required: ['phases'],
@@ -1209,6 +1244,7 @@ function createInstructTool(runtime: any) {
1209
1244
  description:
1210
1245
  '向一条「待指示」子任务下发决定:投递给对应子会话,并把该行恢复为执行中(closure=instructed)。'
1211
1246
  + '根会话可答复第一层部门行;部门负责人可答复自己派出的第三层专家(subtaskId 填自己的部门行 ID 或省略,用 member 或 sessionId 指定目标,二者至少其一)。'
1247
+ + '3.0.5 硬规则:第三层只能答复已经提交请示的原专家,投递成功后必须原专家继续执行;待指示期间负责人不得 review/dispatch/direct 改派。'
1212
1248
  + '只有目标子会话的直接父会话可调用,非直系一律拒绝;根路径只接受 closure=escalated 的行。'
1213
1249
  + '投递失败时状态不变(仍是待指示),按返回的 hint 重试或改用 dsh_workplan_update 明确放弃。',
1214
1250
  parameters: {
@@ -1864,8 +1900,45 @@ export function apply(ctx: any, config: WorkplanConfig = {}) {
1864
1900
  config.failClosedOnIncomplete,
1865
1901
  settingEnv('DSH_WORKPLAN_FAIL_CLOSED_ON_INCOMPLETE'),
1866
1902
  ),
1903
+ turnStoppingMaxWaitMs: numericSetting(config.turnStoppingMaxWaitMs, 'DSH_WORKPLAN_TURN_STOPPING_MAX_WAIT_MS', true),
1867
1904
  })
1868
1905
 
1906
+ /*
1907
+ * [3.0.6][第 2 批] 可选留痕清理:默认关闭(0 = 永久保留证据)。
1908
+ * 只有显式配置正数时才启用;启动先跑一次,之后每 24 小时一次。
1909
+ */
1910
+ const journalRetentionDays = (() => {
1911
+ const configured = numericSetting(config.journalRetentionDays, 'DSH_WORKPLAN_JOURNAL_RETENTION_DAYS', true)
1912
+ return configured !== undefined && configured > 0 ? Math.min(configured, 3650) : 0
1913
+ })()
1914
+ if (journalRetentionDays > 0) {
1915
+ const prune = () => {
1916
+ const result = pruneJournal({ retentionDays: journalRetentionDays, excludePlanIds: activePlanIdSet(runtime) })
1917
+ if (!result.ok) ctx.logger?.warn?.(`[dsh-workplan] journal 清理失败:${result.error}`)
1918
+ // 删除失败逐条 warn(ok 仍为 true,errors[] 是弱错误通道,不得静默)。
1919
+ if (Array.isArray(result.errors) && result.errors.length > 0) {
1920
+ for (const line of result.errors) console.warn(`[dsh-workplan] journal 清理异常:${String(line)}`)
1921
+ }
1922
+ return result
1923
+ }
1924
+ ctx.effect(() => {
1925
+ /*
1926
+ * [复审修复] 首次清理从激活同步路径挪到 10s 后:激活是同步路径,不能
1927
+ * 当场扫盘(readdir/stat 大目录会拖住插件注册)。卸载时清除——
1928
+ * journalRetentionTimer 同款的 ctx.effect 清理模式。
1929
+ */
1930
+ const firstPruneTimer = setTimeout(prune, 10_000)
1931
+ if (typeof firstPruneTimer?.unref === 'function') firstPruneTimer.unref()
1932
+ return () => clearTimeout(firstPruneTimer)
1933
+ })
1934
+ ctx.effect(() => {
1935
+ // 卫生类:不触发只少一次清理,不得拖住正在关闭的宿主。
1936
+ const journalRetentionTimer = setInterval(prune, 24 * 60 * 60 * 1000)
1937
+ if (typeof journalRetentionTimer?.unref === 'function') journalRetentionTimer.unref()
1938
+ return () => clearInterval(journalRetentionTimer)
1939
+ })
1940
+ }
1941
+
1869
1942
  ctx.effect(() =>
1870
1943
  ctx.systemPrompt.section({
1871
1944
  name: 'dsh-workplan',
@@ -1978,7 +2051,10 @@ export function apply(ctx: any, config: WorkplanConfig = {}) {
1978
2051
  return
1979
2052
  }
1980
2053
  try {
1981
- const body = readFileSync(new URL('../vendor/chart.umd.js', import.meta.url))
2054
+ if (!chartVendorBytes) {
2055
+ chartVendorBytes = readFileSync(new URL('../vendor/chart.umd.js', import.meta.url))
2056
+ }
2057
+ const body = chartVendorBytes
1982
2058
  res.statusCode = 200
1983
2059
  res.setHeader('content-type', 'text/javascript; charset=utf-8')
1984
2060
  res.setHeader('cache-control', 'public, max-age=3600')
@@ -1994,11 +2070,18 @@ export function apply(ctx: any, config: WorkplanConfig = {}) {
1994
2070
  })
1995
2071
 
1996
2072
  ctx.effect(() => () => runtime.dispose())
2073
+
2074
+ /*
2075
+ * [3.0.6][复审修复] 把 runtime 句柄交还给调用方:宿主契约不消费本返回值
2076
+ * (清理一律经上方 effect),测试与宿主编排需要观察 state.records /
2077
+ * 替换 startAutoDispatch 时可直接拿到同一实例,不必从工具闭包里挖。
2078
+ */
2079
+ return runtime
1997
2080
  }
1998
2081
 
1999
2082
  export const meta = {
2000
2083
  name,
2001
- version: '3.0.2',
2084
+ version: '3.0.6',
2002
2085
  promptOrder: PROMPT_ORDER,
2003
2086
  routes: ['/dsh-workplan/plans', '/dsh-workplan/vendor/chart.umd.js'],
2004
2087
  }
@@ -2019,7 +2102,14 @@ export function fileWriteGuardReason(
2019
2102
  writeTargets(agent: any, args: any): string[]
2020
2103
  },
2021
2104
  ) {
2022
- if (!isWriteShapedCall(exec)) return undefined
2105
+ /*
2106
+ * [复审修复] bash 写保护绕过:shell 类工具的 command 字符串(重定向/heredoc/
2107
+ * tee/sed -i/cp/mv)此前因参数形状不认(无 file_path/path)而整类绕过闸门。
2108
+ * 先解析出 shell 写目标(非 shell 调用为 null),形状闸门与 shell 闸门至少
2109
+ * 命中其一才继续。
2110
+ */
2111
+ const shellTargets = shellWriteTargets(exec)
2112
+ if (!isWriteShapedCall(exec) && shellTargets === null) return undefined
2023
2113
  // The three historical write tools pass their arguments through untouched, so
2024
2114
  // their behaviour stays exactly as before (argument-shape matching is only an
2025
2115
  // EXTENSION: a tool that used to be denied is still denied the same way).
@@ -2032,9 +2122,47 @@ export function fileWriteGuardReason(
2032
2122
  const extra = runtime.presentedWriteDenialReason(exec?.agent, { file_path: target })
2033
2123
  if (typeof extra === 'string') return extra
2034
2124
  }
2125
+ /*
2126
+ * [复审修复] shell 写目标:与上面同一判定出口——只拦「写入已交付文件」,
2127
+ * 纯读命令(cat/grep/less 该路径)解析不出写目标,天然放行。
2128
+ * 启发式局限(保守模式):只认 > / >> 重定向、tee、sed -i、mv/cp/install/dd
2129
+ * 的目标;命令拼接变量(cmd=path; $cmd)、eval、find -delete 等动态写法
2130
+ * 不在解析范围内——见 shellWriteTargets 注释。
2131
+ */
2132
+ if (shellTargets) {
2133
+ for (const target of shellTargets) {
2134
+ const extra = runtime.presentedWriteDenialReason(exec?.agent, { file_path: target })
2135
+ if (typeof extra === 'string') return extra
2136
+ }
2137
+ }
2035
2138
  return undefined
2036
2139
  }
2037
2140
 
2141
+ /*
2142
+ * [复审修复] 活跃 planId 集合:pruneJournal 只看 mtime,「活跃但安静」的计划
2143
+ * (久无新留痕、mtime 变旧)会被误删;把当前活跃 planId 传给 excludePlanIds
2144
+ * 即可保住。planning 在途时尚未铸出 planId(planId 在规划完成后才生成,占位
2145
+ * 记录 planId=null),因此 runtime.state.records 就是全部活跃 planId 的事实源。
2146
+ * 导出以便直接单测;读取失败返回空集——宁可少排除,也不让清理路径抛错。
2147
+ */
2148
+ export function activePlanIdSet(runtime: any): ReadonlySet<string> {
2149
+ const ids = new Set<string>()
2150
+ try {
2151
+ const records = runtime?.state?.records
2152
+ if (records instanceof Map) {
2153
+ for (const record of records.values()) {
2154
+ const direct = typeof record?.planId === 'string' ? record.planId.trim() : ''
2155
+ const nested = typeof record?.plan?.planId === 'string' ? record.plan.planId.trim() : ''
2156
+ const id = direct !== '' ? direct : (nested !== '' ? nested : null)
2157
+ if (id) ids.add(id)
2158
+ }
2159
+ }
2160
+ } catch {
2161
+ // 同上:名单读取失败不阻断清理。
2162
+ }
2163
+ return ids
2164
+ }
2165
+
2038
2166
  /**
2039
2167
  * [1.12.2] G2: recognise write calls by their argument shape, not by a tool-name
2040
2168
  * allow-list. The 1.8.18 version named write/edit/str_replace_editor only, so a
@@ -2061,3 +2189,78 @@ function isWriteShapedCall(exec: any) {
2061
2189
  // Every other write form names a single target: file_path or path.
2062
2190
  return typeof args.file_path === 'string' || typeof args.path === 'string'
2063
2191
  }
2192
+
2193
+ /*
2194
+ * [复审修复] shell 类工具的识别:exec.name 为 bash/shell/exec,或以它们为
2195
+ * 前缀且前缀后是 [-_] 分隔符或结尾(bash_exec、shell-tool 等宿主工具名变体)。
2196
+ * 要求分隔符是为了避免 'executor' 这类普通名字被误判进 shell 闸门。
2197
+ */
2198
+ function isShellLikeToolName(name: any): boolean {
2199
+ if (typeof name !== 'string' || name === '') return false
2200
+ if (name === 'bash' || name === 'shell' || name === 'exec') return true
2201
+ return /^(?:bash|shell|exec)(?:[-_]|$)/.test(name)
2202
+ }
2203
+
2204
+ /*
2205
+ * [复审修复] 从 shell 调用的 command 字符串解析「写目标路径」。
2206
+ *
2207
+ * 返回 null = 这不是 shell 类调用(或没有 command 参数),调用方据此跳过
2208
+ * shell 闸门;返回数组则可能为空(shell 调用但不含写形态,如纯读的
2209
+ * cat/grep/less)——空数组同样放行。多提取无害:每个候选最终仍走
2210
+ * presentedWriteDenialReason 的「已交付且计划未就绪」判定,普通路径直接
2211
+ * 放行;要防的是漏提取,所以解析宁可宽进。
2212
+ *
2213
+ * 保守模式只认这些强写信号:
2214
+ * - `>` / `>>` 重定向(含 heredoc:`cat <<EOF > path` 的重定向部分);
2215
+ * - `tee [-a] files...`(tee 是纯写管道,必须整组检查);
2216
+ * - `sed -i[.bak] ... files`(段内 -i 之后的全部非选项 token);
2217
+ * - `mv/cp/install 源... 目标`(只取最后一个非选项 token——源是读,只有
2218
+ * 目标是写,全取会把「复制自受保护文件」误拦成写);
2219
+ * - `dd of=path`。
2220
+ *
2221
+ * 启发式局限(有意保守,备查):
2222
+ * - 变量间接(cmd="> $f"; eval、sh -c 嵌套命令)不做展开;
2223
+ * - find -delete、perl -i、crontab 等少见写法不覆盖;
2224
+ * - 引号内带空格的路径按空白截断,不做完整 shell 词法分析;
2225
+ * - 超长命令只解析前 20k 字符。
2226
+ */
2227
+ const SHELL_COMMAND_PARSE_LIMIT = 20_000
2228
+ function shellWriteTargets(exec: any): string[] | null {
2229
+ if (!isShellLikeToolName(exec?.name)) return null
2230
+ const command = exec?.arguments?.command
2231
+ if (typeof command !== 'string' || command.trim() === '') return null
2232
+ const text = command.length > SHELL_COMMAND_PARSE_LIMIT ? command.slice(0, SHELL_COMMAND_PARSE_LIMIT) : command
2233
+ const targets = new Set<string>()
2234
+ const stripQuotes = (token: string) => token.replace(/^['"]+|['"]+$/g, '')
2235
+ const isOption = (token: string) => token === '-' || token.startsWith('-') || token === '--'
2236
+ const add = (token: string | undefined) => {
2237
+ const cleaned = stripQuotes(String(token ?? '')).trim()
2238
+ if (cleaned !== '') targets.add(cleaned)
2239
+ }
2240
+ // > / >> 重定向(兼容 fd 前缀 2>file、1> file;&> 合并重定向跳过——歧义大)。
2241
+ for (const match of text.matchAll(/(?<![&\d])\d*>>?\s*([^\s;|&<>]+)/g)) add(match[1])
2242
+ // 按命令段分隔:; | &&。单 &(2>&1 的合并目标)不拆,避免把 fd 描述切碎。
2243
+ for (const segment of text.split(/&&|[;|]/)) {
2244
+ const trimmed = segment.trim()
2245
+ if (trimmed === '') continue
2246
+ // tee [-a] files...:tee 之后到段尾的全部 token 都是写目标。
2247
+ const tee = /(?:^|\s)tee(?:\s+-[a-zA-Z]+)*\s+(\S(?:[\s\S]*?))?$/.exec(trimmed)
2248
+ if (tee && /\btee\b/.test(trimmed)) {
2249
+ for (const token of (tee[1] ?? '').split(/\s+/)) if (!isOption(token)) add(token)
2250
+ }
2251
+ // sed -i[.bak] ...:段内含 sed 且带 -i 选项时,取其后的全部非选项 token。
2252
+ const sed = /(?:^|\s)sed(?:\s+-[a-zA-Z]+)*\s+(-i\S*)(?:\s+([\s\S]*))?$/.exec(trimmed)
2253
+ if (sed) {
2254
+ for (const token of (sed[2] ?? '').split(/\s+/)) if (!isOption(token)) add(token)
2255
+ }
2256
+ // mv/cp/install 源... 目标:只取最后一个非选项 token(目标是写、源是读)。
2257
+ const mover = /(?:^|\s)(?:mv|cp|install)(?:\s+-[a-zA-Z]+)*\s+([\s\S]+)$/.exec(trimmed)
2258
+ if (mover) {
2259
+ const tokens = (mover[1] ?? '').split(/\s+/).filter((token) => !isOption(token))
2260
+ add(tokens[tokens.length - 1])
2261
+ }
2262
+ // dd of=path(of= 后到空白为止)。
2263
+ for (const match of trimmed.matchAll(/(?:^|\s)of=([^\s;|&]+)/g)) add(match[1])
2264
+ }
2265
+ return [...targets]
2266
+ }
package/src/lessons.ts CHANGED
@@ -18,7 +18,7 @@
18
18
  * 本模块不依赖 harness 服务,只做纯函数 + 同步文件读写,便于离线回放与测试。
19
19
  */
20
20
  import { createHash } from 'node:crypto'
21
- import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
21
+ import { appendFileSync, chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
22
22
  import { homedir } from 'node:os'
23
23
  import { dirname, join } from 'node:path'
24
24
 
@@ -189,26 +189,41 @@ export function resolveLessonsFile(env: NodeJS.ProcessEnv = process.env): string
189
189
  return join(homedir(), '.dsh', 'workplan', 'lessons.jsonl')
190
190
  }
191
191
 
192
- function readJsonLines(file: string): any[] {
193
- if (!existsSync(file)) return []
192
+ type JsonLinesSnapshot = {
193
+ rows: any[]
194
+ /** 无法解析的行原样保留:重写文件时必须带回去,禁止静默丢弃。 */
195
+ corrupt: string[]
196
+ /** 读失败与「文件不存在」必须分开:前者绝不能当成空文件。 */
197
+ readError: unknown | null
198
+ }
199
+
200
+ function readJsonLinesSnapshot(file: string): JsonLinesSnapshot {
201
+ if (!existsSync(file)) return { rows: [], corrupt: [], readError: null }
194
202
  let text = ''
195
203
  try {
196
204
  text = readFileSync(file, 'utf8')
197
- } catch {
198
- return []
205
+ } catch (readError) {
206
+ return { rows: [], corrupt: [], readError }
199
207
  }
200
208
  const rows: any[] = []
209
+ const corrupt: string[] = []
201
210
  for (const line of text.split('\n')) {
202
211
  const trimmed = line.trim()
203
212
  if (!trimmed) continue
204
213
  try {
205
214
  const parsed = JSON.parse(trimmed)
206
215
  if (isRecord(parsed)) rows.push(parsed)
216
+ else corrupt.push(trimmed)
207
217
  } catch {
208
- // 单行损坏不能拖垮整份记忆:跳过该行,其余教训继续可用。
218
+ // 单行损坏不能拖垮整份记忆:读端跳过该行,写端原样保留。
219
+ corrupt.push(trimmed)
209
220
  }
210
221
  }
211
- return rows
222
+ return { rows, corrupt, readError: null }
223
+ }
224
+
225
+ function readJsonLines(file: string): any[] {
226
+ return readJsonLinesSnapshot(file).rows
212
227
  }
213
228
 
214
229
  function coerceRecord(raw: any): LessonRecord | null {
@@ -240,12 +255,52 @@ export function readLessons(file: string = resolveLessonsFile()): LessonRecord[]
240
255
  .filter((item): item is LessonRecord => item !== null)
241
256
  }
242
257
 
243
- function writeLessonsAtomic(file: string, records: LessonRecord[]) {
244
- mkdirSync(dirname(file), { recursive: true })
245
- const body = `${records.map((item) => JSON.stringify(item)).join('\n')}\n`
258
+ /**
259
+ * [3.0.3] 防符号链接投毒:写入前确认目标不是符号链接,否则抛错拒绝
260
+ * (风格同 LESSONS_READ_FAILED)。攻击者把教训文件或临时文件路径换成
261
+ * 符号链接后,一次「原子重写」就会被重定向去覆盖无关文件。
262
+ */
263
+ function assertLessonsWriteTarget(file: string, what: string) {
264
+ let stat
265
+ try {
266
+ stat = lstatSync(file)
267
+ } catch {
268
+ return // 不存在:正常新写。
269
+ }
270
+ if (stat.isSymbolicLink()) {
271
+ throw new Error(`LESSONS_WRITE_REFUSED: 拒绝向符号链接${what}写入 ${file},以免被重定向覆盖无关文件`)
272
+ }
273
+ }
274
+
275
+ function writeLessonsAtomic(file: string, records: LessonRecord[], corrupt: string[] = []) {
276
+ assertLessonsWriteTarget(file, '')
277
+ assertLessonsWriteTarget(`${file}.bak`, '备份')
278
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
279
+ const lines = [
280
+ ...records.map((item) => JSON.stringify(item)),
281
+ // 坏行原样留在文件末尾:下次读端仍会跳过,但绝不会因为一次重写就消失。
282
+ ...corrupt,
283
+ ]
284
+ const body = lines.length > 0 ? `${lines.join('\n')}\n` : ''
285
+ // 覆盖前留一代备份;备份失败不阻断主写入(主写入仍走临时文件 + 原子改名)。
286
+ if (existsSync(file)) {
287
+ try {
288
+ copyFileSync(file, `${file}.bak`)
289
+ } catch {
290
+ // 备份是尽力而为:权限不足等情况下,主写入的失败会由调用方显式上报。
291
+ }
292
+ }
246
293
  const tmp = `${file}.tmp-${process.pid}`
247
- writeFileSync(tmp, body, 'utf8')
294
+ assertLessonsWriteTarget(tmp, '临时文件')
295
+ writeFileSync(tmp, body, { encoding: 'utf8', mode: 0o600 })
248
296
  renameSync(tmp, file)
297
+ // 已存在文件收紧到 0o600(rename 覆盖了同名符号链接之外的目标时,
298
+ // 权限可能带着旧文件的宽松位):best-effort,文件系统不支持时不断写。
299
+ try {
300
+ chmodSync(file, 0o600)
301
+ } catch {
302
+ // best-effort。
303
+ }
249
304
  }
250
305
 
251
306
  export type RecordLessonInput = {
@@ -281,7 +336,22 @@ export function recordLesson(input: RecordLessonInput): RecordLessonResult | nul
281
336
  problems: retro.problems,
282
337
  prevention: retro.prevention,
283
338
  })
284
- const records = readLessons(file)
339
+ const snapshot = readJsonLinesSnapshot(file)
340
+ /*
341
+ * 数据安全红线:读失败 ≠ 没有历史。
342
+ * 以前这里把 EACCES/EMFILE/EIO 当成空数组,随后「读-改-写」会把整份永久记忆
343
+ * 覆盖成刚写入的这一条。现在读失败直接抛错,由 runtime 的 catch 记录到状态里;
344
+ * 坏行则原样带回写端,重写时不会丢。
345
+ */
346
+ if (snapshot.readError) {
347
+ const message = snapshot.readError instanceof Error
348
+ ? snapshot.readError.message
349
+ : String(snapshot.readError)
350
+ throw new Error(`LESSONS_READ_FAILED: 无法读取 ${file},已拒绝写入以免覆盖历史教训(${message})`)
351
+ }
352
+ const records = snapshot.rows
353
+ .map(coerceRecord)
354
+ .filter((item): item is LessonRecord => item !== null)
285
355
  const sameRow = records.findIndex((item) =>
286
356
  item.planId === input.planId && item.subtaskId === input.subtaskId)
287
357
  const sameIssue = records.findIndex((item) =>
@@ -322,10 +392,13 @@ export function recordLesson(input: RecordLessonInput): RecordLessonResult | nul
322
392
  // 时间正序保留最近 N 条;id 冲突(同一毫秒重复)时无需特殊处理,读端按行。
323
393
  const kept = records.slice(Math.max(0, records.length - MAX_LESSON_RECORDS))
324
394
  try {
325
- writeLessonsAtomic(file, kept)
326
- } catch {
395
+ writeLessonsAtomic(file, kept, snapshot.corrupt)
396
+ } catch (error) {
397
+ // 符号链接投毒是拒绝不是故障:不上 append 兜底,直接向上抛。
398
+ if (error instanceof Error && error.message.startsWith('LESSONS_WRITE_REFUSED')) throw error
327
399
  try {
328
- mkdirSync(dirname(file), { recursive: true })
400
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
401
+ assertLessonsWriteTarget(file, '')
329
402
  appendFileSync(file, `${JSON.stringify(base)}\n`, 'utf8')
330
403
  } catch {
331
404
  return null
package/src/llm-rules.ts CHANGED
@@ -191,11 +191,12 @@ export function buildLlmRulesBrief(info: LlmRulesBriefInfo = {}): string {
191
191
  * 与代码门禁同源(planDelegations 的 checkAtomicAssignment、comm-format 的
192
192
  * F10/F11),提示词只是把代码已经在执行的规则提前说清楚。
193
193
  */
194
- lines.push('- 极简任务硬门槛(用户要求 5,用户裁决 A=硬门槛):你派出的每一条任务必须简单到像 1+1=2——一个动作、一个主产物、一项可独立验收;出现「并且/同时/另外/还要/以及/分别/顺便」或分号并列、或超过 300 字符,平台直接拒绝派发(DELEGATE_TASK_NOT_ATOMIC)并给出拆分提示,实例:不要派「分析并修复并写测试」,要拆成「读 X 定位原因」「按原因改 Y」「写 Z 用例」三条。')
194
+ lines.push('- 极简任务硬门槛(用户要求 5,用户裁决 A=硬门槛):你派出的每一条任务必须简单到像 1+1=2——一个动作、一个主产物、一项可独立验收;出现「并且/并/同时/另外/还要/以及/分别/顺便/然后/接着/再」或分号并列、或一个任务里写了多句(含英文句点分隔的多句)、或超过 300 字符,平台直接拒绝派发(DELEGATE_TASK_NOT_ATOMIC)并给出拆分提示,实例:不要派「分析并修复并写测试」,要拆成「读 X 定位原因」「按原因改 Y」「写 Z 用例」三条。')
195
195
  lines.push('- 质量要求硬门槛(用户要求 6):每一条分派都必须带 qualityRequirements(至少 1 条、每条 ≤400 字符、最多 8 条),写清「成果必须达到什么要求、什么算合格、怎么算不合格」;缺它平台拒绝派发(DELEGATE_QUALITY_REQUIREMENTS_MISSING)。任务书会把这块原文交给专家。')
196
196
  lines.push('- 专家汇报必须精简且是 JSON(用户要求 7):专家完成后在证据块里给出 report(keyResults/keyInfo/importantInfo/leadRequirements 四个字符串数组,每数组 ≤6 条、每条 ≤200 字符,禁止重复);你收到后逐条核对,缺项或重复会被格式门禁退回(F10)。')
197
197
  lines.push('- 你的汇总必须精简且是 JSON(用户要求 8/10/11):汇总本部门全部专家汇报后,在证据块里给出 departmentSummary(keyResults/keyInfo/importantInfo/sources 四个字符串数组,sources 必须覆盖全部已派发专家,禁止累赘重复);不合格会被退回(F11)。汇总完成后直接交回主 Agent,不需要另建文件。')
198
198
  lines.push('- 执行时间与验收:你和每位全球顶尖专家均没有总时长、单次时长、空闲或回执硬截止。开工预估及其汇总只用于协调与告知,未报齐时如实显示部分和,但不构成分钟判据;不得以耗时、预估超额或未经时间批准为由拒绝 done,extendMs 已停用。完成只由真实结果、产物、结构化证据和质量验收决定;用户显式取消与真实错误仍然有效。')
199
+ lines.push('- 专家遇阻处置(3.0.5 硬规则,机制已强制):任何专家调用 dsh_workplan_escalate 后,禁止用 review/dispatch/direct 把该问题改派、重派或降级给其他专家;你必须先用 action="status" 全面梳理该成员的问题与本部门全部 delegates 执行状态,再研究形成解决方案,最后用 dsh_workplan_instruct 答复原 member;平台在该成员待指示期间会硬拒一切改派动作,投递成功后强制原专家继续执行。')
199
200
  }
200
201
  return lines.join('\n')
201
202
  }
@@ -637,7 +638,7 @@ export function buildDelegateePrompt(input: {
637
638
  '- 开工前必须先预估本人任务耗时(整数分钟)并经 self_effort 的 timeNotice={ declaredMinutes: 正整数分钟, reason? } 上报部门负责人,未上报不接续(T6/D9 硬门禁:ESTIMATE_MISSING/ESTIMATE_INVALID);该上报只是协调信息,必须如实预估。你和部门负责人执行任务均没有总时长、单次时长、空闲或回执硬截止;预估或实际耗时不会触发延期、超时接手,也不影响 done 验收。',
638
639
  '- 必须在确保自身任务完成品质非常高的前提下,完美、超高效率地执行;严禁低效执行与浪费 token。',
639
640
  '- 你是第三层叶子执行者:不得派生任何第四层 Agent/子会话;无法完成时在结论首行写 BLOCKED: 原因 并说明缺什么,不要空转。',
640
- '- 遇阻上报通道:遇阻(缺权限/缺输入/依赖产物缺失/需求自相矛盾/无法验证/需要负责人决定方向)时,第一动作是调用 dsh_workplan_escalate({ "question": "需要负责人回答的单个问题", "options": ["可选方向"], "needs": ["需要谁提供什么"] })——请示会经 delegate 登记落到你所属部门行的第三层台账(待指示),由部门负责人用 dsh_workplan_instruct 答复你;调用成功后停止推进、只做只读核对,不要自行选定一个选项继续。',
641
+ '- 遇阻上报通道(3.0.5 四步闭环):遇阻(缺权限/缺输入/依赖产物缺失/需求自相矛盾/无法验证/需要负责人决定方向)时,第一动作是调用 dsh_workplan_escalate({ "question": "需要负责人回答的单个问题", "options": ["可选方向"], "needs": ["需要谁提供什么"] })。流程必须严格为:你先向部门负责人报告具体问题→负责人全面梳理你的问题与本部门全部已派发任务执行状态→负责人研究形成解决方案→负责人用 dsh_workplan_instruct 把方案告诉你→你继续执行原任务。平台禁止负责人在你待指示期间把你改派给其他专家;你必须是继续执行的人。调用 escalate 成功后停止推进、只做只读核对,不要自行选定一个选项继续。',
641
642
  '- 完成后把结论与逐项证据(命令输出/文件/引用)用简洁中文回报给部门负责人会话;同时把同一份结构化结论写入 reports/wp-member-<你的成员名>-<任务代号>.json(相对工作目录,目录不存在就创建)作为结算兜底。',
642
643
  `- 结果块契约:以 ${EVIDENCE_MARKER_BEGIN} 开头、${EVIDENCE_MARKER_END} 结尾,内含合法 JSON(status ∈ done/blocked/partial、phases 三阶段、acceptance 逐条带证据)。`,
643
644
  '',