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.
@@ -16,7 +16,7 @@
16
16
  * 由 channel-expert 按契约 §3 实现)。
17
17
  */
18
18
  import { randomBytes } from 'node:crypto';
19
- import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
19
+ import { appendFileSync, chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, unlinkSync } from 'node:fs';
20
20
  import { homedir } from 'node:os';
21
21
  import { dirname, join } from 'node:path';
22
22
  /** 接口版本(契约 §1:字面量 1)。 */
@@ -235,7 +235,8 @@ export function deptJournalPath(planId) {
235
235
  }
236
236
  /**
237
237
  * 追加一条留痕(契约 §2):先 validate,再 mkdirSync(recursive)+appendFileSync。
238
- * 任何失败(校验不过 / planId 非法 / 写盘失败)显式返回 JOURNAL_WRITE_FAILED,绝不静默。
238
+ * 任何失败(校验不过 / planId 非法 / 写盘失败 / 回读不一致)显式返回
239
+ * JOURNAL_WRITE_FAILED / JOURNAL_READBACK_FAILED,绝不静默。
239
240
  */
240
241
  export function appendDeptMessage(msg) {
241
242
  const verdict = validateDeptMessage(msg);
@@ -249,19 +250,152 @@ export function appendDeptMessage(msg) {
249
250
  return { ok: false, code: 'JOURNAL_WRITE_FAILED', error: errorText(error) };
250
251
  }
251
252
  try {
252
- mkdirSync(dirname(path), { recursive: true });
253
- appendFileSync(path, `${JSON.stringify(verdict.value)}\n`, 'utf8');
253
+ /*
254
+ * [安全加固] 防符号链接投毒:journal 文件若是符号链接则跳过写入并告警——
255
+ * 绝不跟随链接把审计内容写到链接指向的任意路径;失败显式返回(绝不静默)。
256
+ * lstatSync 抛错(文件不存在等)属正常首写场景,交给 appendFileSync 处理。
257
+ */
258
+ try {
259
+ if (lstatSync(path).isSymbolicLink()) {
260
+ console.warn(`dsh-workplan: journal 文件是符号链接,跳过写入 path=${path}`);
261
+ return {
262
+ ok: false,
263
+ code: 'JOURNAL_WRITE_FAILED',
264
+ error: `JOURNAL_WRITE_FAILED: journal 文件是符号链接,已跳过写入 path=${path}(防链接投毒)。`,
265
+ };
266
+ }
267
+ }
268
+ catch {
269
+ /* 文件不存在(首写)或 lstat 失败:继续走正常写入,错误由 appendFileSync 显式上报。 */
270
+ }
271
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
272
+ appendFileSync(path, `${JSON.stringify(verdict.value)}\n`, { encoding: 'utf8', mode: 0o600 });
273
+ try {
274
+ // 既有文件权限收紧为 0o600(best-effort;新建文件已由 mode 覆盖)。
275
+ chmodSync(path, 0o600);
276
+ }
277
+ catch {
278
+ /* best-effort:权限收紧失败不阻断追加。 */
279
+ }
254
280
  }
255
281
  catch (error) {
256
282
  return { ok: false, code: 'JOURNAL_WRITE_FAILED', error: errorText(error) };
257
283
  }
284
+ /* [T3][回读校验] 写后读回比对关键字段(见下方 helper 注释),不一致绝不静默。 */
285
+ const readback = verifyJournalAppendReadback(path, verdict.value);
286
+ if (!readback.ok)
287
+ return { ok: false, code: 'JOURNAL_READBACK_FAILED', error: readback.error };
258
288
  return { ok: true, path };
259
289
  }
290
+ /*
291
+ * [T3][回读校验] journal 追加写后读回。依据:reports/wp-member-expert-persist-call-T1.json
292
+ * 写盘点⑦(dept-journal.ts:290-308;2026-11-17 复核 mkdirSync:302、appendFileSync:303
293
+ * 无漂移)与 reports/wp-member-expert-storage-T1-storage.json(落盘路径
294
+ * <journalDir>/<planId>.jsonl,事件流追加、非整文件快照)。
295
+ * appendFileSync 成功后读回文件末尾窗口,JSON 解析后比对关键字段(v/id/planId/
296
+ * subtaskId/kind/ts/body 头 120 字摘要)。找不到匹配行 → 返回显式错误码
297
+ * JOURNAL_READBACK_FAILED(本模块「绝不静默」契约=显式错误码+处置指引,与
298
+ * JOURNAL_WRITE_FAILED 同口径;负责人硬性要求③的「抛显式错误」在本模块以
299
+ * 显式错误码实现,错误信息含文件路径与期望/实际摘要及指引:重试或让主 Agent
300
+ * 手动制定计划)。纯读校验、不写盘 → 幂等(硬性要求④)。
301
+ *
302
+ * [复审修复][O(n²)→O(窗口)] journal 默认永久保留,文件会涨到 MB 级;旧实现每次
303
+ * 追加后 readFileSync 整个文件逐行 parse,热路径每次请示/指示/完成/预估都全文件
304
+ * 重读。改为只读末尾一个窗口(JOURNAL_READBACK_WINDOW_BYTES):
305
+ * - O_APPEND 保证刚写入的行必在文件末尾;窗口 ≥ 单行最大体积(body ≤4000 字符 +
306
+ * data JSON ≤4000 字符,单 line 远小于 64KB)即可命中;
307
+ * - 窗口起点可能落在行中间 → 首行 parse 失败直接跳过该坏行继续;
308
+ * - 并发追加交错不会把新行挤出窗口(需同一瞬时有 64KB 更新行写入才会,
309
+ * 概率可忽略;且失败显式可重试)。
310
+ */
311
+ function deptMessageKeyDigest(record) {
312
+ return JSON.stringify({
313
+ v: record?.v,
314
+ id: record?.id,
315
+ planId: record?.planId,
316
+ subtaskId: record?.subtaskId,
317
+ kind: record?.kind,
318
+ ts: record?.ts,
319
+ bodyHead: String(record?.body ?? '').slice(0, 120),
320
+ });
321
+ }
322
+ /** 回读窗口字节数:64KB。单行最大体积(body 4000 + data JSON 4000 + 结构开销)远小于此。 */
323
+ const JOURNAL_READBACK_WINDOW_BYTES = 64 * 1024;
324
+ /** 只读文件末尾一个窗口(按字节);文件小于窗口则全读。读失败由调用方捕获。 */
325
+ function readJournalTailWindow(path, windowBytes) {
326
+ const { size } = statSync(path);
327
+ const start = Math.max(0, size - windowBytes);
328
+ const length = size - start;
329
+ if (length <= 0)
330
+ return '';
331
+ const buffer = Buffer.alloc(length);
332
+ const fd = openSync(path, 'r');
333
+ try {
334
+ let offset = 0;
335
+ while (offset < length) {
336
+ const read = readSync(fd, buffer, offset, length - offset, start + offset);
337
+ if (read <= 0)
338
+ break;
339
+ offset += read;
340
+ }
341
+ }
342
+ finally {
343
+ closeSync(fd);
344
+ }
345
+ return buffer.toString('utf8');
346
+ }
347
+ function verifyJournalAppendReadback(path, expected) {
348
+ let text;
349
+ try {
350
+ text = readJournalTailWindow(path, JOURNAL_READBACK_WINDOW_BYTES);
351
+ }
352
+ catch (error) {
353
+ return {
354
+ ok: false,
355
+ error: `dsh-workplan: journal 回读校验读不到文件 path=${path}(${errorText(error)})。`
356
+ + '请重试;若多次失败请让主 Agent 手动制定计划。',
357
+ };
358
+ }
359
+ const lines = text.split('\n').filter((line) => line.trim() !== '');
360
+ const want = deptMessageKeyDigest(expected);
361
+ /*
362
+ * 只扫末尾窗口:窗口首行可能被截断(窗口从行中间字节开始),parse 失败跳过该
363
+ * 坏行继续;新追加的行(digest 匹配)由 O_APPEND 保证在文件末尾、必在窗口内。
364
+ */
365
+ for (const line of lines) {
366
+ let parsed = null;
367
+ try {
368
+ parsed = JSON.parse(line);
369
+ }
370
+ catch {
371
+ continue;
372
+ }
373
+ if (deptMessageKeyDigest(parsed) === want)
374
+ return { ok: true };
375
+ }
376
+ const tail = lines.slice(-5);
377
+ const actual = tail
378
+ .map((line) => {
379
+ try {
380
+ return deptMessageKeyDigest(JSON.parse(line));
381
+ }
382
+ catch {
383
+ return '<不可解析行>';
384
+ }
385
+ })
386
+ .join(' | ');
387
+ return {
388
+ ok: false,
389
+ error: `dsh-workplan: journal 落盘回读校验失败 path=${path}:写入内容与读回内容关键字段不一致。`
390
+ + `期望=${want.slice(0, 300)} 实际(末${tail.length}行)=${actual.slice(0, 300)}。`
391
+ + '请重试;若多次失败请让主 Agent 手动制定计划。',
392
+ };
393
+ }
260
394
  /**
261
395
  * 按追加序回放留痕(契约 §2):
262
396
  * - 文件不存在 → 空列表(ok:true);
263
397
  * - 坏行(JSON 损坏或校验不过)计入 skipped,不静默吞;
264
- * - kind/since 过滤后按 limit 截取:默认 500、上限 5000;
398
+ * - kind/since 过滤后按 limit 截取:默认 500、上限 5000;newest=true 取最近,否则取最早;
265
399
  * - planId 非法或读盘失败 → 显式 JOURNAL_READ_FAILED。
266
400
  */
267
401
  export function readDeptMessages(planId, filter) {
@@ -315,5 +449,88 @@ export function readDeptMessages(planId, filter) {
315
449
  continue;
316
450
  matched.push(message);
317
451
  }
318
- return { ok: true, messages: matched.slice(0, limit), skipped };
452
+ return { ok: true, messages: filter?.newest ? matched.slice(-limit) : matched.slice(0, limit), skipped };
453
+ }
454
+ /**
455
+ * [3.0.6][第 2 批] 留痕目录的可选保留策略(默认关闭)。
456
+ *
457
+ * 审计证据不该被默认删除,所以本函数只在显式配置
458
+ * `journalRetentionDays > 0`(或环境变量
459
+ * `DSH_WORKPLAN_JOURNAL_RETENTION_DAYS`)时被调用。它只删除同时满足以下
460
+ * 条件的文件:目录里直接的 `.jsonl` 普通文件、文件名是合法 planId、
461
+ * mtime 早于保留天数。活跃计划会持续追加,mtime 保持新,因此不会被误删。
462
+ *
463
+ * 单次最多删 `maxFiles`(默认 200,上限 1000)个最旧文件,避免一次启动
464
+ * 长时间阻塞;删除失败不再静默跳过——逐个 console.warn 一行并收集进
465
+ * 返回值的 `errors[]`(ok 保持 true,兼容既有调用方)。
466
+ *
467
+ * [复审修复] `excludePlanIds`(可选):文件名(去 .jsonl)在集合内的一律
468
+ * 跳过删除,防「活跃但安静」(久无新消息、mtime 变旧)的计划被误删。
469
+ */
470
+ export function pruneJournal(options) {
471
+ const days = Number(options?.retentionDays);
472
+ if (!Number.isFinite(days) || days <= 0)
473
+ return { ok: true, scanned: 0, deleted: [] };
474
+ const dir = resolveJournalDir();
475
+ let names;
476
+ try {
477
+ names = readdirSync(dir);
478
+ }
479
+ catch (error) {
480
+ if (error?.code === 'ENOENT')
481
+ return { ok: true, scanned: 0, deleted: [] };
482
+ return { ok: false, scanned: 0, deleted: [], error: errorText(error) };
483
+ }
484
+ const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
485
+ const cutoff = now - days * 24 * 60 * 60 * 1000;
486
+ const maxFiles = Math.max(0, Math.min(1000, Math.trunc(options?.maxFiles ?? 200)));
487
+ const exclude = options?.excludePlanIds;
488
+ const candidates = [];
489
+ for (const name of names) {
490
+ if (!name.endsWith('.jsonl'))
491
+ continue;
492
+ const planId = name.slice(0, -'.jsonl'.length);
493
+ if (!PLAN_ID_PATTERN.test(planId))
494
+ continue;
495
+ // 活跃但安静的保护名单:在册计划即使 mtime 超期也不删。
496
+ if (exclude?.has(planId))
497
+ continue;
498
+ const path = join(dir, name);
499
+ try {
500
+ const stat = lstatSync(path);
501
+ // 只删普通文件;符号链接一律跳过(防越界删除)。
502
+ if (!stat.isFile() || stat.isSymbolicLink())
503
+ continue;
504
+ if (stat.mtimeMs >= cutoff)
505
+ continue;
506
+ candidates.push({ name, path, mtimeMs: stat.mtimeMs });
507
+ }
508
+ catch {
509
+ // 单个文件 stat 失败不影响其他文件,最后以 scanned 如实反映总数。
510
+ continue;
511
+ }
512
+ }
513
+ candidates.sort((a, b) => a.mtimeMs - b.mtimeMs);
514
+ const deleted = [];
515
+ const errors = [];
516
+ for (const candidate of candidates.slice(0, maxFiles)) {
517
+ try {
518
+ unlinkSync(candidate.path);
519
+ deleted.push(candidate.name);
520
+ }
521
+ catch (error) {
522
+ // 单个 unlink 失败不再静默:收集原因 + 逐条 warn(ok 保持 true 兼容)。
523
+ const reason = `${candidate.name}: ${errorText(error)}`;
524
+ errors.push(reason);
525
+ console.warn(`dsh-workplan: journal 保留清理删除失败 ${reason} path=${candidate.path}`);
526
+ }
527
+ }
528
+ const result = {
529
+ ok: true,
530
+ scanned: names.length,
531
+ deleted,
532
+ };
533
+ if (errors.length > 0)
534
+ result.errors = errors;
535
+ return result;
319
536
  }
package/lib/host.js CHANGED
@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
14
14
  import { applyHardeningHeaders, cancelToolOutputSchema, createWorkplanRuntime, dispatchToolOutputSchema, plannerOutputSchema, replanToolOutputSchema, statusToolOutputSchema, updateToolOutputSchema, } from './runtime.js';
15
15
  import { DEPARTMENT_IDS, isRecord } from './plan.js';
16
16
  import { autoResumeEnabledFrom } from './auto-resume.js';
17
+ import { pruneJournal } from './dept-journal.js';
17
18
  /*
18
19
  * [1.8.14] Identity of the modules this process actually loaded (N1).
19
20
  *
@@ -54,6 +55,13 @@ const LOADED_BUILD = (() => {
54
55
  * "restarted after the fix" from "same process, rebuilt files on disk".
55
56
  */
56
57
  const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
58
+ /*
59
+ * [3.0.6][第 2 批] 静态图表资产只读一次。
60
+ * 旧实现每次请求都 readFileSync 210KB(看板每次加载都拉一次),在请求路径上
61
+ * 做磁盘 I/O 没有必要:vendor 文件随插件发布、运行期不会变。缓存 Buffer 后
62
+ * 后续请求直接复用;读取失败不缓存,下次仍会重试。
63
+ */
64
+ let chartVendorBytes = null;
57
65
  function phaseLabel(phase) {
58
66
  if (phase === 'paused')
59
67
  return '本轮预算用尽,可续跑';
@@ -75,7 +83,7 @@ export const name = 'dsh-workplan';
75
83
  export const inject = ['tools', 'systemPrompt', 'llm', 'subagents', 'sessions'];
76
84
  export const PROMPT_ORDER = 40;
77
85
  const PROMPT_SECTION = [
78
- '本会话已启用自动任务分解。系统会在每个新用户任务的第一个模型步骤前生成计划,并先把计划显示在对话里;收到【任务分解】后,必须先调用 dsh_workplan_dispatch(默认 wait 等结果;预计较久时用 mode:"async" 先开跑),再做任何其他工具调用或回答。',
86
+ '本会话已启用自动任务分解。系统会在每个新用户任务的第一个模型步骤前生成计划,并先把计划显示在对话里;看到【任务分解】计划消息后,若插件未自动派发或需要续跑/重试,再调用 dsh_workplan_dispatch(默认 wait 等结果;预计较久时用 mode:"async" 先开跑)。若只收到「任务分解已在后台生成中」而尚未看到【任务分解】,不要手动派发,先告知用户正在分配并等待计划落地。',
79
87
  /*
80
88
  * [3.0.0] 用户 2026-11-14 十三条要求的提示词侧双保险(代码侧同源门禁见
81
89
  * v3-contract / comm-format / llm-rules / runtime)。文案不做发挥,只写
@@ -85,7 +93,7 @@ const PROMPT_SECTION = [
85
93
  '3.0.0 任务书质量要求(用户要求 3/6):插件派给部门负责人的每个子任务都携带 qualityRequirements(结果质量要求),部门负责人派给专家的每条任务也必须携带 qualityRequirements。负责人→专家缺它平台直接拒绝派发(DELEGATE_QUALITY_REQUIREMENTS_MISSING);主 Agent→部门负责人缺它则该子任务在派发时被直接拒发(DISPATCH_QUALITY_REQUIREMENTS_MISSING,不启动部门 Agent),须 replan 补齐后重派。你审阅计划时先看每个子任务是否写了清楚的质量要求。',
86
94
  '3.0.0 极简任务(用户要求 5,用户裁决 A=硬门槛):部门负责人派出的每条任务必须简单到像 1+1=2——一个动作、一个主产物、一项可独立验收,单句、≤300 字符、不含「并且/同时/另外/还要/以及/分别/顺便」等并列词;不满足即被拒绝并给出拆分提示(DELEGATE_TASK_NOT_ATOMIC)。',
87
95
  '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)。',
88
- '3.0.2 版本(用户要求 13):本插件当前版本为 3.0.2。涉及版本号的对外表述一律写 3.0.2。',
96
+ '3.0.6 版本(用户要求 13):本插件当前版本为 3.0.6。涉及版本号的对外表述一律写 3.0.6。',
89
97
  /*
90
98
  * [2.5.1] 主 Agent 两轮深度思考协议(用户 2026-11-11 补充要求):部门三层
91
99
  * 执行者已有结算/再分配双门禁,主 Agent 自己也必须做到同一协议——提示词
@@ -664,8 +672,9 @@ function createEscalateTool(runtime) {
664
672
  name: 'dsh_workplan_escalate',
665
673
  description: '子 Agent 遇阻时向父会话上报请示,并把该子任务置为「待指示」。'
666
674
  + '第三层专家(叶子)同样可用:请示会经 delegate 登记落到所属部门行的第三层台账,由部门负责人用 dsh_workplan_instruct 答复。'
675
+ + '3.0.5 硬规则:第三层专家上报后,部门负责人禁止另派给其他专家,必须梳理该问题与本部门全部任务执行状态、研究方案后,用 dsh_workplan_instruct 答复原专家,原专家继续执行。'
667
676
  + '遇阻(缺权限/缺输入/依赖产物缺失/需求自相矛盾/无法验证/同一命令连续两次失败/需要主 Agent 决定方向)时,'
668
- + '第一动作是调用本工具,然后停止推进、只做只读核对,等待主 Agent 指示。'
677
+ + '第一动作是调用本工具,然后停止推进、只做只读核对,等待主 Agent/负责人指示。'
669
678
  + '不需要外部决定时不要调用;调用后不要自行选定一个选项继续。',
670
679
  parameters: {
671
680
  type: 'object',
@@ -718,7 +727,7 @@ function createEscalateTool(runtime) {
718
727
  return textContent(`${String(result.subtaskId ?? '')} 已登记为「待指示」`
719
728
  + (result.alreadyEscalated ? '(此前已登记,未重复提交)' : '')
720
729
  + `:${String(result.question ?? '')}`
721
- + '|现在停止推进,只做只读核对;等待主 Agent 指示后再继续。');
730
+ + '|现在停止推进,只做只读核对;等待主 Agent/部门负责人指示后再继续。第三层请示在答复前禁止改派给其他专家。');
722
731
  },
723
732
  },
724
733
  async execute(args, exec) {
@@ -767,7 +776,8 @@ function createDelegateTool(runtime) {
767
776
  + '平台按当前模型家族合法集合自动钳制越界档并留痕,等级在其任务全生命周期生效。'
768
777
  + 'action="status" 查看梳理登记与下级进度。第三层专家叶子用 action="self_effort" 自配推理等级并提交执行前两轮深度思考产物'
769
778
  + '(先配置+先思考后开工:phase-0 以 low 启动,唯一职责=评估自身任务复杂度并提交 reasoningEffort+complexityRationale+deepThink{problemAnalysis,approach,approachBasis}+开工前预估 timeNotice{declaredMinutes:正整数分钟,reason?};'
770
- + '缺交/不合格 deepThink 硬拒 DEEP_THINK_MISSING/DEEP_THINK_INCOMPLETE、不接续;两项齐全登记后平台立即以自配档接续同一任务进入 phase-1,正式执行必须按第二轮方法流程步骤进行、全程少走弯路;成员自配为权威、分工表档仅建议)。',
779
+ + '缺交/不合格 deepThink 硬拒 DEEP_THINK_MISSING/DEEP_THINK_INCOMPLETE、不接续;两项齐全登记后平台立即以自配档接续同一任务进入 phase-1,正式执行必须按第二轮方法流程步骤进行、全程少走弯路;成员自配为权威、分工表档仅建议)。'
780
+ + '3.0.5 硬规则:任一第三层成员处于待指示(escalated)时,review/dispatch/direct 一律拒绝改派、重派或降级;负责人必须梳理该成员问题与本部门全部任务状态,研究方案后用 dsh_workplan_instruct 答复原成员,原成员继续执行。',
771
781
  parameters: {
772
782
  type: 'object',
773
783
  properties: {
@@ -934,7 +944,7 @@ export function createVerifyTool(runtime) {
934
944
  },
935
945
  phases: {
936
946
  type: 'object',
937
- description: '三阶段证据:planning(问题梳理 + 可执行思路)、execution(执行步骤)、verification(逐项验证)。',
947
+ description: '五步证据:planning(第一步问题梳理 + 第二步资源/工具/方案)、preparation(第三步准备与就绪证据)、execution(第四步执行步骤)、verification(第四步逐项验证与复盘)。',
938
948
  properties: {
939
949
  planning: {
940
950
  type: 'object',
@@ -944,9 +954,20 @@ export function createVerifyTool(runtime) {
944
954
  constraints: { type: 'array', items: { type: 'string' }, description: '约束条件' },
945
955
  unknowns: { type: 'array', items: { type: 'string' }, description: '未知或待确认项' },
946
956
  approach: { type: 'array', items: { type: 'string' }, description: '第二轮 · 方法流程步骤:基于第一轮全部结果理清的具体一步步执行、完美完成任务的方法、流程和步骤(每一步做什么、产出什么、如何证明)' },
947
- approachBasis: { type: 'array', items: { type: 'string' }, description: '第二轮依据(必填):第二轮如何基于第一轮完成好的所有结果——第一轮的哪些事实/约束/矛盾决定了第二轮的哪些方法/流程/步骤' },
957
+ approachBasis: { type: 'array', items: { type: 'string' }, description: '第二步依据(必填):第二步的资源、工具、方案如何基于第一步完成好的所有结果——第一步的哪些事实/约束/矛盾决定了第二步的哪些资源/工具/步骤' },
958
+ resources: { type: 'array', items: { type: 'string' }, description: '第二步 · 资源研究:完成本任务需要哪些资源(数据/文件/权限/人/知识/时间),逐项写清用途与获取方式' },
959
+ tools: { type: 'array', items: { type: 'string' }, description: '第二步 · 工具研究:需要哪些工具、每个工具用来做什么、为什么选它' },
960
+ },
961
+ required: ['problemAnalysis', 'approach', 'approachBasis', 'resources', 'tools'],
962
+ },
963
+ preparation: {
964
+ type: 'object',
965
+ description: '第三步 · 准备:把第二步研究出的资源、工具、实施方案真正备齐,并给出可复核的就绪证据。',
966
+ properties: {
967
+ prepared: { type: 'array', items: { type: 'string' }, description: '已准备好的资源/工具清单:准备了什么、在哪里、是否可用' },
968
+ evidence: { type: 'array', items: { type: 'string' }, description: '就绪证据:命令输出/文件路径/配置项/版本号/引用,与 prepared 一一对应' },
948
969
  },
949
- required: ['problemAnalysis', 'approach', 'approachBasis'],
970
+ required: ['prepared', 'evidence'],
950
971
  },
951
972
  execution: {
952
973
  type: 'object',
@@ -988,7 +1009,7 @@ export function createVerifyTool(runtime) {
988
1009
  required: ['allPassed', 'checks', 'retrospective'],
989
1010
  },
990
1011
  },
991
- required: ['planning', 'execution', 'verification'],
1012
+ required: ['planning', 'preparation', 'execution', 'verification'],
992
1013
  },
993
1014
  },
994
1015
  required: ['phases'],
@@ -1104,6 +1125,7 @@ function createInstructTool(runtime) {
1104
1125
  name: 'dsh_workplan_instruct',
1105
1126
  description: '向一条「待指示」子任务下发决定:投递给对应子会话,并把该行恢复为执行中(closure=instructed)。'
1106
1127
  + '根会话可答复第一层部门行;部门负责人可答复自己派出的第三层专家(subtaskId 填自己的部门行 ID 或省略,用 member 或 sessionId 指定目标,二者至少其一)。'
1128
+ + '3.0.5 硬规则:第三层只能答复已经提交请示的原专家,投递成功后必须原专家继续执行;待指示期间负责人不得 review/dispatch/direct 改派。'
1107
1129
  + '只有目标子会话的直接父会话可调用,非直系一律拒绝;根路径只接受 closure=escalated 的行。'
1108
1130
  + '投递失败时状态不变(仍是待指示),按返回的 hint 重试或改用 dsh_workplan_update 明确放弃。',
1109
1131
  parameters: {
@@ -1732,7 +1754,47 @@ export function apply(ctx, config = {}) {
1732
1754
  * 运行上下文(提供 `headlessStartup` 服务)才硬失败,交互式会话不受影响。
1733
1755
  */
1734
1756
  failClosedOnIncomplete: failClosedOnIncompleteFrom(config.failClosedOnIncomplete, settingEnv('DSH_WORKPLAN_FAIL_CLOSED_ON_INCOMPLETE')),
1757
+ turnStoppingMaxWaitMs: numericSetting(config.turnStoppingMaxWaitMs, 'DSH_WORKPLAN_TURN_STOPPING_MAX_WAIT_MS', true),
1735
1758
  });
1759
+ /*
1760
+ * [3.0.6][第 2 批] 可选留痕清理:默认关闭(0 = 永久保留证据)。
1761
+ * 只有显式配置正数时才启用;启动先跑一次,之后每 24 小时一次。
1762
+ */
1763
+ const journalRetentionDays = (() => {
1764
+ const configured = numericSetting(config.journalRetentionDays, 'DSH_WORKPLAN_JOURNAL_RETENTION_DAYS', true);
1765
+ return configured !== undefined && configured > 0 ? Math.min(configured, 3650) : 0;
1766
+ })();
1767
+ if (journalRetentionDays > 0) {
1768
+ const prune = () => {
1769
+ const result = pruneJournal({ retentionDays: journalRetentionDays, excludePlanIds: activePlanIdSet(runtime) });
1770
+ if (!result.ok)
1771
+ ctx.logger?.warn?.(`[dsh-workplan] journal 清理失败:${result.error}`);
1772
+ // 删除失败逐条 warn(ok 仍为 true,errors[] 是弱错误通道,不得静默)。
1773
+ if (Array.isArray(result.errors) && result.errors.length > 0) {
1774
+ for (const line of result.errors)
1775
+ console.warn(`[dsh-workplan] journal 清理异常:${String(line)}`);
1776
+ }
1777
+ return result;
1778
+ };
1779
+ ctx.effect(() => {
1780
+ /*
1781
+ * [复审修复] 首次清理从激活同步路径挪到 10s 后:激活是同步路径,不能
1782
+ * 当场扫盘(readdir/stat 大目录会拖住插件注册)。卸载时清除——
1783
+ * journalRetentionTimer 同款的 ctx.effect 清理模式。
1784
+ */
1785
+ const firstPruneTimer = setTimeout(prune, 10_000);
1786
+ if (typeof firstPruneTimer?.unref === 'function')
1787
+ firstPruneTimer.unref();
1788
+ return () => clearTimeout(firstPruneTimer);
1789
+ });
1790
+ ctx.effect(() => {
1791
+ // 卫生类:不触发只少一次清理,不得拖住正在关闭的宿主。
1792
+ const journalRetentionTimer = setInterval(prune, 24 * 60 * 60 * 1000);
1793
+ if (typeof journalRetentionTimer?.unref === 'function')
1794
+ journalRetentionTimer.unref();
1795
+ return () => clearInterval(journalRetentionTimer);
1796
+ });
1797
+ }
1736
1798
  ctx.effect(() => ctx.systemPrompt.section({
1737
1799
  name: 'dsh-workplan',
1738
1800
  order: PROMPT_ORDER,
@@ -1836,7 +1898,10 @@ export function apply(ctx, config = {}) {
1836
1898
  return;
1837
1899
  }
1838
1900
  try {
1839
- const body = readFileSync(new URL('../vendor/chart.umd.js', import.meta.url));
1901
+ if (!chartVendorBytes) {
1902
+ chartVendorBytes = readFileSync(new URL('../vendor/chart.umd.js', import.meta.url));
1903
+ }
1904
+ const body = chartVendorBytes;
1840
1905
  res.statusCode = 200;
1841
1906
  res.setHeader('content-type', 'text/javascript; charset=utf-8');
1842
1907
  res.setHeader('cache-control', 'public, max-age=3600');
@@ -1851,10 +1916,16 @@ export function apply(ctx, config = {}) {
1851
1916
  }));
1852
1917
  });
1853
1918
  ctx.effect(() => () => runtime.dispose());
1919
+ /*
1920
+ * [3.0.6][复审修复] 把 runtime 句柄交还给调用方:宿主契约不消费本返回值
1921
+ * (清理一律经上方 effect),测试与宿主编排需要观察 state.records /
1922
+ * 替换 startAutoDispatch 时可直接拿到同一实例,不必从工具闭包里挖。
1923
+ */
1924
+ return runtime;
1854
1925
  }
1855
1926
  export const meta = {
1856
1927
  name,
1857
- version: '3.0.2',
1928
+ version: '3.0.6',
1858
1929
  promptOrder: PROMPT_ORDER,
1859
1930
  routes: ['/dsh-workplan/plans', '/dsh-workplan/vendor/chart.umd.js'],
1860
1931
  };
@@ -1867,7 +1938,14 @@ export { PROMPT_SECTION, createCancelTool, createDelegateTool, createDispatchToo
1867
1938
  * 取第一个非空原因,互不覆盖。
1868
1939
  */
1869
1940
  export function fileWriteGuardReason(exec, runtime) {
1870
- if (!isWriteShapedCall(exec))
1941
+ /*
1942
+ * [复审修复] bash 写保护绕过:shell 类工具的 command 字符串(重定向/heredoc/
1943
+ * tee/sed -i/cp/mv)此前因参数形状不认(无 file_path/path)而整类绕过闸门。
1944
+ * 先解析出 shell 写目标(非 shell 调用为 null),形状闸门与 shell 闸门至少
1945
+ * 命中其一才继续。
1946
+ */
1947
+ const shellTargets = shellWriteTargets(exec);
1948
+ if (!isWriteShapedCall(exec) && shellTargets === null)
1871
1949
  return undefined;
1872
1950
  // The three historical write tools pass their arguments through untouched, so
1873
1951
  // their behaviour stays exactly as before (argument-shape matching is only an
@@ -1883,8 +1961,48 @@ export function fileWriteGuardReason(exec, runtime) {
1883
1961
  if (typeof extra === 'string')
1884
1962
  return extra;
1885
1963
  }
1964
+ /*
1965
+ * [复审修复] shell 写目标:与上面同一判定出口——只拦「写入已交付文件」,
1966
+ * 纯读命令(cat/grep/less 该路径)解析不出写目标,天然放行。
1967
+ * 启发式局限(保守模式):只认 > / >> 重定向、tee、sed -i、mv/cp/install/dd
1968
+ * 的目标;命令拼接变量(cmd=path; $cmd)、eval、find -delete 等动态写法
1969
+ * 不在解析范围内——见 shellWriteTargets 注释。
1970
+ */
1971
+ if (shellTargets) {
1972
+ for (const target of shellTargets) {
1973
+ const extra = runtime.presentedWriteDenialReason(exec?.agent, { file_path: target });
1974
+ if (typeof extra === 'string')
1975
+ return extra;
1976
+ }
1977
+ }
1886
1978
  return undefined;
1887
1979
  }
1980
+ /*
1981
+ * [复审修复] 活跃 planId 集合:pruneJournal 只看 mtime,「活跃但安静」的计划
1982
+ * (久无新留痕、mtime 变旧)会被误删;把当前活跃 planId 传给 excludePlanIds
1983
+ * 即可保住。planning 在途时尚未铸出 planId(planId 在规划完成后才生成,占位
1984
+ * 记录 planId=null),因此 runtime.state.records 就是全部活跃 planId 的事实源。
1985
+ * 导出以便直接单测;读取失败返回空集——宁可少排除,也不让清理路径抛错。
1986
+ */
1987
+ export function activePlanIdSet(runtime) {
1988
+ const ids = new Set();
1989
+ try {
1990
+ const records = runtime?.state?.records;
1991
+ if (records instanceof Map) {
1992
+ for (const record of records.values()) {
1993
+ const direct = typeof record?.planId === 'string' ? record.planId.trim() : '';
1994
+ const nested = typeof record?.plan?.planId === 'string' ? record.plan.planId.trim() : '';
1995
+ const id = direct !== '' ? direct : (nested !== '' ? nested : null);
1996
+ if (id)
1997
+ ids.add(id);
1998
+ }
1999
+ }
2000
+ }
2001
+ catch {
2002
+ // 同上:名单读取失败不阻断清理。
2003
+ }
2004
+ return ids;
2005
+ }
1888
2006
  /**
1889
2007
  * [1.12.2] G2: recognise write calls by their argument shape, not by a tool-name
1890
2008
  * allow-list. The 1.8.18 version named write/edit/str_replace_editor only, so a
@@ -1914,3 +2032,88 @@ function isWriteShapedCall(exec) {
1914
2032
  // Every other write form names a single target: file_path or path.
1915
2033
  return typeof args.file_path === 'string' || typeof args.path === 'string';
1916
2034
  }
2035
+ /*
2036
+ * [复审修复] shell 类工具的识别:exec.name 为 bash/shell/exec,或以它们为
2037
+ * 前缀且前缀后是 [-_] 分隔符或结尾(bash_exec、shell-tool 等宿主工具名变体)。
2038
+ * 要求分隔符是为了避免 'executor' 这类普通名字被误判进 shell 闸门。
2039
+ */
2040
+ function isShellLikeToolName(name) {
2041
+ if (typeof name !== 'string' || name === '')
2042
+ return false;
2043
+ if (name === 'bash' || name === 'shell' || name === 'exec')
2044
+ return true;
2045
+ return /^(?:bash|shell|exec)(?:[-_]|$)/.test(name);
2046
+ }
2047
+ /*
2048
+ * [复审修复] 从 shell 调用的 command 字符串解析「写目标路径」。
2049
+ *
2050
+ * 返回 null = 这不是 shell 类调用(或没有 command 参数),调用方据此跳过
2051
+ * shell 闸门;返回数组则可能为空(shell 调用但不含写形态,如纯读的
2052
+ * cat/grep/less)——空数组同样放行。多提取无害:每个候选最终仍走
2053
+ * presentedWriteDenialReason 的「已交付且计划未就绪」判定,普通路径直接
2054
+ * 放行;要防的是漏提取,所以解析宁可宽进。
2055
+ *
2056
+ * 保守模式只认这些强写信号:
2057
+ * - `>` / `>>` 重定向(含 heredoc:`cat <<EOF > path` 的重定向部分);
2058
+ * - `tee [-a] files...`(tee 是纯写管道,必须整组检查);
2059
+ * - `sed -i[.bak] ... files`(段内 -i 之后的全部非选项 token);
2060
+ * - `mv/cp/install 源... 目标`(只取最后一个非选项 token——源是读,只有
2061
+ * 目标是写,全取会把「复制自受保护文件」误拦成写);
2062
+ * - `dd of=path`。
2063
+ *
2064
+ * 启发式局限(有意保守,备查):
2065
+ * - 变量间接(cmd="> $f"; eval、sh -c 嵌套命令)不做展开;
2066
+ * - find -delete、perl -i、crontab 等少见写法不覆盖;
2067
+ * - 引号内带空格的路径按空白截断,不做完整 shell 词法分析;
2068
+ * - 超长命令只解析前 20k 字符。
2069
+ */
2070
+ const SHELL_COMMAND_PARSE_LIMIT = 20_000;
2071
+ function shellWriteTargets(exec) {
2072
+ if (!isShellLikeToolName(exec?.name))
2073
+ return null;
2074
+ const command = exec?.arguments?.command;
2075
+ if (typeof command !== 'string' || command.trim() === '')
2076
+ return null;
2077
+ const text = command.length > SHELL_COMMAND_PARSE_LIMIT ? command.slice(0, SHELL_COMMAND_PARSE_LIMIT) : command;
2078
+ const targets = new Set();
2079
+ const stripQuotes = (token) => token.replace(/^['"]+|['"]+$/g, '');
2080
+ const isOption = (token) => token === '-' || token.startsWith('-') || token === '--';
2081
+ const add = (token) => {
2082
+ const cleaned = stripQuotes(String(token ?? '')).trim();
2083
+ if (cleaned !== '')
2084
+ targets.add(cleaned);
2085
+ };
2086
+ // > / >> 重定向(兼容 fd 前缀 2>file、1> file;&> 合并重定向跳过——歧义大)。
2087
+ for (const match of text.matchAll(/(?<![&\d])\d*>>?\s*([^\s;|&<>]+)/g))
2088
+ add(match[1]);
2089
+ // 按命令段分隔:; | &&。单 &(2>&1 的合并目标)不拆,避免把 fd 描述切碎。
2090
+ for (const segment of text.split(/&&|[;|]/)) {
2091
+ const trimmed = segment.trim();
2092
+ if (trimmed === '')
2093
+ continue;
2094
+ // tee [-a] files...:tee 之后到段尾的全部 token 都是写目标。
2095
+ const tee = /(?:^|\s)tee(?:\s+-[a-zA-Z]+)*\s+(\S(?:[\s\S]*?))?$/.exec(trimmed);
2096
+ if (tee && /\btee\b/.test(trimmed)) {
2097
+ for (const token of (tee[1] ?? '').split(/\s+/))
2098
+ if (!isOption(token))
2099
+ add(token);
2100
+ }
2101
+ // sed -i[.bak] ...:段内含 sed 且带 -i 选项时,取其后的全部非选项 token。
2102
+ const sed = /(?:^|\s)sed(?:\s+-[a-zA-Z]+)*\s+(-i\S*)(?:\s+([\s\S]*))?$/.exec(trimmed);
2103
+ if (sed) {
2104
+ for (const token of (sed[2] ?? '').split(/\s+/))
2105
+ if (!isOption(token))
2106
+ add(token);
2107
+ }
2108
+ // mv/cp/install 源... 目标:只取最后一个非选项 token(目标是写、源是读)。
2109
+ const mover = /(?:^|\s)(?:mv|cp|install)(?:\s+-[a-zA-Z]+)*\s+([\s\S]+)$/.exec(trimmed);
2110
+ if (mover) {
2111
+ const tokens = (mover[1] ?? '').split(/\s+/).filter((token) => !isOption(token));
2112
+ add(tokens[tokens.length - 1]);
2113
+ }
2114
+ // dd of=path(of= 后到空白为止)。
2115
+ for (const match of trimmed.matchAll(/(?:^|\s)of=([^\s;|&]+)/g))
2116
+ add(match[1]);
2117
+ }
2118
+ return [...targets];
2119
+ }