@oyasmi/pipiclaw 0.8.10-beta.2 → 0.8.10-beta.4

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.
Files changed (60) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +54 -15
  3. package/dist/agent/commands.js +30 -28
  4. package/dist/agent/effect-ledger.d.ts +25 -4
  5. package/dist/agent/effect-ledger.js +45 -5
  6. package/dist/agent/job-manager.d.ts +20 -0
  7. package/dist/agent/job-manager.js +66 -10
  8. package/dist/agent/maintenance-context.js +3 -2
  9. package/dist/agent/progress-formatter.d.ts +10 -1
  10. package/dist/agent/progress-formatter.js +14 -2
  11. package/dist/agent/prompt/manifest.d.ts +32 -1
  12. package/dist/agent/prompt/manifest.js +41 -2
  13. package/dist/executor.d.ts +2 -0
  14. package/dist/executor.js +1 -0
  15. package/dist/memory/maintenance-gates.d.ts +24 -10
  16. package/dist/memory/maintenance-gates.js +11 -9
  17. package/dist/memory/maintenance-jobs.d.ts +3 -2
  18. package/dist/memory/maintenance-jobs.js +33 -21
  19. package/dist/memory/scheduler.d.ts +7 -2
  20. package/dist/playbooks/task-closeout.md +2 -0
  21. package/dist/playbooks/task-delegation.md +14 -8
  22. package/dist/playbooks/task-driving.md +8 -5
  23. package/dist/playbooks/task-planning.md +2 -2
  24. package/dist/runtime/bootstrap.js +35 -9
  25. package/dist/runtime/delivery.d.ts +12 -2
  26. package/dist/runtime/delivery.js +55 -13
  27. package/dist/runtime/dingtalk.d.ts +9 -1
  28. package/dist/runtime/dingtalk.js +7 -4
  29. package/dist/runtime/task-commands.js +170 -54
  30. package/dist/runtime/task-driver.d.ts +3 -3
  31. package/dist/runtime/task-driver.js +42 -12
  32. package/dist/settings.d.ts +10 -0
  33. package/dist/settings.js +14 -0
  34. package/dist/shared/file-stamp.d.ts +10 -0
  35. package/dist/shared/file-stamp.js +19 -0
  36. package/dist/shared/task-ledger.d.ts +12 -1
  37. package/dist/shared/task-ledger.js +34 -3
  38. package/dist/subagents/tool.d.ts +1 -0
  39. package/dist/subagents/tool.js +33 -3
  40. package/dist/tasks/control.d.ts +1 -0
  41. package/dist/tasks/control.js +2 -2
  42. package/dist/tasks/transitions.d.ts +2 -1
  43. package/dist/tasks/transitions.js +2 -1
  44. package/dist/tasks/verification.d.ts +8 -0
  45. package/dist/tasks/verification.js +4 -1
  46. package/dist/tools/bash.js +12 -12
  47. package/dist/tools/task-manage/lifecycle.js +9 -6
  48. package/dist/tools/task-manage/schema.d.ts +1 -3
  49. package/dist/tools/task-manage/schema.js +6 -5
  50. package/dist/tools/task-manage/shared.d.ts +8 -0
  51. package/dist/tools/task-manage/shared.js +17 -1
  52. package/dist/tools/task-manage/types.d.ts +20 -21
  53. package/dist/tools/task-manage/verification.d.ts +2 -1
  54. package/dist/tools/task-manage/verification.js +2 -1
  55. package/dist/tools/task-manage.js +4 -20
  56. package/dist/tui/turn-controller.js +3 -3
  57. package/dist/usage/ledger.d.ts +2 -0
  58. package/dist/usage/ledger.js +7 -2
  59. package/dist/usage/render.js +17 -8
  60. package/package.json +1 -1
@@ -1,79 +1,100 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
+ import { channelJobTaskIds } from "../agent/job-manager.js";
4
5
  import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
5
- import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
+ import { extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
7
  import { errorMessage } from "../shared/text-utils.js";
7
8
  import { isRecord } from "../shared/type-guards.js";
8
- import { retiredTaskControlKeys, taskBudgetViolation } from "../tasks/control.js";
9
+ import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys, TASK_PRIORITIES, taskBudgetViolation, } from "../tasks/control.js";
9
10
  import { claimTaskAttempt, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
10
11
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
11
12
  import { readVerificationAttestation } from "../tasks/verification.js";
12
13
  import { parseScheduledEventContent } from "./events.js";
14
+ /**
15
+ * Fields `/tasks set` can edit directly.
16
+ *
17
+ * Deliberately a small, flat set: the ones a user already knows they want to change (when it
18
+ * should wake, what it should do next, how much rope it has). Everything structural — status
19
+ * transitions, verification, approval, side effects — stays with `task_manage`, whose state
20
+ * machine those fields belong to. The value is the rest of the line, so it may contain spaces.
21
+ */
22
+ const SETTABLE_TASK_FIELDS = ["wake", "next", "priority", "attempts", "deadline"];
13
23
  function usage() {
14
- return `# Tasks
24
+ return `# 任务
15
25
 
16
- Usage:
26
+ 用法:
17
27
 
18
- - \`/tasks\` — list active tasks in this channel
19
- - \`/tasks show <id>\` — show a single task file (active or archived)
20
- - \`/tasks archive\` — list archived (closed) tasks
21
- - \`/tasks approve <id>\` — explicitly approve this task's external side effects
22
- - \`/tasks pause <id>\` — stop automatic wake-ups for a task
23
- - \`/tasks resume <id>\` — make a paused task eligible for the next driver scan
24
- - \`/tasks run <id>\` — resume and immediately enqueue one task attempt when the runtime is available
25
- - \`/tasks stats [id]\` — show task-level attempt, token, cost, and verification outcomes
26
- - \`/tasks doctor\` — check task/event consistency without changing files`;
28
+ - \`/tasks\` — 列出本频道进行中的任务
29
+ - \`/tasks show <id>\` — 查看单个任务文件(进行中或已归档)
30
+ - \`/tasks archive\` — 列出已归档(已关闭)的任务
31
+ - \`/tasks approve <id>\` — 显式批准该任务的外部副作用
32
+ - \`/tasks pause <id>\` — 停止该任务的自动唤醒
33
+ - \`/tasks resume <id>\` — 让暂停的任务在下一轮扫描中恢复
34
+ - \`/tasks run <id>\` — 恢复并立即排入一次执行(需要运行时可用)
35
+ - \`/tasks set <id> <${SETTABLE_TASK_FIELDS.join("|")}> <值>\` — 直接改一个字段,不花一个 LLM 回合
36
+ - \`/tasks stats [id]\` — 查看任务级的尝试次数、token、花费与验收结果
37
+ - \`/tasks doctor\` — 只读检查任务/事件一致性`;
27
38
  }
28
39
  function parseTasksCommand(args) {
29
- const parts = args.trim().split(/\s+/).filter(Boolean);
40
+ const trimmed = args.trim();
41
+ const parts = trimmed.split(/\s+/).filter(Boolean);
30
42
  const action = parts[0];
31
43
  if (!action || action === "list") {
32
44
  if (parts.length > 1)
33
- throw new Error("Usage: /tasks list");
45
+ throw new Error("用法:/tasks list");
34
46
  return { action: "list" };
35
47
  }
36
48
  if (action === "show") {
37
49
  const id = parts[1];
38
50
  if (!id || parts.length > 2)
39
- throw new Error("Usage: /tasks show <id>");
51
+ throw new Error("用法:/tasks show <id>");
40
52
  return { action: "show", id };
41
53
  }
42
54
  if (action === "archive") {
43
55
  if (parts.length > 1)
44
- throw new Error("Usage: /tasks archive");
56
+ throw new Error("用法:/tasks archive");
45
57
  return { action: "archive" };
46
58
  }
47
59
  if (action === "doctor") {
48
60
  if (parts.length > 1)
49
- throw new Error("Usage: /tasks doctor");
61
+ throw new Error("用法:/tasks doctor");
50
62
  return { action: "doctor" };
51
63
  }
52
64
  if (action === "approve") {
53
65
  const id = parts[1];
54
66
  if (!id || parts.length > 2)
55
- throw new Error("Usage: /tasks approve <id>");
67
+ throw new Error("用法:/tasks approve <id>");
56
68
  return { action: "approve", id };
57
69
  }
58
70
  if (action === "pause" || action === "resume") {
59
71
  const id = parts[1];
60
72
  if (!id || parts.length > 2)
61
- throw new Error(`Usage: /tasks ${action} <id>`);
73
+ throw new Error(`用法:/tasks ${action} <id>`);
62
74
  return { action, id };
63
75
  }
64
76
  if (action === "run") {
65
77
  const id = parts[1];
66
78
  if (!id || parts.length > 2)
67
- throw new Error("Usage: /tasks run <id>");
79
+ throw new Error("用法:/tasks run <id>");
68
80
  return { action: "run", id };
69
81
  }
82
+ if (action === "set") {
83
+ // Everything after the field name is the value, verbatim — a nextAction is a sentence.
84
+ const match = /^set\s+(\S+)\s+(\S+)\s*([\s\S]*)$/.exec(trimmed);
85
+ const field = match?.[2];
86
+ if (!match || !field || !SETTABLE_TASK_FIELDS.includes(field)) {
87
+ throw new Error(`用法:/tasks set <id> <${SETTABLE_TASK_FIELDS.join("|")}> <值>`);
88
+ }
89
+ return { action: "set", id: match[1], field: field, value: match[3].trim() };
90
+ }
70
91
  if (action === "stats") {
71
92
  const id = parts[1];
72
93
  if (parts.length > 2)
73
- throw new Error("Usage: /tasks stats [id]");
94
+ throw new Error("用法:/tasks stats [id]");
74
95
  return { action: "stats", id };
75
96
  }
76
- throw new Error(`Unknown /tasks action: ${action}`);
97
+ throw new Error(`未知的 /tasks 动作:${action}`);
77
98
  }
78
99
  function tasksDir(channelDir) {
79
100
  return join(channelDir, "tasks");
@@ -178,7 +199,7 @@ async function listTasks(channelDir) {
178
199
  const now = Date.now();
179
200
  const entries = await readActiveTasks(dir, now);
180
201
  if (entries.length === 0) {
181
- return "# Tasks\n\nNo active tasks.";
202
+ return "# 任务\n\n当前没有进行中的任务。";
182
203
  }
183
204
  const blocks = entries.map((entry) => {
184
205
  const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "⚠ unreadable frontmatter";
@@ -207,40 +228,40 @@ async function listTasks(channelDir) {
207
228
  }
208
229
  return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
209
230
  });
210
- return `# Tasks: ${entries.length} active\n\n${blocks.join("\n")}`;
231
+ return `# 任务:${entries.length} 个进行中\n\n${blocks.join("\n")}`;
211
232
  }
212
233
  async function approveTask(options, idInput) {
213
234
  const id = normalizeTaskId(idInput);
214
235
  const task = await readStoredTask(options.channelDir, id);
215
236
  if (!task)
216
- return `Task not found: ${id}`;
237
+ return `找不到任务:${id}`;
217
238
  const control = task.fields.control;
218
239
  if (!control)
219
- return `Task ${id} has no governed control metadata. Ask the agent to normalize it before approval.`;
240
+ return `任务 ${id} 没有受治理的 control 元数据,先让 agent 规范化后再审批。`;
220
241
  if (task.fields.status === "done" || task.fields.status === "cancelled") {
221
- return `Task ${id} is ${task.fields.status} and cannot receive a new external-action approval.`;
242
+ return `任务 ${id} 已是 ${task.fields.status},不能再授予外部动作审批。`;
222
243
  }
223
244
  if (control.sideEffects !== "external") {
224
- return `Task ${id} is not marked for external side effects; no approval is required.`;
245
+ return `任务 ${id} 未标记为外部副作用,无需审批。`;
225
246
  }
226
247
  if (control.externalApproval === "granted") {
227
- return `Task ${id} was already approved by ${control.approvalBy ?? "a user"} at ${control.approvedAt ?? "an unknown time"}.`;
248
+ return `任务 ${id} 已由 ${control.approvalBy ?? "某位用户"} 于 ${control.approvedAt ?? "未知时间"} 批准过。`;
228
249
  }
229
250
  control.externalApproval = "granted";
230
251
  control.approvalBy = options.approver?.trim() || "unknown-user";
231
252
  control.approvedAt = new Date().toISOString();
232
253
  control.approvalBodyHash = taskBodyHash(task.body);
233
254
  await writeStoredTask(task);
234
- return `Approved external side effects for task ${id}. Approval is recorded for ${control.approvalBy}.`;
255
+ return `已批准任务 ${id} 的外部副作用,审批人记为 ${control.approvalBy}。`;
235
256
  }
236
257
  export async function pauseTask(options, idInput) {
237
258
  const id = normalizeTaskId(idInput);
238
259
  const task = await readStoredTask(options.channelDir, id);
239
260
  if (!task)
240
- return `Task not found: ${id}`;
261
+ return `找不到任务:${id}`;
241
262
  const from = normalizeStoredStatus(task.fields.status);
242
263
  if (from === "paused")
243
- return `Task ${id} is already paused.`;
264
+ return `任务 ${id} 已经是暂停状态。`;
244
265
  try {
245
266
  resolveTaskTransition("pause", id, from);
246
267
  }
@@ -254,16 +275,42 @@ export async function pauseTask(options, idInput) {
254
275
  task.fields.control.blockedReason = `Paused by ${options.approver?.trim() || "a user"}.`;
255
276
  }
256
277
  await writeStoredTask(task);
257
- return `Paused task ${id}. Use /tasks resume ${id} when it should continue.`;
278
+ return `已暂停任务 ${id}。需要继续时用 /tasks resume ${id}。`;
279
+ }
280
+ /**
281
+ * Why restarting this task would immediately stop it again, or `undefined` when it is free to run.
282
+ *
283
+ * The governor pauses on the same condition it re-checks on the next scan, so a plain resume of a
284
+ * budget/deadline-exhausted task looked like it worked, cost one escalation turn, and landed back
285
+ * in `paused` minutes later — while three separate places (the `/stop` receipt, `/tasks` usage,
286
+ * the driving playbook) told the user resume was the fix. Refuse instead, and name the command
287
+ * that actually unblocks it.
288
+ */
289
+ function restartBlockedMessage(id, control) {
290
+ if (!control)
291
+ return undefined;
292
+ const violation = taskBudgetViolation(control, Date.now());
293
+ if (!violation)
294
+ return undefined;
295
+ return [
296
+ `任务 ${id} 仍然超出治理限额:${violation}。`,
297
+ "直接恢复只会在下一轮扫描中被治理器再次暂停,并白白多花一个回合。",
298
+ `先放宽限额:\`/tasks set ${id} attempts <n>\`(当前上限 ${control.budget.maxAttempts})` +
299
+ `${control.deadline ? `,或 \`/tasks set ${id} deadline <ISO8601>\`(当前 ${control.deadline})` : ""},然后再试一次。`,
300
+ "若这个任务已经不该继续,用 `task_manage cancel` 关掉它。",
301
+ ].join("\n");
258
302
  }
259
303
  export async function resumeTask(options, idInput) {
260
304
  const id = normalizeTaskId(idInput);
261
305
  const task = await readStoredTask(options.channelDir, id);
262
306
  if (!task)
263
- return `Task not found: ${id}`;
307
+ return `找不到任务:${id}`;
264
308
  const from = normalizeStoredStatus(task.fields.status);
265
309
  if (from !== "paused")
266
- return `Task ${id} is ${from}, not paused.`;
310
+ return `任务 ${id} 当前是 ${from},并非暂停状态。`;
311
+ const blocked = restartBlockedMessage(id, task.fields.control);
312
+ if (blocked)
313
+ return blocked;
267
314
  resolveTaskTransition("resume", id, from);
268
315
  task.fields.status = "active";
269
316
  task.fields.wake = undefined;
@@ -272,13 +319,68 @@ export async function resumeTask(options, idInput) {
272
319
  task.fields.control.blockedReason = undefined;
273
320
  }
274
321
  await writeStoredTask(task);
275
- return `Resumed task ${id}; the task driver will pick it up on its next scan.`;
322
+ return `已恢复任务 ${id},任务驱动器下一轮扫描会接上。`;
323
+ }
324
+ /**
325
+ * Edit one task field directly.
326
+ *
327
+ * The alternative — telling the model "change wake to tomorrow 9am" — costs a whole turn and its
328
+ * tokens to reach the same one-line write. Validation is not re-implemented here: `wake` reuses
329
+ * the ledger's ISO8601 rule and everything else goes through `applyTaskControlPatch`, the same
330
+ * function `task_manage set` uses, so the two entry points cannot drift apart.
331
+ */
332
+ async function setTaskField(options, idInput, field, value) {
333
+ const id = normalizeTaskId(idInput);
334
+ const task = await readStoredTask(options.channelDir, id);
335
+ if (!task)
336
+ return `找不到任务:${id}`;
337
+ if (field === "wake") {
338
+ if (!value) {
339
+ task.fields.wake = undefined;
340
+ }
341
+ else if (!Number.isFinite(new Date(value).getTime())) {
342
+ return `wake "${value}" 不是合法的 ISO8601 时间。`;
343
+ }
344
+ else {
345
+ task.fields.wake = value;
346
+ }
347
+ }
348
+ else {
349
+ const control = task.fields.control ?? createDefaultTaskControl();
350
+ try {
351
+ task.fields.control = applyTaskControlPatch(control, field === "next"
352
+ ? { nextAction: value }
353
+ : field === "deadline"
354
+ ? { deadline: value }
355
+ : field === "priority"
356
+ ? { priority: parseTaskPriority(value) }
357
+ : { maxAttempts: parseAttempts(value) });
358
+ }
359
+ catch (error) {
360
+ return errorMessage(error);
361
+ }
362
+ }
363
+ await writeStoredTask(task);
364
+ return `已更新任务 ${id}:${field} = ${value || "(已清除)"}`;
365
+ }
366
+ function parseTaskPriority(value) {
367
+ if (!TASK_PRIORITIES.includes(value)) {
368
+ throw new Error(`priority 必须是 ${TASK_PRIORITIES.join(" / ")} 之一。`);
369
+ }
370
+ return value;
371
+ }
372
+ function parseAttempts(value) {
373
+ const parsed = Number(value);
374
+ if (!Number.isInteger(parsed) || parsed < 1) {
375
+ throw new Error("attempts 必须是不小于 1 的整数。");
376
+ }
377
+ return parsed;
276
378
  }
277
379
  async function runTask(options, idInput) {
278
380
  const id = normalizeTaskId(idInput);
279
381
  const task = await readStoredTask(options.channelDir, id);
280
382
  if (!task)
281
- return `Task not found: ${id}`;
383
+ return `找不到任务:${id}`;
282
384
  const from = normalizeStoredStatus(task.fields.status);
283
385
  try {
284
386
  resolveTaskTransition("run", id, from);
@@ -286,6 +388,9 @@ async function runTask(options, idInput) {
286
388
  catch (error) {
287
389
  return errorMessage(error);
288
390
  }
391
+ const blocked = restartBlockedMessage(id, task.fields.control);
392
+ if (blocked)
393
+ return blocked;
289
394
  task.fields.status = "active";
290
395
  task.fields.wake = undefined;
291
396
  if (task.fields.control) {
@@ -299,13 +404,13 @@ async function runTask(options, idInput) {
299
404
  if (!enqueued && claim)
300
405
  await releaseTaskAttemptClaim(options.channelDir, id, claim, now);
301
406
  return enqueued
302
- ? `Enqueued task ${id} for an immediate attempt.`
303
- : `Task ${id} is ready. Start or use the DingTalk daemon for automatic dispatch, or send a normal prompt in this session to advance it.`;
407
+ ? `已把任务 ${id} 排入一次立即执行。`
408
+ : `任务 ${id} 已就绪。启动钉钉守护进程可自动派发,或在本会话里直接发一条普通消息推进它。`;
304
409
  }
305
410
  function renderUsageLine(entry) {
306
411
  const control = entry.frontmatter.control;
307
412
  if (!control)
308
- return `- ${entry.id}: legacy task (no governed usage recorded)`;
413
+ return `- ${entry.id}:旧格式任务(没有受治理的用量记录)`;
309
414
  const verification = control.verification;
310
415
  const cycleCost = control.usage.costKnown ? `$${control.usage.costUsd.toFixed(4)}` : "unavailable";
311
416
  return [
@@ -320,7 +425,7 @@ async function taskStats(options, idInput) {
320
425
  const id = normalizeTaskId(idInput);
321
426
  const task = await readStoredTask(options.channelDir, id, true, true);
322
427
  if (!task)
323
- return `Task not found: ${id}`;
428
+ return `找不到任务:${id}`;
324
429
  const entry = {
325
430
  id,
326
431
  title: extractTaskTitle(task.body, id),
@@ -333,7 +438,7 @@ async function taskStats(options, idInput) {
333
438
  },
334
439
  actionable: false,
335
440
  };
336
- return `# Task Stats\n\n${renderUsageLine(entry)}`;
441
+ return `# 任务用量\n\n${renderUsageLine(entry)}`;
337
442
  }
338
443
  const entries = await readActiveTasks(tasksDir(options.channelDir));
339
444
  const governed = entries.filter((entry) => entry.frontmatter.control);
@@ -349,7 +454,7 @@ async function taskStats(options, idInput) {
349
454
  const verified = governed.filter((entry) => entry.frontmatter.control?.verification.status === "passed").length;
350
455
  const stalled = governed.filter((entry) => entry.frontmatter.control?.lastOutcome === "failed").length;
351
456
  return [
352
- "# Task Stats",
457
+ "# 任务用量",
353
458
  "",
354
459
  `governed tasks: ${governed.length}/${entries.length}`,
355
460
  `this cycle: ${totals.attempts} attempts, ${totals.tokens} tokens, ${totals.costKnown ? `$${totals.costUsd.toFixed(4)}` : "cost unavailable"}, ${totals.wallTimeMinutes.toFixed(1)}m`,
@@ -366,20 +471,20 @@ async function showTask(channelDir, id) {
366
471
  const archivePath = resolveTaskPath(dir, taskId, "archive");
367
472
  const path = existsSync(activePath) ? activePath : existsSync(archivePath) ? archivePath : undefined;
368
473
  if (!path) {
369
- return `Task not found: ${taskId}`;
474
+ return `找不到任务:${taskId}`;
370
475
  }
371
- const location = path === archivePath ? " (archived)" : "";
476
+ const location = path === archivePath ? "(已归档)" : "";
372
477
  const content = await readFile(path, "utf-8");
373
- return `# Task: ${taskId}${location}\n\n\`\`\`markdown\n${content}\n\`\`\``;
478
+ return `# 任务:${taskId}${location}\n\n\`\`\`markdown\n${content}\n\`\`\``;
374
479
  }
375
480
  async function listArchive(channelDir) {
376
481
  const dir = join(tasksDir(channelDir), "archive");
377
482
  if (!existsSync(dir)) {
378
- return "# Archived Tasks\n\nNo archived tasks.";
483
+ return "# 已归档任务\n\n暂无已归档任务。";
379
484
  }
380
485
  const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".md")).sort();
381
486
  if (filenames.length === 0) {
382
- return "# Archived Tasks\n\nNo archived tasks.";
487
+ return "# 已归档任务\n\n暂无已归档任务。";
383
488
  }
384
489
  const blocks = [];
385
490
  for (const filename of filenames) {
@@ -392,17 +497,18 @@ async function listArchive(channelDir) {
392
497
  blocks.push(`- ${id}`);
393
498
  }
394
499
  }
395
- return `# Archived Tasks: ${blocks.length}\n\n${blocks.join("\n")}`;
500
+ return `# 已归档任务:${blocks.length}\n\n${blocks.join("\n")}`;
396
501
  }
397
502
  async function doctor(options) {
398
503
  if (!options.workspaceDir || !options.channelId) {
399
- return "# Task Doctor\n\nNot available: workspaceDir and channelId are required.";
504
+ return "# 任务体检\n\n不可用:需要 workspaceDir 与 channelId。";
400
505
  }
401
506
  const now = Date.now();
402
507
  const entries = await readActiveTasks(tasksDir(options.channelDir), now);
403
508
  const activeIds = new Set(entries.map((entry) => entry.id));
404
509
  const archivedIds = await readArchivedTaskIds(options.channelDir);
405
510
  const events = await readTaskEvents(options.workspaceDir, options.channelId);
511
+ const runningJobTaskIds = channelJobTaskIds(options.channelId);
406
512
  const issues = [];
407
513
  for (const entry of entries) {
408
514
  const status = entry.frontmatter.status ?? "active";
@@ -459,6 +565,14 @@ async function doctor(options) {
459
565
  issues.push(issue(`tasks/${entry.id}.md is missing standard section(s): ${missing.join(", ")}.`, `Ask the agent to normalize tasks/${entry.id}.md to the standard task skeleton.`));
460
566
  }
461
567
  }
568
+ // A parked task is waiting for someone to call it: a finished background job, a user
569
+ // message, or `/tasks run`. The driver deliberately will not (see `isTaskParked`), so with
570
+ // no running job carrying this id, whether it ever resumes is entirely up to the user.
571
+ // That is legitimate when it is waiting on an answer — and indistinguishable, on disk,
572
+ // from a task everyone has forgotten. Report the fact and name every way out.
573
+ if (isTaskParked(entry.frontmatter) && !runningJobTaskIds.has(entry.id)) {
574
+ issues.push(issue(`tasks/${entry.id}.md is parked (waiting, no wake) and no running background job will wake it.`, `It resumes only when you reply to it, run /tasks run ${entry.id}, or give it a wake with /tasks set ${entry.id} wake <ISO8601>; cancel it if what it waits for is gone.`));
575
+ }
462
576
  if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
463
577
  issues.push(issue(`tasks/${entry.id}.md has an invalid wake value (${entry.frontmatter.wake}); the native driver will treat it as due.`, `Use task_manage set or progress to replace wake with ISO8601, or clear it if the task should continue now.`));
464
578
  }
@@ -493,9 +607,9 @@ async function doctor(options) {
493
607
  }
494
608
  }
495
609
  if (issues.length === 0) {
496
- return "# Task Doctor\n\nNo task ledger issues found.";
610
+ return "# 任务体检\n\n未发现任务台账问题。";
497
611
  }
498
- return `# Task Doctor\n\nFound ${issues.length} issue${issues.length === 1 ? "" : "s"}:\n\n${issues.join("\n")}`;
612
+ return `# 任务体检\n\n发现 ${issues.length} 个问题:\n\n${issues.join("\n")}`;
499
613
  }
500
614
  export async function handleTasksCommand(options) {
501
615
  let command;
@@ -522,6 +636,8 @@ export async function handleTasksCommand(options) {
522
636
  return await resumeTask(options, command.id);
523
637
  case "run":
524
638
  return await runTask(options, command.id);
639
+ case "set":
640
+ return await setTaskField(options, command.id, command.field, command.value);
525
641
  case "stats":
526
642
  return await taskStats(options, command.id);
527
643
  case "doctor":
@@ -530,6 +646,6 @@ export async function handleTasksCommand(options) {
530
646
  }
531
647
  catch (error) {
532
648
  const message = errorMessage(error);
533
- return `Could not ${command.action} tasks: ${message}`;
649
+ return `执行 /tasks ${command.action} 失败:${message}`;
534
650
  }
535
651
  }
@@ -10,10 +10,10 @@ export interface TaskDriverOptions {
10
10
  onDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
11
11
  getSettings: () => PipiclawTaskDriverSettings;
12
12
  /**
13
- * Externally visible effects recorded for a channel so far (spec 031, D7). Defaults to a
14
- * constant, which simply makes the fingerprint depend on ledger fields alone.
13
+ * Externally visible effects produced by this task's own turns so far (spec 031, D7).
14
+ * Defaults to a constant, which simply makes the fingerprint depend on ledger fields alone.
15
15
  */
16
- getEffectCount?: (channelId: string) => number;
16
+ getEffectCount?: (channelId: string, taskId: string) => number;
17
17
  /** Master autonomy switch (`tools.tasks.enabled`); re-read every tick. Defaults to on. */
18
18
  isEnabled?: () => boolean;
19
19
  /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
@@ -49,8 +49,9 @@ function attemptKey(channelId, taskId) {
49
49
  *
50
50
  * `latestNote` is deliberately absent (spec 031, D7): it is the model's own account of its work,
51
51
  * so including it let a wake that did nothing but append a note reset the futile counter forever,
52
- * and let a wake that changed real files count as stalled. The channel's effect tally stands in
53
- * for the work itself instead.
52
+ * and let a wake that changed real files count as stalled. The task's own effect tally stands in
53
+ * for the work itself instead — per task, not per channel, so a neighbour's activity (including
54
+ * the user chatting) neither certifies progress here nor hides a task that is spinning.
54
55
  */
55
56
  function taskFingerprint(entry, effects) {
56
57
  const control = entry.frontmatter.control;
@@ -67,12 +68,37 @@ function taskFingerprint(entry, effects) {
67
68
  `effects:${effects}`,
68
69
  ].join("\0");
69
70
  }
70
- function isEligible(attempt, fingerprint, nowMs, settings) {
71
+ /**
72
+ * How long a task must wait after its last attempt, in three tiers.
73
+ *
74
+ * Backoff and cadence are different jobs, and one delay used to do both: any wake that changed
75
+ * the ledger — including one that wrote code — waited out the same continuation delay as one that
76
+ * only edited a note. A twenty-step task therefore spent well over an hour purely idle, which is
77
+ * fatal for the "drive an external agent in small steps" shape this driver exists for.
78
+ *
79
+ * So the tiers are keyed on evidence, not on the boolean "something changed":
80
+ * - this task's effect tally grew ⇒ its last wake actually did something ⇒ continue at once;
81
+ * - the ledger changed with no effect (status/note churn) ⇒ the ordinary continuation delay;
82
+ * - nothing changed ⇒ the long stalled-retry backoff, and the futile counter keeps running.
83
+ *
84
+ * Nothing here relaxes the stop-losses: the fast tier still costs one attempt against
85
+ * `budget.maxAttempts`, so a task that spins productively-looking still hits the governor — just
86
+ * sooner in wall time instead of an hour per step.
87
+ */
88
+ function attemptDelayMs(attempt, fingerprint, effects, settings) {
89
+ // A dispatch the channel refused never ran; retry it on the short delay regardless of state.
90
+ if (!attempt.accepted)
91
+ return settings.continuationDelayMinutes * 60_000;
92
+ if (attempt.fingerprint === fingerprint)
93
+ return settings.stalledRetryMinutes * 60_000;
94
+ if (effects > attempt.effects)
95
+ return 0;
96
+ return settings.continuationDelayMinutes * 60_000;
97
+ }
98
+ function isEligible(attempt, fingerprint, effects, nowMs, settings) {
71
99
  if (!attempt)
72
100
  return true;
73
- const changed = attempt.fingerprint !== fingerprint;
74
- const delayMinutes = changed || !attempt.accepted ? settings.continuationDelayMinutes : settings.stalledRetryMinutes;
75
- return nowMs - attempt.atMs >= delayMinutes * 60_000;
101
+ return nowMs - attempt.atMs >= attemptDelayMs(attempt, fingerprint, effects, settings);
76
102
  }
77
103
  /**
78
104
  * Stable, provenance-derived dispatch id for a task wake (spec 031, D1).
@@ -372,10 +398,10 @@ export class TaskDriver {
372
398
  log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
373
399
  }
374
400
  const key = attemptKey(channelId, entry.id);
375
- const effects = this.options.getEffectCount?.(channelId) ?? 0;
401
+ const effects = this.options.getEffectCount?.(channelId, entry.id) ?? 0;
376
402
  const fingerprint = taskFingerprint(entry, effects);
377
403
  const previous = this.attempts.get(key);
378
- if (!isEligible(previous, fingerprint, nowMs, settings))
404
+ if (!isEligible(previous, fingerprint, effects, nowMs, settings))
379
405
  continue;
380
406
  // D5: a wake that was accepted and left the ledger fingerprint unchanged made no
381
407
  // visible progress. Count consecutive such wakes (a changed fingerprint — including
@@ -404,7 +430,7 @@ export class TaskDriver {
404
430
  this.observeDispatch(event, accepted);
405
431
  if (!accepted && claim)
406
432
  await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
407
- this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, futileCount });
433
+ this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, effects, futileCount });
408
434
  this.lastDispatchedTaskId.set(channelId, entry.id);
409
435
  if (accepted) {
410
436
  dispatched++;
@@ -420,10 +446,14 @@ export class TaskDriver {
420
446
  this.attempts.delete(key);
421
447
  }
422
448
  // A backed-off task becomes eligible again at attempt time + its retry delay; wake then
423
- // so an unchanged ledger is still retried without polling. Changed ledgers arrive via nudge.
449
+ // so an unchanged ledger is still retried without polling. Changed ledgers arrive via
450
+ // nudge. Both tiers are noted because which one applies depends on the ledger as it will
451
+ // be *then*: `noteHorizon` keeps whichever is next in the future, so the short tier is
452
+ // honored on time and the long one is still not missed.
424
453
  for (const attempt of this.attempts.values()) {
425
- const delayMinutes = attempt.accepted ? settings.stalledRetryMinutes : settings.continuationDelayMinutes;
426
- this.noteHorizon(attempt.atMs + delayMinutes * 60_000, nowMs);
454
+ this.noteHorizon(attempt.atMs + settings.continuationDelayMinutes * 60_000, nowMs);
455
+ if (attempt.accepted)
456
+ this.noteHorizon(attempt.atMs + settings.stalledRetryMinutes * 60_000, nowMs);
427
457
  }
428
458
  const channelSet = new Set(channels);
429
459
  for (const channelId of this.lastDispatchedTaskId.keys()) {
@@ -171,9 +171,19 @@ export declare class PipiclawSettingsManager {
171
171
  private settings;
172
172
  private loadErrors;
173
173
  private retiredKeys;
174
+ /** The file's change token as of the last actual parse; see `reload`. */
175
+ private loadedStamp;
174
176
  constructor(baseDir: string);
175
177
  private load;
176
178
  private save;
179
+ /**
180
+ * Re-read `settings.json`, but only when the file actually changed.
181
+ *
182
+ * The task driver and the memory scheduler call this on every tick — and the driver ticks
183
+ * after every turn — so an unchanged file was being read, JSON-parsed and scanned for retired
184
+ * keys many times a minute. Skipping keeps the last parse *and* its diagnostics, which is the
185
+ * same thing a re-parse of identical bytes would produce.
186
+ */
177
187
  reload(): void;
178
188
  drainErrors(): SettingsError[];
179
189
  getDiagnostics(): ConfigDiagnostic[];
package/dist/settings.js CHANGED
@@ -10,6 +10,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
10
10
  import { dirname, join } from "path";
11
11
  import * as log from "./log.js";
12
12
  import { getMemoryMaintenanceTuning, getSessionRefreshCadence, } from "./memory/maintenance-tuning.js";
13
+ import { fileStamp } from "./shared/file-stamp.js";
13
14
  const DEFAULT_TUI = {
14
15
  responseMode: "full_progress_then_plain_final",
15
16
  };
@@ -138,12 +139,15 @@ export class PipiclawSettingsManager {
138
139
  constructor(baseDir) {
139
140
  this.loadErrors = [];
140
141
  this.retiredKeys = [];
142
+ /** The file's change token as of the last actual parse; see `reload`. */
143
+ this.loadedStamp = "";
141
144
  this.settingsPath = join(baseDir, "settings.json");
142
145
  this.settings = this.load();
143
146
  }
144
147
  load() {
145
148
  this.loadErrors = [];
146
149
  this.retiredKeys = [];
150
+ this.loadedStamp = fileStamp(this.settingsPath);
147
151
  if (!existsSync(this.settingsPath)) {
148
152
  return {};
149
153
  }
@@ -180,7 +184,17 @@ export class PipiclawSettingsManager {
180
184
  log.logWarning(`Could not save settings file`, `${this.settingsPath}\n${String(error)}`);
181
185
  }
182
186
  }
187
+ /**
188
+ * Re-read `settings.json`, but only when the file actually changed.
189
+ *
190
+ * The task driver and the memory scheduler call this on every tick — and the driver ticks
191
+ * after every turn — so an unchanged file was being read, JSON-parsed and scanned for retired
192
+ * keys many times a minute. Skipping keeps the last parse *and* its diagnostics, which is the
193
+ * same thing a re-parse of identical bytes would produce.
194
+ */
183
195
  reload() {
196
+ if (fileStamp(this.settingsPath) === this.loadedStamp)
197
+ return;
184
198
  this.settings = this.load();
185
199
  }
186
200
  drainErrors() {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
3
+ * cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
4
+ *
5
+ * Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
6
+ * `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
7
+ * triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
8
+ * that preserves the timestamp, ctime catches the rename, size catches the rest.
9
+ */
10
+ export declare function fileStamp(path: string): string;
@@ -0,0 +1,19 @@
1
+ import { statSync } from "node:fs";
2
+ /**
3
+ * A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
4
+ * cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
5
+ *
6
+ * Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
7
+ * `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
8
+ * triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
9
+ * that preserves the timestamp, ctime catches the rename, size catches the rest.
10
+ */
11
+ export function fileStamp(path) {
12
+ try {
13
+ const stats = statSync(path);
14
+ return `${stats.mtimeMs}:${stats.ctimeMs}:${stats.size}`;
15
+ }
16
+ catch {
17
+ return "";
18
+ }
19
+ }