dsh-workplan 1.8.4 → 1.8.18

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/host.js CHANGED
@@ -1,4 +1,7 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { readFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
2
5
  /**
3
6
  * Host half of dsh-workplan.
4
7
  *
@@ -10,6 +13,46 @@ import { readFileSync } from 'node:fs';
10
13
  */
11
14
  import { applyHardeningHeaders, cancelToolOutputSchema, createWorkplanRuntime, dispatchToolOutputSchema, plannerOutputSchema, statusToolOutputSchema, updateToolOutputSchema, } from './runtime.js';
12
15
  import { isRecord } from './plan.js';
16
+ /*
17
+ * [1.8.14] Identity of the modules this process actually loaded (N1).
18
+ *
19
+ * `version` alone cannot answer "is the running process the build I just
20
+ * shipped": the same version can be rebuilt, and a profile recomposition can
21
+ * leave stale modules in memory while the files on disk are new. Hashing the
22
+ * compiled entry files that make up the plugin at activation time gives a
23
+ * value that changes whenever the loaded bytes change. It is computed once, so
24
+ * it cannot drift during the process's life.
25
+ *
26
+ * [1.8.15] `watchdog.js` was missing from the list even though runtime.ts
27
+ * imports it and the build copies it next to the other entries. Appending a
28
+ * line to it left the fingerprint unchanged (T5c §6.1) — a build identity that
29
+ * ignores a loaded module is a false negative, exactly what it exists to catch.
30
+ */
31
+ const LOADED_BUILD = (() => {
32
+ try {
33
+ const entryPath = fileURLToPath(import.meta.url);
34
+ const dir = dirname(entryPath);
35
+ const hash = createHash('sha256');
36
+ for (const file of ['host.js', 'runtime.js', 'plan.js', 'watchdog.js']) {
37
+ hash.update(readFileSync(join(dir, file)));
38
+ }
39
+ return { entryPath, buildHash: hash.digest('hex').slice(0, 16) };
40
+ }
41
+ catch {
42
+ /*
43
+ * Never fail activation for a diagnostic. An unknown fingerprint is still a
44
+ * truthful answer ("I cannot prove which bytes I am"), and `status` will
45
+ * show `unknown` instead of a fabricated hash.
46
+ */
47
+ return { entryPath: '', buildHash: 'unknown' };
48
+ }
49
+ })();
50
+ /*
51
+ * Process start time derived from `process.uptime()`, so it is the actual OS
52
+ * process start, not the moment the plugin was constructed. Used to tell
53
+ * "restarted after the fix" from "same process, rebuilt files on disk".
54
+ */
55
+ const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
13
56
  function phaseLabel(phase) {
14
57
  if (phase === 'paused')
15
58
  return '本轮预算用尽,可续跑';
@@ -41,7 +84,24 @@ const PROMPT_SECTION = [
41
84
  '2. 核对每个完成子任务的证据与验收标准,不合格的要用 dsh_workplan_update 标记为 blocked 或 in_progress;',
42
85
  '3. 对受阻项向用户说明,必要时先询问再继续;',
43
86
  '4. 不要声称未经验证的完成,不要重复派发已完成的子任务。',
44
- '结果消息里每个完成项都带 verification 与 acceptance:`structured` 是子 Agent 逐条自检通过,`unverified` 是自述但未逐条确认,`failed` 是自检失败(已按受阻处理),`legacy` 是旧格式回传。只把 structured 当作可直接采信,其余必须你自己核对产物。',
87
+ /*
88
+ * [1.8.7] 硬规则:ok:true 不等于完成。
89
+ *
90
+ * 事故(session-99984ebd…)里模型把「本轮预算用尽,可续跑(10/13)」当成
91
+ * 成功,直接 present 并收尾。提示词必须把「complete 字段才是完成」写到
92
+ * 不可误解,并且与 runtime 的回合收尾闸门(agent/turn-stopping)形成双保险。
93
+ */
94
+ /*
95
+ * [1.8.13] 用户明确取消不是完成。
96
+ *
97
+ * 1.8.7 的原文是「全部 done(或用户明确取消)」,T5-C 就是拿这句话把
98
+ * “取消 1/3 再 present”走通的:提示词把它写成完成等价物,present 的
99
+ * planIncomplete 又对 cancelled 短路。现在完成只有一个判据:全部 done
100
+ * 且 deliveryReady=true。
101
+ */
102
+ '5. 「完成」只有一个判据:计划里全部子任务都是 done,**且** deliveryReady=true(每个 done 项 verification="structured"、acceptance 非空且逐项 result="pass"、无缺失产物)。用户取消 ≠ 完成:取消只停止执行,未完成项仍然是未完成。`dsh_workplan_dispatch` 返回 ok:true / complete:true 只表示调用成功或状态全 done,必须再看 deliveryReady 与 完成 X/Y;只要 deliveryReady=false 或还有 pending/blocked,就禁止 present 交付物、禁止写“已完成/最终版/已交付”、禁止给收尾性最终答复,必须先再次调用 dsh_workplan_dispatch 续跑剩余项。',
103
+ '6. 如果续跑被拒绝、受阻项无法恢复、证据补不齐、计划已取消但未完成,或用户要求先看中间结果:答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」,正文只能按中间结果表述,不得包装成成品。取消不会给你交付许可。',
104
+ '结果消息里每个完成项都带 verification 与 acceptance:`structured` 是子 Agent 逐条自检通过,`unverified` 是自述但未逐条确认,`failed` 是自检失败(已按受阻处理),`legacy` 是旧格式回传。只有 structured 且 acceptance 每项 pass 才算可交付;其余必须你自己核对产物,并用 dsh_workplan_update 的 verification/acceptance/artifacts 字段把核对结果写回(这些字段会持久化、刷新后仍生效),不要把“看着没问题”当成证据。',
45
105
  '子 Agent 通过 `needs` 提出的跨部门需求会列在结果消息的「跨部门待转达」里:由你逐条处理(补派、向用户确认或直接完成),不要忽略。',
46
106
  '长任务可以用 `dsh_workplan_dispatch({ mode: "async" })` 先开跑并立即答复用户,再用 `dsh_workplan_status` 查看进度;async 返回的是“已开跑”,不是“已完成”。',
47
107
  '如果自动分解降级,先向用户说明失败原因并询问是否重试,在用户确认前不要开始执行任务。',
@@ -81,7 +141,10 @@ function createUpdateTool(runtime) {
81
141
  return {
82
142
  name: 'dsh_workplan_update',
83
143
  description: '更新当前任务分解计划中一个子任务的状态与证据。仅用于本会话已生成的主计划;子 Agent 不可调用。'
84
- + '当主 Agent 核对子任务结果、发现完成不实或需要修正时使用。',
144
+ + '当主 Agent 核对子任务结果、发现完成不实或需要修正时使用。'
145
+ + '把子任务标成 done 时,必须同时给出真实的 verification 与 acceptance(每项 result="pass"),'
146
+ + '否则计划不会变成可交付状态(deliveryReady=false,present 会被拒绝)。'
147
+ + '这些字段会写入会话日志,刷新/重启后仍然生效。',
85
148
  parameters: {
86
149
  type: 'object',
87
150
  properties: {
@@ -105,7 +168,47 @@ function createUpdateTool(runtime) {
105
168
  evidence: {
106
169
  type: 'array',
107
170
  items: { type: 'string' },
108
- description: '支持该状态的证据(文件、命令输出、验收结果)。',
171
+ description: '支持该状态的证据(文件、命令输出、验收结果)。只用于说明,不参与可交付判定。',
172
+ },
173
+ verification: {
174
+ type: 'string',
175
+ enum: ['structured', 'legacy', 'unverified', 'failed'],
176
+ description: '证据等级:structured=逐条自检通过;unverified=自述未逐条确认;'
177
+ + 'legacy=旧格式回传(没有结构化证据);failed=自检失败。'
178
+ + '可交付要求 structured。',
179
+ },
180
+ acceptance: {
181
+ type: 'array',
182
+ description: '验收项及逐项结果;可交付要求非空且每项 result="pass"。',
183
+ items: {
184
+ type: 'object',
185
+ properties: {
186
+ criterion: { type: 'string', description: '验收标准。' },
187
+ result: { type: 'string', enum: ['pass', 'fail', 'unverified'], description: '该项结果。' },
188
+ evidence: { type: 'string', description: '支持该结果的证据(文件、命令输出、测试结果)。' },
189
+ },
190
+ required: ['criterion', 'result'],
191
+ additionalProperties: false,
192
+ },
193
+ },
194
+ artifacts: {
195
+ type: 'array',
196
+ description: '声明产物;kind=file/url/note,exists=false 表示产物缺失。',
197
+ items: {
198
+ type: 'object',
199
+ properties: {
200
+ kind: { type: 'string', enum: ['file', 'url', 'note'] },
201
+ ref: { type: 'string' },
202
+ exists: { type: 'boolean' },
203
+ },
204
+ required: ['kind', 'ref'],
205
+ additionalProperties: false,
206
+ },
207
+ },
208
+ missingArtifacts: {
209
+ type: 'array',
210
+ items: { type: 'string' },
211
+ description: '已知缺失的产物路径;非空时计划不可交付。',
109
212
  },
110
213
  expectedRevision: {
111
214
  type: 'integer',
@@ -148,7 +251,9 @@ function createCancelTool(runtime) {
148
251
  return {
149
252
  name: 'dsh_workplan_cancel',
150
253
  description: '取消当前会话尚未派发/正在等待派发的任务分解计划。仅取消计划记录,不伪造任何完成;'
151
- + '取消后计划在面板中显示为“已取消”,不会启动任何部门 Agent。',
254
+ + '取消后计划在面板中显示为“已取消”,不会启动任何部门 Agent。'
255
+ + '注意:取消不等于完成。取消后如仍有未完成项或证据缺口,present 仍会被拒绝,'
256
+ + '答复必须按「未完成:剩余 N 项与原因」说明。',
152
257
  parameters: {
153
258
  type: 'object',
154
259
  properties: {
@@ -167,9 +272,15 @@ function createCancelTool(runtime) {
167
272
  schema: cancelToolOutputSchema(),
168
273
  render(_args, value) {
169
274
  const result = isRecord(value) ? value : {};
170
- return textContent(result.ok
171
- ? `已取消计划 ${String(result.planId ?? '')}:${String(result.reason ?? '用户取消')}`
172
- : `取消失败:${String(result.error ?? '未知错误')}`);
275
+ if (!result.ok)
276
+ return textContent(`取消失败:${String(result.error ?? '未知错误')}`);
277
+ const stats = isRecord(result.stats) ? result.stats : {};
278
+ const cancelledIncomplete = result.phase !== 'done';
279
+ return textContent(`已取消计划 ${String(result.planId ?? '')}:${String(result.reason ?? '用户取消')}`
280
+ + `(完成 ${Number(stats.done ?? 0)}/${Number(stats.total ?? 0)})`
281
+ + (cancelledIncomplete
282
+ ? '|计划仍未完成:不要 present,不要写“已完成”;答复按「未完成:剩余 N 项与原因」开头。'
283
+ : '|计划此前已全部 done。'));
173
284
  },
174
285
  },
175
286
  async execute(args, exec) {
@@ -200,15 +311,35 @@ function createStatusTool(runtime) {
200
311
  render(_args, value) {
201
312
  const result = isRecord(value) ? value : {};
202
313
  const stats = isRecord(result.stats) ? result.stats : {};
203
- if (!result.ok)
204
- return textContent(`查询失败:${String(result.error ?? '未知错误')}`);
314
+ const runtimeInfo = isRecord(result.runtime) ? result.runtime : {};
315
+ /*
316
+ * [1.8.14] Every answer names the loaded build, including the failure
317
+ * path. The restart verification in the incident report (§14.6 step 2)
318
+ * called `status` before any plan existed and got bare `NO_PLAN`, so it
319
+ * could not confirm which build was answering.
320
+ */
321
+ const startedAt = Number(runtimeInfo.startedAt) || 0;
322
+ const identity = [
323
+ typeof result.version === 'string' ? `v${result.version}` : '',
324
+ typeof runtimeInfo.buildHash === 'string' ? `build ${runtimeInfo.buildHash}` : '',
325
+ Number(runtimeInfo.pid) > 0 ? `pid ${Number(runtimeInfo.pid)}` : '',
326
+ startedAt > 0
327
+ ? `启动 ${new Date(startedAt).toLocaleString('zh-CN', { hour12: false })}`
328
+ : '',
329
+ ].filter(Boolean).join('|');
330
+ if (!result.ok) {
331
+ return textContent(`查询失败:${String(result.error ?? '未知错误')}`
332
+ + (identity ? `(${identity})` : ''));
333
+ }
205
334
  const running = result.running === true;
206
335
  return textContent(`计划 ${String(result.planId ?? '')}|${running ? '执行中' : '未在执行'}`
207
336
  + `|阶段:${phaseLabel(result.phase)}`
208
337
  + `|完成 ${Number(stats.done ?? 0)}/${Number(stats.total ?? 0)},受阻 ${Number(stats.blocked ?? 0)}`
338
+ + `|${result.deliveryReady === true ? '可交付' : '未就绪'}`
209
339
  + (running && Number(result.elapsedMs ?? 0) > 0
210
340
  ? `|已 ${Math.round(Number(result.elapsedMs) / 1000)}s`
211
- : ''));
341
+ : '')
342
+ + (identity ? `|${identity}` : ''));
212
343
  },
213
344
  },
214
345
  async execute(args, exec) {
@@ -220,8 +351,10 @@ function createStatusTool(runtime) {
220
351
  function createDispatchTool(runtime) {
221
352
  return {
222
353
  name: 'dsh_workplan_dispatch',
223
- description: '派发当前会话尚未执行的任务分解计划。计划显示后必须先调用本工具;它会等待各部门 Agent 完成,'
224
- + '把 durable 结果写入会话并返回每个子任务的状态/摘要。重复调用是幂等的。',
354
+ description: '派发当前会话尚未执行的任务分解计划。计划显示后必须先调用本工具;wait 会等到本轮结束,'
355
+ + '把 durable 结果写入会话并返回每个子任务的状态/摘要。'
356
+ + '返回值里的 complete=false 表示计划还没做完(可能只是本轮预算用尽),此时必须再次派发续跑,'
357
+ + '不得把当前产物当作最终结果。重复调用是幂等的。',
225
358
  parameters: {
226
359
  type: 'object',
227
360
  properties: {
@@ -243,17 +376,53 @@ function createDispatchTool(runtime) {
243
376
  render(_args, value) {
244
377
  const result = isRecord(value) ? value : {};
245
378
  const stats = isRecord(result.stats) ? result.stats : {};
246
- return textContent(result.ok
247
- ? `计划 ${String(result.planId ?? '')} 当前阶段:${phaseLabel(result.phase)}`
248
- + `(完成 ${Number(stats.done ?? 0)}/${Number(stats.total ?? 0)},受阻 ${Number(stats.blocked ?? 0)})`
249
- + (result.alreadyRunning || result.mode === 'async'
250
- ? `|已在执行(${Math.round(elapsedSeconds(result) / 1000)}s)`
251
- : '')
252
- + (result.joined ? '|已加入进行中的派发并等到结果' : '')
379
+ const done = Number(stats.done ?? 0);
380
+ const total = Number(stats.total ?? 0);
381
+ const blocked = Number(stats.blocked ?? 0);
382
+ const remaining = Math.max(0, total - done);
383
+ const name = `计划 ${String(result.planId ?? '')}`;
384
+ if (!result.ok) {
253
385
  // The hint carries the recovery instruction (resume, or take the work
254
386
  // over directly); showing it in the rendered line keeps it visible
255
387
  // even when only the summary is read.
256
- : `派发失败:${String(result.error ?? '未知错误')}${result.hint ? `|下一步:${String(result.hint)}` : ''}`);
388
+ return textContent(`派发失败:${String(result.error ?? '未知错误')}${result.hint ? `|下一步:${String(result.hint)}` : ''}`);
389
+ }
390
+ /*
391
+ * [1.8.7] The first word decides how the model reads the round.
392
+ *
393
+ * Incident: `ok:true` + "已加入进行中的派发并等到结果(完成 10/13)"
394
+ * read as "done", so the model presented a half-finished report. Now an
395
+ * unfinished round starts with 未完成 and states the only legal next
396
+ * move; a finished one is the only place the word 已完成 appears.
397
+ */
398
+ if (result.mode === 'async' || (result.running === true && result.joined !== true)) {
399
+ return textContent(`${name} 已开跑,尚未完成:当前完成 ${done}/${total},剩余 ${remaining} 项由本轮执行`
400
+ + `(${Math.round(elapsedSeconds(result) / 1000)}s)`
401
+ + '|不要重复派发;结果消息会在本轮结束时自动写入。在结果消息到达并确认 complete=true 之前,不要给最终答复。');
402
+ }
403
+ /*
404
+ * [1.8.13] All rows done is not the finish line.
405
+ *
406
+ * T5-B/D: every row said done, no structured evidence, and this branch
407
+ * printed 已完成 — the model then presented. Only deliveryReady=true
408
+ * reaches the completion sentence; every other state names the gaps and
409
+ * the legal next move (dispatch, fix evidence, or report unfinished).
410
+ */
411
+ if (result.deliveryReady === true) {
412
+ return textContent(`${name} 已完成且可交付:完成 ${done}/${total},证据通过`
413
+ + (result.joined ? '|已加入进行中的派发并等到结果' : ''));
414
+ }
415
+ const blockers = Array.isArray(result.deliveryBlockers) ? result.deliveryBlockers.slice(0, 6).join(';') : '';
416
+ const cancelled = result.phase === 'cancelled';
417
+ const next = cancelled
418
+ ? '计划已取消且未完成:不要再次 dispatch,不要 present;答复按「未完成:剩余 N 项与原因」开头。'
419
+ : remaining > 0
420
+ ? '下一步:再次调用 dsh_workplan_dispatch 续跑剩余项;全部 done 之前不要 present。'
421
+ : "全部子任务虽已 done,但证据未通过:用 dsh_workplan_update 补 verification='structured' 与 acceptance(每项 result='pass'),或把对应项改回 blocked;不要 present。";
422
+ return textContent(`${name} 未就绪:完成 ${done}/${total},剩余 ${remaining} 项,受阻 ${blocked}(${phaseLabel(result.phase)})`
423
+ + (blockers ? `|证据缺口:${blockers}` : '')
424
+ + (result.joined ? '|本轮已返回,但计划没有达到可交付状态' : '')
425
+ + `|${next}|不要写“已完成/最终版/已交付”,不要给收尾性最终答复。`);
257
426
  },
258
427
  },
259
428
  /*
@@ -287,8 +456,37 @@ function numericSetting(configValue, envName) {
287
456
  const numeric = Number(raw);
288
457
  return Number.isFinite(numeric) && numeric > 0 ? numeric : undefined;
289
458
  }
459
+ /**
460
+ * Hard, tool-level guards. Kept as a pure function so the contracts can be
461
+ * pinned without mounting the whole plugin:
462
+ * - plan mode:只拦住 dispatch,其他工具保持可用(避免死锁);
463
+ * - `present`:计划未完成时由 runtime 拒绝(事故中模型在收尾闸门之前
464
+ * present,卡片一旦出现就无法撤回)。
465
+ */
466
+ export function toolGuardReason(exec, runtime) {
467
+ if (exec?.name === 'dsh_workplan_dispatch') {
468
+ const session = exec?.agent?.session;
469
+ if (session && runtime.planModeActive(session)) {
470
+ return '当前是 plan 模式:计划已生成,请先让用户审阅/退出 plan 模式,再调用 dsh_workplan_dispatch。';
471
+ }
472
+ return undefined;
473
+ }
474
+ if (exec?.name === 'present')
475
+ return runtime.presentDenialReason(exec?.agent);
476
+ return undefined;
477
+ }
290
478
  export function apply(ctx, config = {}) {
291
479
  const runtime = createWorkplanRuntime(ctx, {
480
+ // [1.8.13] The answering version must be visible in status/dispatch output,
481
+ // not inferred from the PID.
482
+ version: meta.version,
483
+ // [1.8.14] ...and so must the exact loaded build (see LOADED_BUILD above).
484
+ build: {
485
+ pid: process.pid,
486
+ startedAt: PROCESS_STARTED_AT,
487
+ entryPath: LOADED_BUILD.entryPath,
488
+ buildHash: LOADED_BUILD.buildHash,
489
+ },
292
490
  cwd: typeof config.cwd === 'string' ? config.cwd : undefined,
293
491
  childTimeoutMs: numericSetting(config.childTimeoutMs, 'DSH_WORKPLAN_CHILD_TIMEOUT_MS'),
294
492
  idleTimeoutMs: numericSetting(config.idleTimeoutMs, 'DSH_WORKPLAN_IDLE_TIMEOUT_MS'),
@@ -308,17 +506,21 @@ export function apply(ctx, config = {}) {
308
506
  * Plan mode produces a plan for review, not department execution. Denying
309
507
  * only the dispatch tool keeps every other tool available (no deadlock)
310
508
  * and gives the model a precise reason instead of a silent no-op.
509
+ *
510
+ * [1.8.8] `present` 也在执行前拦截:事故里模型在回合中途就把未完成
511
+ * 的产物 present 出去,回合收尾闸门再拦已经撤不回卡片。计划未完成时
512
+ * 拒绝交付,模型必须先续跑或显式取消计划。
311
513
  */
312
- ctx.effect(() => ctx.tools.guard((exec) => {
313
- if (exec?.name !== 'dsh_workplan_dispatch')
314
- return undefined;
315
- const session = exec?.agent?.session;
316
- if (session && runtime.planModeActive(session)) {
317
- return '当前是 plan 模式:计划已生成,请先让用户审阅/退出 plan 模式,再调用 dsh_workplan_dispatch。';
318
- }
319
- return undefined;
320
- }));
514
+ ctx.effect(() => ctx.tools.guard((exec) => toolGuardReason(exec, runtime)));
321
515
  ctx.effect(() => ctx.on('agent/pre-step', runtime.onPreStep));
516
+ /*
517
+ * [1.8.7] 回合收尾前的闸门。官方 `agent/turn-stopping` 是 serial 事件、
518
+ * 在边界提交前被 await;监听器 `agent.steer()` 后机器会重读 inbox,于是
519
+ * 「计划没做完」时回合不会被关闭。这是「未完成即输出」的唯一强制点:
520
+ * 提示词和工具文案只能说服模型,这个事件能拦住收尾本身。
521
+ */
522
+ ctx.effect(() => ctx.on('agent/turn-stopping', runtime.onTurnStopping));
523
+ ctx.effect(() => ctx.tools.guard((exec) => fileWriteGuardReason(exec, runtime)));
322
524
  ctx.inject(['webServer', 'connection'], (scope) => {
323
525
  scope.effect(() => scope.webServer.register({
324
526
  kind: 'exact',
@@ -371,8 +573,20 @@ export function apply(ctx, config = {}) {
371
573
  }
372
574
  export const meta = {
373
575
  name,
374
- version: '1.8.4',
576
+ version: '1.8.18',
375
577
  promptOrder: PROMPT_ORDER,
376
578
  routes: ['/dsh-workplan/plans', '/dsh-workplan/vendor/chart.umd.js'],
377
579
  };
378
580
  export { PROMPT_SECTION, createCancelTool, createDispatchTool, createStatusTool, createUpdateTool, plannerOutputSchema };
581
+ /**
582
+ * [1.8.18] 写工具的路径级闸门(T7-N2),与 `toolGuardReason` 分开注册。
583
+ *
584
+ * present/dispatch 的语义是「计划未就绪不能交付」;这里管的是「已交付的
585
+ * 文件不能在计划未就绪时被原地改写」。两条守卫都返回拒绝原因,harness
586
+ * 取第一个非空原因,互不覆盖。
587
+ */
588
+ export function fileWriteGuardReason(exec, runtime) {
589
+ if (exec?.name !== 'write' && exec?.name !== 'edit' && exec?.name !== 'str_replace_editor')
590
+ return undefined;
591
+ return runtime.presentedWriteDenialReason(exec?.agent, exec?.arguments);
592
+ }