@oyasmi/pipiclaw 0.8.10 → 0.8.11-beta.3

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 (106) hide show
  1. package/README.md +3 -3
  2. package/dist/agent/channel-runner.d.ts +11 -0
  3. package/dist/agent/channel-runner.js +58 -27
  4. package/dist/agent/commands.js +2 -3
  5. package/dist/agent/effect-ledger.d.ts +1 -1
  6. package/dist/agent/effect-ledger.js +2 -2
  7. package/dist/agent/prompt/sections.js +3 -3
  8. package/dist/agent/runner-factory.d.ts +2 -0
  9. package/dist/agent/session-events.js +1 -1
  10. package/dist/main.js +6 -0
  11. package/dist/memory/commands.js +6 -1
  12. package/dist/memory/consolidation.d.ts +8 -1
  13. package/dist/memory/consolidation.js +34 -6
  14. package/dist/memory/extraction.d.ts +11 -3
  15. package/dist/memory/extraction.js +19 -6
  16. package/dist/memory/files.d.ts +2 -0
  17. package/dist/memory/files.js +14 -0
  18. package/dist/memory/maintenance-gates.d.ts +3 -0
  19. package/dist/memory/maintenance-gates.js +5 -2
  20. package/dist/memory/maintenance-jobs.js +19 -2
  21. package/dist/memory/maintenance-state.d.ts +29 -0
  22. package/dist/memory/maintenance-state.js +100 -8
  23. package/dist/memory/metadata.d.ts +9 -0
  24. package/dist/memory/metadata.js +5 -0
  25. package/dist/memory/probation.d.ts +21 -0
  26. package/dist/memory/probation.js +48 -0
  27. package/dist/memory/promotion.d.ts +26 -1
  28. package/dist/memory/promotion.js +34 -4
  29. package/dist/memory/recall.js +38 -19
  30. package/dist/memory/session-corpus.js +12 -11
  31. package/dist/memory/session-search.js +25 -6
  32. package/dist/memory/sidecar-worker.js +2 -0
  33. package/dist/memory/task-digest.d.ts +3 -2
  34. package/dist/memory/task-digest.js +22 -8
  35. package/dist/models/auth-cli.d.ts +25 -0
  36. package/dist/models/auth-cli.js +344 -0
  37. package/dist/models/login-ui.d.ts +35 -0
  38. package/dist/models/login-ui.js +145 -0
  39. package/dist/models/provider-login.d.ts +41 -0
  40. package/dist/models/provider-login.js +126 -0
  41. package/dist/models/utils.d.ts +6 -0
  42. package/dist/models/utils.js +10 -0
  43. package/dist/playbooks/memory-and-learning.md +7 -1
  44. package/dist/playbooks/outbound-media.md +7 -33
  45. package/dist/playbooks/runtime-orientation.md +2 -0
  46. package/dist/playbooks/task-closeout.md +22 -35
  47. package/dist/playbooks/task-delegation.md +13 -35
  48. package/dist/playbooks/task-driving.md +36 -56
  49. package/dist/playbooks/task-planning.md +26 -45
  50. package/dist/runtime/bootstrap.js +48 -14
  51. package/dist/runtime/delivery.js +8 -2
  52. package/dist/runtime/dingtalk.d.ts +6 -3
  53. package/dist/runtime/dingtalk.js +6 -39
  54. package/dist/runtime/events.js +4 -3
  55. package/dist/runtime/proxy.d.ts +36 -0
  56. package/dist/runtime/proxy.js +68 -0
  57. package/dist/runtime/store.d.ts +8 -2
  58. package/dist/runtime/store.js +12 -6
  59. package/dist/runtime/task-commands.d.ts +0 -2
  60. package/dist/runtime/task-commands.js +99 -112
  61. package/dist/runtime/task-driver.d.ts +5 -0
  62. package/dist/runtime/task-driver.js +155 -53
  63. package/dist/runtime/task-migration.d.ts +9 -0
  64. package/dist/runtime/task-migration.js +75 -2
  65. package/dist/security/command-guard.js +51 -17
  66. package/dist/security/path-guard.js +72 -14
  67. package/dist/shared/open-browser.d.ts +6 -0
  68. package/dist/shared/open-browser.js +22 -0
  69. package/dist/shared/recoverable-error.d.ts +1 -1
  70. package/dist/shared/recoverable-error.js +1 -1
  71. package/dist/subagents/tool.js +2 -0
  72. package/dist/tasks/control.d.ts +38 -67
  73. package/dist/tasks/control.js +90 -152
  74. package/dist/tasks/ledger.d.ts +104 -22
  75. package/dist/tasks/ledger.js +419 -56
  76. package/dist/tasks/store.d.ts +11 -10
  77. package/dist/tasks/store.js +58 -27
  78. package/dist/tasks/transitions.d.ts +8 -36
  79. package/dist/tasks/transitions.js +29 -54
  80. package/dist/tasks/verification.d.ts +2 -2
  81. package/dist/tools/index.d.ts +2 -0
  82. package/dist/tools/index.js +1 -0
  83. package/dist/tools/memory-manage.js +8 -1
  84. package/dist/tools/read.js +19 -5
  85. package/dist/tools/registry.d.ts +1 -0
  86. package/dist/tools/registry.js +1 -0
  87. package/dist/tools/task-manage/lifecycle.d.ts +1 -7
  88. package/dist/tools/task-manage/lifecycle.js +76 -77
  89. package/dist/tools/task-manage/schema.d.ts +10 -5
  90. package/dist/tools/task-manage/schema.js +35 -21
  91. package/dist/tools/task-manage/shared.d.ts +1 -1
  92. package/dist/tools/task-manage/shared.js +29 -30
  93. package/dist/tools/task-manage/types.d.ts +7 -1
  94. package/dist/tools/task-manage/verification.d.ts +4 -5
  95. package/dist/tools/task-manage/verification.js +43 -15
  96. package/dist/tools/task-manage.d.ts +1 -1
  97. package/dist/tools/task-manage.js +9 -9
  98. package/dist/tui/app.js +1 -2
  99. package/dist/tui/commands.d.ts +1 -1
  100. package/dist/tui/commands.js +1 -1
  101. package/dist/tui/turn-controller.d.ts +1 -1
  102. package/dist/usage/ledger.d.ts +1 -1
  103. package/dist/usage/ledger.js +47 -22
  104. package/dist/usage/render.d.ts +1 -1
  105. package/dist/usage/render.js +8 -6
  106. package/package.json +7 -6
@@ -50,9 +50,15 @@ export declare class ChannelStore {
50
50
  private closed;
51
51
  constructor(config: ChannelStoreConfig);
52
52
  /**
53
- * Get or create the directory for a channel/DM
53
+ * The archive path for a channel — resolved, not created.
54
+ *
55
+ * This used to call `ensureChannelDir`, i.e. a synchronous `mkdirSync` on the event loop for
56
+ * every archived message. `logBotResponse` runs on every progress update of a streaming turn,
57
+ * so that was a blocking syscall per progress tick. The appender's own `ensureDir` already
58
+ * creates the directory before it writes, and memoizes it, so the mkdir here was pure
59
+ * duplicated I/O.
54
60
  */
55
- getChannelDir(channelId: string): string;
61
+ private channelArchiveDir;
56
62
  /**
57
63
  * Log a message to the channel's log.jsonl raw archive.
58
64
  * This file is cold storage and is not proactively loaded into memory context.
@@ -3,7 +3,7 @@ import { writeFile } from "fs/promises";
3
3
  import { basename, dirname, join } from "path";
4
4
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
5
5
  import { formatLocalTime } from "../shared/local-time.js";
6
- import { ensureChannelDir } from "./channel-paths.js";
6
+ import { getChannelDir } from "./channel-paths.js";
7
7
  const MAX_LOG_SIZE_BYTES = 1_000_000;
8
8
  const DEDUPE_TTL_MS = 60_000;
9
9
  const DEDUPE_CLEANUP_INTERVAL_MS = 30_000;
@@ -35,10 +35,16 @@ export class ChannelStore {
35
35
  }
36
36
  }
37
37
  /**
38
- * Get or create the directory for a channel/DM
38
+ * The archive path for a channel — resolved, not created.
39
+ *
40
+ * This used to call `ensureChannelDir`, i.e. a synchronous `mkdirSync` on the event loop for
41
+ * every archived message. `logBotResponse` runs on every progress update of a streaming turn,
42
+ * so that was a blocking syscall per progress tick. The appender's own `ensureDir` already
43
+ * creates the directory before it writes, and memoizes it, so the mkdir here was pure
44
+ * duplicated I/O.
39
45
  */
40
- getChannelDir(channelId) {
41
- return ensureChannelDir(this.workingDir, channelId);
46
+ channelArchiveDir(channelId) {
47
+ return getChannelDir(this.workingDir, channelId);
42
48
  }
43
49
  /**
44
50
  * Log a message to the channel's log.jsonl raw archive.
@@ -58,7 +64,7 @@ export class ChannelStore {
58
64
  }
59
65
  this.recentlyLogged.delete(dedupeKey);
60
66
  }
61
- const logPath = join(this.getChannelDir(channelId), "log.jsonl");
67
+ const logPath = join(this.channelArchiveDir(channelId), "log.jsonl");
62
68
  if (!message.date) {
63
69
  message.date = formatLocalTime();
64
70
  }
@@ -72,7 +78,7 @@ export class ChannelStore {
72
78
  async logSubAgentRun(channelId, run) {
73
79
  if (this.closed)
74
80
  return;
75
- const logPath = join(this.getChannelDir(channelId), "subagent-runs.jsonl");
81
+ const logPath = join(this.channelArchiveDir(channelId), "subagent-runs.jsonl");
76
82
  if (!this.archiveAppender.tryAppend({ filePath: logPath, value: run })) {
77
83
  throw new Error("Sub-agent archive queue is full. Retry after pending log writes drain.");
78
84
  }
@@ -5,8 +5,6 @@ export interface HandleTasksCommandOptions {
5
5
  /** Workspace directory; required for `/tasks doctor` because events are workspace-scoped. */
6
6
  workspaceDir?: string;
7
7
  channelId?: string;
8
- /** Direct command issuer; used to create an auditable external-action approval. */
9
- approver?: string;
10
8
  /** Optional immediate task wake, available in the long-lived DingTalk runtime. */
11
9
  dispatchTask?: (id: string, attemptGeneration?: number) => Promise<boolean>;
12
10
  }
@@ -4,11 +4,11 @@ import { join, resolve, sep } from "node:path";
4
4
  import { channelJobTaskIds } from "../agent/job-manager.js";
5
5
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
6
6
  import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
7
- import { nextTaskWake } from "../shared/task-schedule.js";
7
+ import { nextTaskWake, validateTaskSchedule } from "../shared/task-schedule.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { isRecord } from "../shared/type-guards.js";
10
10
  import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys, TASK_PRIORITIES, taskBudgetViolation, } from "../tasks/control.js";
11
- import { extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../tasks/ledger.js";
11
+ import { countTaskDodItems, extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
12
12
  import { withTaskMutation } from "../tasks/mutation-lock.js";
13
13
  import { claimTaskAttempt, openRecurringTaskCycle, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
14
14
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
@@ -19,7 +19,7 @@ import { parseScheduledEventContent } from "./events.js";
19
19
  *
20
20
  * Deliberately a small, flat set: the ones a user already knows they want to change (when it
21
21
  * should wake, what it should do next, how much rope it has). Everything structural — status
22
- * transitions, verification, approval, side effects — stays with `task_manage`, whose state
22
+ * transitions and verification — stays with `task_manage`, whose state
23
23
  * machine those fields belong to. The value is the rest of the line, so it may contain spaces.
24
24
  */
25
25
  const SETTABLE_TASK_FIELDS = ["wake", "next", "priority", "attempts", "deadline"];
@@ -31,9 +31,8 @@ function usage() {
31
31
  - \`/tasks\` — 列出本频道进行中的任务
32
32
  - \`/tasks show <id>\` — 查看单个任务文件(进行中或已归档)
33
33
  - \`/tasks archive\` — 列出已归档(已关闭)的任务
34
- - \`/tasks approve <id>\` — 显式批准该任务的外部副作用
35
- - \`/tasks pause <id>\` — 停止该任务的自动唤醒
36
- - \`/tasks resume <id>\` — 让暂停的任务在下一轮扫描中恢复
34
+ - \`/tasks pause <id>\` — 停止该任务的自动执行(保留当前阶段与 wake)
35
+ - \`/tasks resume <id>\` — 重新启用该任务,按当前阶段继续
37
36
  - \`/tasks run <id>\` — 恢复并立即排入一次执行(需要运行时可用)
38
37
  - \`/tasks set <id> <${SETTABLE_TASK_FIELDS.join("|")}> <值>\` — 直接改一个字段,不花一个 LLM 回合
39
38
  - \`/tasks stats [id]\` — 查看任务级的尝试次数、token、花费与验收结果
@@ -64,12 +63,6 @@ function parseTasksCommand(args) {
64
63
  throw new Error("用法:/tasks doctor");
65
64
  return { action: "doctor" };
66
65
  }
67
- if (action === "approve") {
68
- const id = parts[1];
69
- if (!id || parts.length > 2)
70
- throw new Error("用法:/tasks approve <id>");
71
- return { action: "approve", id };
72
- }
73
66
  if (action === "pause" || action === "resume") {
74
67
  const id = parts[1];
75
68
  if (!id || parts.length > 2)
@@ -204,7 +197,7 @@ async function readActiveTaskContent(channelDir, id) {
204
197
  async function listTasks(channelDir) {
205
198
  const dir = tasksDir(channelDir);
206
199
  const now = Date.now();
207
- const entries = await readActiveTasks(dir, now);
200
+ const entries = (await readActiveTasks(dir, now)).filter((entry) => !entry.frontmatter.archiveOutcome);
208
201
  if (entries.length === 0) {
209
202
  return "# 任务\n\n当前没有进行中的任务。";
210
203
  }
@@ -217,17 +210,20 @@ async function listTasks(channelDir) {
217
210
  detail.push(`attempts: ${control.usage.attempts}/${control.budget.maxAttempts}`);
218
211
  if (control.verification.required)
219
212
  detail.push(`verify: required/${control.verification.status}`);
220
- if (control.sideEffects !== "workspace") {
221
- detail.push(`effects: ${control.sideEffects}/${control.externalApproval}`);
222
- }
213
+ if (control.waitingFor)
214
+ detail.push(`waiting for: ${control.waitingFor}`);
215
+ if (control.stop)
216
+ detail.push(`stop: ${control.stop.by} — ${control.stop.reason}`);
223
217
  if (control.deadline)
224
218
  detail.push(`deadline: ${control.deadline}`);
225
219
  if (control.nextAction)
226
220
  detail.push(`next: ${control.nextAction}`);
227
221
  if (control.cycleId) {
228
- detail.push(`${status === "done" ? "last" : "current"} cycle: ${control.cycleId}`);
222
+ detail.push(`${status === "sleeping" ? "last" : "current"} cycle: ${control.cycleId}`);
229
223
  }
230
224
  }
225
+ if (entry.frontmatter.enabled === false)
226
+ detail.push("enabled: false");
231
227
  if (entry.frontmatter.recurrence)
232
228
  detail.push(`recurrence: ${entry.frontmatter.recurrence}`);
233
229
  if (entry.frontmatter.schedule) {
@@ -235,31 +231,7 @@ async function listTasks(channelDir) {
235
231
  }
236
232
  return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
237
233
  });
238
- return `# 任务:${entries.length} 个进行中\n\n${blocks.join("\n")}`;
239
- }
240
- async function approveTask(options, idInput) {
241
- const id = normalizeTaskId(idInput);
242
- const task = await readStoredTask(options.channelDir, id);
243
- if (!task)
244
- return `找不到任务:${id}`;
245
- const control = task.fields.control;
246
- if (!control)
247
- return `任务 ${id} 没有受治理的 control 元数据,先让 agent 规范化后再审批。`;
248
- if (task.fields.status === "done" || task.fields.status === "cancelled") {
249
- return `任务 ${id} 已是 ${task.fields.status},不能再授予外部动作审批。`;
250
- }
251
- if (control.sideEffects !== "external") {
252
- return `任务 ${id} 未标记为外部副作用,无需审批。`;
253
- }
254
- if (control.externalApproval === "granted") {
255
- return `任务 ${id} 已由 ${control.approvalBy ?? "某位用户"} 于 ${control.approvedAt ?? "未知时间"} 批准过。`;
256
- }
257
- control.externalApproval = "granted";
258
- control.approvalBy = options.approver?.trim() || "unknown-user";
259
- control.approvedAt = formatLocalTime();
260
- control.approvalBodyHash = taskBodyHash(task.body);
261
- await writeStoredTask(task);
262
- return `已批准任务 ${id} 的外部副作用,审批人记为 ${control.approvalBy}。`;
234
+ return `# 任务:${entries.length} 个活动任务\n\n${blocks.join("\n")}`;
263
235
  }
264
236
  export async function pauseTask(options, idInput) {
265
237
  const id = normalizeTaskId(idInput);
@@ -269,67 +241,37 @@ async function pauseTaskLocked(options, id) {
269
241
  const task = await readStoredTask(options.channelDir, id);
270
242
  if (!task)
271
243
  return `找不到任务:${id}`;
272
- const from = normalizeStoredStatus(task.fields.status);
273
- if (from === "paused")
274
- return `任务 ${id} 已经是暂停状态。`;
244
+ const from = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
275
245
  try {
276
246
  resolveTaskTransition("pause", id, from);
277
247
  }
278
248
  catch (error) {
279
249
  return errorMessage(error);
280
250
  }
281
- task.fields.status = "paused";
282
- task.fields.wake = undefined;
283
- if (task.fields.control) {
284
- task.fields.control.pausedBy = "user";
285
- task.fields.control.blockedReason = `Paused by ${options.approver?.trim() || "a user"}.`;
286
- }
251
+ if (task.fields.enabled === false)
252
+ return `任务 ${id} 已停用。需要继续时用 /tasks resume ${id}。`;
253
+ task.fields.enabled = false;
254
+ const control = task.fields.control ?? createDefaultTaskControl();
255
+ control.stop = { by: "user", reason: "Disabled by /tasks pause.", at: formatLocalTime() };
256
+ task.fields.control = control;
287
257
  await writeStoredTask(task);
288
- return `已暂停任务 ${id}。需要继续时用 /tasks resume ${id}。`;
289
- }
290
- /**
291
- * Why restarting this task would immediately stop it again, or `undefined` when it is free to run.
292
- *
293
- * The governor pauses on the same condition it re-checks on the next scan, so a plain resume of a
294
- * budget/deadline-exhausted task looked like it worked, cost one escalation turn, and landed back
295
- * in `paused` minutes later — while three separate places (the `/stop` receipt, `/tasks` usage,
296
- * the driving playbook) told the user resume was the fix. Refuse instead, and name the command
297
- * that actually unblocks it.
298
- */
299
- function restartBlockedMessage(id, control) {
300
- if (!control)
301
- return undefined;
302
- const violation = taskBudgetViolation(control, Date.now());
303
- if (!violation)
304
- return undefined;
305
- return [
306
- `任务 ${id} 仍然超出治理限额:${violation}。`,
307
- "直接恢复只会在下一轮扫描中被治理器再次暂停,并白白多花一个回合。",
308
- `先放宽限额:\`/tasks set ${id} attempts <n>\`(当前上限 ${control.budget.maxAttempts})` +
309
- `${control.deadline ? `,或 \`/tasks set ${id} deadline <本地时间>\`(当前 ${control.deadline})` : ""},然后再试一次。`,
310
- "若这个任务已经不该继续,用 `task_manage cancel` 关掉它。",
311
- ].join("\n");
258
+ return `已停用任务 ${id}。当前阶段与 wake 已保留;需要继续时用 /tasks resume ${id}。`;
312
259
  }
313
260
  export async function resumeTask(options, idInput) {
314
261
  const id = normalizeTaskId(idInput);
315
262
  const task = await readStoredTask(options.channelDir, id);
316
263
  if (!task)
317
264
  return `找不到任务:${id}`;
318
- const from = normalizeStoredStatus(task.fields.status);
319
- if (from !== "paused")
320
- return `任务 ${id} 当前是 ${from},并非暂停状态。`;
321
- const blocked = restartBlockedMessage(id, task.fields.control);
322
- if (blocked)
323
- return blocked;
265
+ const from = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
266
+ if (task.fields.enabled !== false)
267
+ return `任务 ${id} 已启用。`;
324
268
  resolveTaskTransition("resume", id, from);
325
- task.fields.status = "active";
326
- task.fields.wake = undefined;
269
+ task.fields.enabled = true;
327
270
  if (task.fields.control) {
328
- task.fields.control.pausedBy = undefined;
329
- task.fields.control.blockedReason = undefined;
271
+ task.fields.control.stop = undefined;
330
272
  }
331
273
  await writeStoredTask(task);
332
- return `已恢复任务 ${id},任务驱动器下一轮扫描会接上。`;
274
+ return `已重新启用任务 ${id},任务驱动器会按当前阶段与 wake 接上。`;
333
275
  }
334
276
  /**
335
277
  * Edit one task field directly.
@@ -400,30 +342,27 @@ async function runTask(options, idInput) {
400
342
  catch (error) {
401
343
  return errorMessage(error);
402
344
  }
403
- const blocked = restartBlockedMessage(id, task.fields.control);
404
- if (blocked)
405
- return blocked;
406
345
  const now = new Date();
407
- let claimedControl = task.fields.control;
408
- if (from === "done") {
346
+ if (from === "sleeping") {
409
347
  if (!task.fields.schedule) {
410
- return `任务 ${id} 已完成且不是周期任务,不能重新运行;如需新工作请创建新的 task id。`;
348
+ return `任务 ${id} 没有 schedule,不能从 sleeping 打开周期;如需新工作请创建新的 task id。`;
411
349
  }
412
- const opened = await openRecurringTaskCycle(options.channelDir, id, now);
350
+ const opened = await openRecurringTaskCycle(options.channelDir, id, now, true);
413
351
  if (!opened)
414
352
  return `任务 ${id} 无法打开新周期;先用 /tasks doctor 检查任务文件。`;
415
- claimedControl = opened.document.fields.control;
416
353
  }
417
354
  else {
418
355
  task.fields.status = "active";
419
356
  task.fields.wake = undefined;
357
+ task.fields.enabled = true;
420
358
  if (task.fields.control) {
421
- task.fields.control.pausedBy = undefined;
359
+ task.fields.control.stop = undefined;
360
+ task.fields.control.waitingFor = undefined;
422
361
  task.fields.control.blockedReason = undefined;
423
362
  }
424
363
  await writeStoredTask(task);
425
364
  }
426
- const claim = claimedControl ? await claimTaskAttempt(options.channelDir, id, now) : undefined;
365
+ const claim = await claimTaskAttempt(options.channelDir, id, now);
427
366
  const enqueued = await options.dispatchTask?.(id, claim?.generation);
428
367
  if (!enqueued && claim)
429
368
  await releaseTaskAttemptClaim(options.channelDir, id, claim);
@@ -456,7 +395,9 @@ async function taskStats(options, idInput) {
456
395
  frontmatter: {
457
396
  readable: true,
458
397
  status: task.fields.status,
398
+ enabled: task.fields.enabled !== false,
459
399
  wake: task.fields.wake,
400
+ schedule: task.fields.schedule,
460
401
  recurrence: task.fields.recurrence,
461
402
  control: task.fields.control,
462
403
  },
@@ -464,7 +405,7 @@ async function taskStats(options, idInput) {
464
405
  };
465
406
  return `# 任务用量\n\n${renderUsageLine(entry)}`;
466
407
  }
467
- const entries = await readActiveTasks(tasksDir(options.channelDir));
408
+ const entries = (await readActiveTasks(tasksDir(options.channelDir))).filter((entry) => !entry.frontmatter.archiveOutcome);
468
409
  const governed = entries.filter((entry) => entry.frontmatter.control);
469
410
  const totals = governed.reduce((total, entry) => {
470
411
  const usage = entry.frontmatter.control.usage;
@@ -545,21 +486,16 @@ async function doctor(options) {
545
486
  continue;
546
487
  }
547
488
  const control = entry.frontmatter.control;
489
+ if (!control && entry.frontmatter.enabled === false) {
490
+ issues.push(issue(`tasks/${entry.id}.md is disabled but has no v2 control.stop receipt.`, `Use task_manage set to repair control metadata, then /tasks resume ${entry.id} when it is safe to continue.`));
491
+ }
548
492
  if (control) {
549
493
  const storedTask = await readStoredTask(options.channelDir, entry.id);
550
- const violation = taskBudgetViolation(control, now);
494
+ const violation = taskBudgetViolation(control, now, status);
551
495
  if (violation) {
552
496
  issues.push(issue(`tasks/${entry.id}.md exceeds its control limit: ${violation}.`, `Review the task, then explicitly raise its budget/deadline or cancel it; the driver will escalate it.`));
553
497
  }
554
- if (control.sideEffects === "external" && control.externalApproval === "required") {
555
- issues.push(issue(`tasks/${entry.id}.md requires external side effects but has no user approval.`, `After reviewing the proposed action, a user must run /tasks approve ${entry.id}.`));
556
- }
557
- if (control.externalApproval === "granted" &&
558
- storedTask &&
559
- control.approvalBodyHash !== taskBodyHash(storedTask.body)) {
560
- issues.push(issue(`tasks/${entry.id}.md changed after external-action approval was granted.`, `Review the current action and run /tasks approve ${entry.id} again.`));
561
- }
562
- if (status !== "done" && control.verification.status === "passed" && control.verification.bodyHash) {
498
+ if (status !== "sleeping" && control.verification.status === "passed" && control.verification.bodyHash) {
563
499
  if (storedTask && taskBodyHash(storedTask.body) !== control.verification.bodyHash) {
564
500
  issues.push(issue(`tasks/${entry.id}.md changed after its recorded independent PASS.`, `Run a fresh purpose=verify sub-agent and import its attestation before completion.`));
565
501
  }
@@ -574,10 +510,48 @@ async function doctor(options) {
574
510
  }
575
511
  }
576
512
  }
513
+ if (entry.frontmatter.enabled === false && !control.stop) {
514
+ issues.push(issue(`tasks/${entry.id}.md is disabled without a control.stop receipt.`, `Use /tasks resume ${entry.id} after deciding who stopped it, or write a valid stop record with task_manage set.`));
515
+ }
516
+ if (entry.frontmatter.enabled !== false && control.stop) {
517
+ issues.push(issue(`tasks/${entry.id}.md has a stop receipt but enabled is true.`, `Run /tasks resume ${entry.id} to clear the stale stop receipt, or disable the task explicitly.`));
518
+ }
577
519
  }
578
520
  const recurring = Boolean(entry.frontmatter.schedule);
579
- if (status === "done" && !recurring) {
580
- issues.push(issue(`tasks/${entry.id}.md is done but still in the active directory.`, `Archive one-shot task ${entry.id}, or add a schedule cron with task_manage set if it is recurring.`));
521
+ if (status === "sleeping" && !recurring) {
522
+ issues.push(issue(`tasks/${entry.id}.md is sleeping without a recurring schedule.`, `Use task_manage complete/cancel for a one-shot task, or add a valid schedule before sleeping it.`));
523
+ }
524
+ if (recurring) {
525
+ try {
526
+ validateTaskSchedule(entry.frontmatter.schedule);
527
+ }
528
+ catch (error) {
529
+ issues.push(issue(`tasks/${entry.id}.md has an invalid schedule: ${errorMessage(error)}`, `Repair or clear schedule for ${entry.id}; the driver will keep this task disabled until repaired.`));
530
+ }
531
+ if (status === "sleeping" && !entry.frontmatter.wake) {
532
+ issues.push(issue(`tasks/${entry.id}.md is sleeping but has no wake.`, `Repair the schedule and wake, then run /tasks resume ${entry.id} after review.`));
533
+ }
534
+ }
535
+ if (status === "active" &&
536
+ entry.frontmatter.wake &&
537
+ validWakeMs(entry) !== undefined &&
538
+ validWakeMs(entry) > now) {
539
+ issues.push(issue(`tasks/${entry.id}.md is active but its wake is in the future.`, `Use task_manage set/progress to make it waiting with waitingFor=time, or clear wake to continue now.`));
540
+ }
541
+ if (status === "waiting" && entry.frontmatter.wake && !control?.waitingFor) {
542
+ issues.push(issue(`tasks/${entry.id}.md is waiting on a timed wake but has no waitingFor marker.`, `Run task_manage set with control.waitingFor=time or progress the task to normalize the wait.`));
543
+ }
544
+ if (status === "waiting" &&
545
+ entry.frontmatter.wake &&
546
+ control?.waitingFor &&
547
+ !["time", "external-signal"].includes(control.waitingFor)) {
548
+ issues.push(issue(`tasks/${entry.id}.md is waiting on a wake but waitingFor=${control.waitingFor} is not a timed source.`, `Set control.waitingFor to time, or clear wake and record the real signal source before resuming ${entry.id}.`));
549
+ }
550
+ if (status === "waiting" && !entry.frontmatter.wake && control?.waitingFor === "time") {
551
+ issues.push(issue(`tasks/${entry.id}.md is parked but waitingFor=time has no wake.`, `Set a valid wake or change waitingFor to the actual recovery source.`));
552
+ }
553
+ if (recurringTaskMissedOccurrence({ status, schedule: entry.frontmatter.schedule, control }, new Date(now))) {
554
+ issues.push(issue(`tasks/${entry.id}.md has an open ${status} cycle past its next recurring occurrence; no concurrent cycle was opened.`, `Finish, skip, or cancel the current cycle for ${entry.id}; then let the driver compute the next occurrence.`));
581
555
  }
582
556
  const content = await readActiveTaskContent(options.channelDir, entry.id);
583
557
  if (content === undefined) {
@@ -588,13 +562,28 @@ async function doctor(options) {
588
562
  if (missing.length > 0) {
589
563
  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.`));
590
564
  }
565
+ // spec 037, D4: two deterministic, zero-LLM-cost drift checks between a Plan and its
566
+ // DoD — the first real consumer of "is the plan still pointed at the goal?".
567
+ if (entry.plan) {
568
+ const dodCount = countTaskDodItems(content);
569
+ const invalidRefs = entry.plan.steps.flatMap((step) => step.dodRefs.filter((ref) => ref < 1 || ref > dodCount).map((ref) => `${step.id}→dod:${ref}`));
570
+ if (invalidRefs.length > 0) {
571
+ issues.push(issue(`tasks/${entry.id}.md Plan references DoD item(s) that do not exist: ${invalidRefs.join(", ")}.`, `Fix the "→ dod:N" reference(s) in the Plan, or renumber them if the DoD list changed.`));
572
+ }
573
+ const covered = new Set(entry.plan.steps.filter((step) => step.status !== "dropped").flatMap((step) => step.dodRefs));
574
+ const uncovered = Array.from({ length: dodCount }, (_, index) => index + 1).filter((dodIndex) => !covered.has(dodIndex));
575
+ if (dodCount > 0 && uncovered.length > 0) {
576
+ issues.push(issue(`tasks/${entry.id}.md has DoD item(s) with no Plan step covering them: dod:${uncovered.join(",")}.`, `Add or update a Plan step's "→ dod:${uncovered[0]}" reference, or confirm those DoD items need no dedicated step.`));
577
+ }
578
+ }
591
579
  }
592
580
  // A parked task is waiting for someone to call it: a finished background job, a user
593
581
  // message, or `/tasks run`. The driver deliberately will not (see `isTaskParked`), so with
594
582
  // no running job carrying this id, whether it ever resumes is entirely up to the user.
595
583
  // That is legitimate when it is waiting on an answer — and indistinguishable, on disk,
596
584
  // from a task everyone has forgotten. Report the fact and name every way out.
597
- if (isTaskParked(entry.frontmatter) && !runningJobTaskIds.has(entry.id)) {
585
+ const hasDurableWaitingSource = control?.waitingFor === "verification" || (control?.waitingFor === "job" && runningJobTaskIds.has(entry.id));
586
+ if (isTaskParked(entry.frontmatter) && !hasDurableWaitingSource) {
598
587
  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 <local time or +2h>; cancel it if what it waits for is gone.`));
599
588
  }
600
589
  if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
@@ -677,8 +666,6 @@ async function dispatchTasksCommand(options, command) {
677
666
  return await showTask(options.channelDir, command.id);
678
667
  case "archive":
679
668
  return await listArchive(options.channelDir);
680
- case "approve":
681
- return await approveTask(options, command.id);
682
669
  case "pause":
683
670
  return await pauseTask(options, command.id);
684
671
  case "resume":
@@ -18,9 +18,14 @@ export interface TaskDriverOptions {
18
18
  isEnabled?: () => boolean;
19
19
  /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
20
20
  intervalMs?: number;
21
+ /** Direct, non-LLM receipt for deterministic governor stops. */
22
+ notify?: (event: DingTalkEvent) => boolean | Promise<boolean>;
21
23
  }
22
24
  export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
23
25
  export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number, attemptGeneration?: number): DingTalkEvent;
26
+ /** Durable checker wake created by request-verification; it is a normal main-agent turn. */
27
+ export declare function createTaskVerificationEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
28
+ export declare function taskGovernorReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): DingTalkEvent;
24
29
  /**
25
30
  * Native, token-gated driver for the persistent task ledger.
26
31
  *