@oyasmi/pipiclaw 0.7.7 → 0.8.1

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 (114) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/channel-runner.d.ts +4 -4
  3. package/dist/agent/channel-runner.js +25 -23
  4. package/dist/agent/commands.js +7 -2
  5. package/dist/agent/job-manager.d.ts +5 -5
  6. package/dist/agent/prompt-builder.d.ts +3 -13
  7. package/dist/agent/prompt-builder.js +49 -159
  8. package/dist/agent/run-queue.js +2 -1
  9. package/dist/agent/runner-factory.d.ts +1 -2
  10. package/dist/agent/runner-factory.js +2 -2
  11. package/dist/agent/status-render.d.ts +0 -7
  12. package/dist/agent/status-render.js +8 -3
  13. package/dist/agent/types.d.ts +2 -0
  14. package/dist/agent/workspace-resources.d.ts +1 -1
  15. package/dist/agent/workspace-resources.js +3 -15
  16. package/dist/executor.d.ts +20 -0
  17. package/dist/{sandbox.js → executor.js} +3 -95
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/log.d.ts +1 -1
  21. package/dist/log.js +1 -2
  22. package/dist/memory/files.js +0 -0
  23. package/dist/memory/lifecycle.js +6 -5
  24. package/dist/memory/maintenance-jobs.d.ts +0 -1
  25. package/dist/memory/maintenance-jobs.js +2 -2
  26. package/dist/memory/maintenance-state.js +2 -1
  27. package/dist/memory/post-turn-review.d.ts +0 -1
  28. package/dist/memory/post-turn-review.js +4 -4
  29. package/dist/memory/scheduler.d.ts +0 -1
  30. package/dist/memory/scheduler.js +2 -2
  31. package/dist/memory/session.js +2 -2
  32. package/dist/memory/task-digest.js +17 -0
  33. package/dist/paths.d.ts +2 -0
  34. package/dist/paths.js +11 -0
  35. package/dist/playbooks/catalog.d.ts +9 -0
  36. package/dist/playbooks/catalog.js +44 -0
  37. package/dist/playbooks/event-scheduling.md +43 -0
  38. package/dist/playbooks/memory-and-learning.md +45 -0
  39. package/dist/playbooks/runtime-orientation.md +48 -0
  40. package/dist/playbooks/task-closeout.md +45 -0
  41. package/dist/playbooks/task-delegation.md +44 -0
  42. package/dist/playbooks/task-driving.md +43 -0
  43. package/dist/playbooks/task-planning.md +47 -0
  44. package/dist/playbooks/task-recurring.md +42 -0
  45. package/dist/playbooks/task-repair.md +43 -0
  46. package/dist/runtime/bootstrap.d.ts +12 -11
  47. package/dist/runtime/bootstrap.js +81 -57
  48. package/dist/runtime/delivery.js +4 -3
  49. package/dist/runtime/dingtalk.d.ts +2 -0
  50. package/dist/runtime/dingtalk.js +15 -14
  51. package/dist/runtime/durable-dispatch.d.ts +30 -0
  52. package/dist/runtime/durable-dispatch.js +172 -0
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +5 -3
  55. package/dist/runtime/events.js +17 -13
  56. package/dist/runtime/task-commands.d.ts +6 -0
  57. package/dist/runtime/task-commands.js +292 -6
  58. package/dist/runtime/task-driver.d.ts +32 -0
  59. package/dist/runtime/task-driver.js +268 -0
  60. package/dist/security/config.js +2 -1
  61. package/dist/security/network.js +9 -2
  62. package/dist/security/path-guard.js +12 -24
  63. package/dist/security/types.d.ts +0 -1
  64. package/dist/settings.d.ts +12 -0
  65. package/dist/settings.js +30 -0
  66. package/dist/shared/jsonl-appender.js +2 -1
  67. package/dist/shared/task-ledger.d.ts +35 -0
  68. package/dist/shared/task-ledger.js +229 -15
  69. package/dist/shared/text-utils.d.ts +1 -0
  70. package/dist/shared/text-utils.js +3 -0
  71. package/dist/subagents/discovery.js +3 -2
  72. package/dist/subagents/tool.d.ts +15 -3
  73. package/dist/subagents/tool.js +194 -17
  74. package/dist/tasks/artifact-subject.d.ts +6 -0
  75. package/dist/tasks/artifact-subject.js +29 -0
  76. package/dist/tasks/control.d.ts +83 -0
  77. package/dist/tasks/control.js +293 -0
  78. package/dist/tasks/store.d.ts +32 -0
  79. package/dist/tasks/store.js +142 -0
  80. package/dist/tasks/verification.d.ts +23 -0
  81. package/dist/tasks/verification.js +69 -0
  82. package/dist/tools/bash.d.ts +1 -1
  83. package/dist/tools/bash.js +3 -5
  84. package/dist/tools/command-optimizer.d.ts +1 -1
  85. package/dist/tools/command-optimizer.js +4 -6
  86. package/dist/tools/config.js +4 -3
  87. package/dist/tools/edit.d.ts +1 -1
  88. package/dist/tools/edit.js +0 -0
  89. package/dist/tools/event-manage.d.ts +0 -1
  90. package/dist/tools/event-manage.js +9 -14
  91. package/dist/tools/grep.d.ts +1 -1
  92. package/dist/tools/grep.js +4 -6
  93. package/dist/tools/index.d.ts +1 -3
  94. package/dist/tools/index.js +1 -4
  95. package/dist/tools/read.d.ts +1 -1
  96. package/dist/tools/read.js +1 -2
  97. package/dist/tools/registry.d.ts +2 -3
  98. package/dist/tools/registry.js +5 -11
  99. package/dist/tools/skill-manage.d.ts +0 -1
  100. package/dist/tools/skill-manage.js +7 -14
  101. package/dist/tools/task-manage.d.ts +37 -4
  102. package/dist/tools/task-manage.js +398 -39
  103. package/dist/tools/write-content.d.ts +1 -1
  104. package/dist/tools/write-content.js +0 -1
  105. package/dist/tools/write.d.ts +1 -1
  106. package/dist/tui/app.d.ts +0 -2
  107. package/dist/tui/app.js +12 -7
  108. package/dist/tui/cli.d.ts +0 -2
  109. package/dist/tui/cli.js +3 -25
  110. package/dist/tui/turn-controller.d.ts +7 -3
  111. package/dist/tui/turn-controller.js +9 -6
  112. package/dist/web/client.js +2 -1
  113. package/package.json +2 -2
  114. package/dist/sandbox.d.ts +0 -42
@@ -3,6 +3,9 @@ import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { isTaskCheckinEvent, isTaskScheduleEvent, parseTaskEventName, taskEventPrefix, taskScheduleEventName, } from "../shared/task-events.js";
5
5
  import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
7
+ import { taskBudgetViolation } from "../tasks/control.js";
8
+ import { claimTaskAttempt, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
6
9
  import { parseScheduledEventContent } from "./events.js";
7
10
  function usage() {
8
11
  return `# Tasks
@@ -12,6 +15,11 @@ Usage:
12
15
  - \`/tasks\` — list active tasks in this channel
13
16
  - \`/tasks show <id>\` — show a single task file (active or archived)
14
17
  - \`/tasks archive\` — list archived (closed) tasks
18
+ - \`/tasks approve <id>\` — explicitly approve this task's external side effects
19
+ - \`/tasks pause <id>\` — stop automatic wake-ups for a task
20
+ - \`/tasks resume <id>\` — make a paused task eligible for the next driver scan
21
+ - \`/tasks run <id>\` — resume and immediately enqueue one task attempt when the runtime is available
22
+ - \`/tasks stats [id]\` — show task-level attempt, token, cost, and verification outcomes
15
23
  - \`/tasks doctor\` — check task/event consistency without changing files`;
16
24
  }
17
25
  function parseTasksCommand(args) {
@@ -38,6 +46,30 @@ function parseTasksCommand(args) {
38
46
  throw new Error("Usage: /tasks doctor");
39
47
  return { action: "doctor" };
40
48
  }
49
+ if (action === "approve") {
50
+ const id = parts[1];
51
+ if (!id || parts.length > 2)
52
+ throw new Error("Usage: /tasks approve <id>");
53
+ return { action: "approve", id };
54
+ }
55
+ if (action === "pause" || action === "resume") {
56
+ const id = parts[1];
57
+ if (!id || parts.length > 2)
58
+ throw new Error(`Usage: /tasks ${action} <id>`);
59
+ return { action, id };
60
+ }
61
+ if (action === "run") {
62
+ const id = parts[1];
63
+ if (!id || parts.length > 2)
64
+ throw new Error("Usage: /tasks run <id>");
65
+ return { action: "run", id };
66
+ }
67
+ if (action === "stats") {
68
+ const id = parts[1];
69
+ if (parts.length > 2)
70
+ throw new Error("Usage: /tasks stats [id]");
71
+ return { action: "stats", id };
72
+ }
41
73
  throw new Error(`Unknown /tasks action: ${action}`);
42
74
  }
43
75
  function tasksDir(channelDir) {
@@ -94,7 +126,7 @@ async function readTaskEvents(workspaceDir, channelId) {
94
126
  info.event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
95
127
  }
96
128
  catch (error) {
97
- info.error = error instanceof Error ? error.message : String(error);
129
+ info.error = errorMessage(error);
98
130
  }
99
131
  events.push(info);
100
132
  }
@@ -117,6 +149,35 @@ function validWakeMs(entry) {
117
149
  function issue(problem, nextStep) {
118
150
  return `- ${problem}\n Next step: ${nextStep}`;
119
151
  }
152
+ function relationCycles(graph) {
153
+ const visited = new Set();
154
+ const active = new Set();
155
+ const stack = [];
156
+ const cycles = new Map();
157
+ const visit = (id) => {
158
+ if (active.has(id)) {
159
+ const start = stack.indexOf(id);
160
+ const cycle = [...stack.slice(start), id];
161
+ const key = [...new Set(cycle)].sort().join("\0");
162
+ cycles.set(key, cycle);
163
+ return;
164
+ }
165
+ if (visited.has(id))
166
+ return;
167
+ visited.add(id);
168
+ active.add(id);
169
+ stack.push(id);
170
+ for (const next of graph.get(id) ?? []) {
171
+ if (graph.has(next))
172
+ visit(next);
173
+ }
174
+ stack.pop();
175
+ active.delete(id);
176
+ };
177
+ for (const id of graph.keys())
178
+ visit(id);
179
+ return Array.from(cycles.values());
180
+ }
120
181
  async function readActiveTaskContent(channelDir, id) {
121
182
  try {
122
183
  return await readFile(join(tasksDir(channelDir), `${id}.md`), "utf-8");
@@ -135,12 +196,178 @@ async function listTasks(channelDir) {
135
196
  const blocks = entries.map((entry) => {
136
197
  const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
137
198
  const detail = [` status: ${status}`, `wake: ${relativeWake(entry.wakeMs, now)}`];
199
+ const control = entry.frontmatter.control;
200
+ if (control) {
201
+ detail.push(`priority: ${control.priority}`);
202
+ detail.push(`attempts: ${control.usage.attempts}/${control.budget.maxAttempts}`);
203
+ detail.push(`verify: ${control.verification.mode}/${control.verification.status}`);
204
+ if (control.isolation !== "shared")
205
+ detail.push(`isolation: ${control.isolation}`);
206
+ if (control.sideEffects !== "workspace") {
207
+ detail.push(`effects: ${control.sideEffects}/${control.externalApproval}`);
208
+ }
209
+ if (control.deadline)
210
+ detail.push(`deadline: ${control.deadline}`);
211
+ if (control.parent)
212
+ detail.push(`parent: ${control.parent}`);
213
+ if (control.dependsOn.length > 0)
214
+ detail.push(`depends: ${control.dependsOn.join(",")}`);
215
+ if (control.nextAction)
216
+ detail.push(`next: ${control.nextAction}`);
217
+ if (control.worktree?.branch)
218
+ detail.push(`branch: ${control.worktree.branch}`);
219
+ }
138
220
  if (entry.frontmatter.recurrence)
139
221
  detail.push(`recurrence: ${entry.frontmatter.recurrence}`);
140
222
  return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
141
223
  });
142
224
  return `# Tasks: ${entries.length} active\n\n${blocks.join("\n")}`;
143
225
  }
226
+ async function approveTask(options, idInput) {
227
+ const id = normalizeTaskId(idInput);
228
+ const task = await readStoredTask(options.channelDir, id);
229
+ if (!task)
230
+ return `Task not found: ${id}`;
231
+ const control = task.fields.control;
232
+ if (!control)
233
+ return `Task ${id} has no governed control metadata. Ask the agent to normalize it before approval.`;
234
+ if (task.fields.status === "done" || task.fields.status === "cancelled" || task.fields.status === "escalated") {
235
+ return `Task ${id} is ${task.fields.status} and cannot receive a new external-action approval.`;
236
+ }
237
+ if (control.sideEffects !== "external") {
238
+ return `Task ${id} is not marked for external side effects; no approval is required.`;
239
+ }
240
+ if (control.externalApproval === "granted") {
241
+ return `Task ${id} was already approved by ${control.approvalBy ?? "a user"} at ${control.approvedAt ?? "an unknown time"}.`;
242
+ }
243
+ control.externalApproval = "granted";
244
+ control.approvalBy = options.approver?.trim() || "unknown-user";
245
+ control.approvedAt = new Date().toISOString();
246
+ control.approvalBodyHash = taskBodyHash(task.body);
247
+ await writeStoredTask(task);
248
+ return `Approved external side effects for task ${id}. Approval is recorded for ${control.approvalBy}.`;
249
+ }
250
+ export async function pauseTask(options, idInput) {
251
+ const id = normalizeTaskId(idInput);
252
+ const task = await readStoredTask(options.channelDir, id);
253
+ if (!task)
254
+ return `Task not found: ${id}`;
255
+ if (["done", "cancelled", "escalated"].includes(task.fields.status)) {
256
+ return `Task ${id} is ${task.fields.status} and cannot be paused.`;
257
+ }
258
+ if (task.fields.status === "paused")
259
+ return `Task ${id} is already paused.`;
260
+ task.fields.status = "paused";
261
+ task.fields.wake = undefined;
262
+ if (task.fields.control) {
263
+ task.fields.control.lastOutcome = "blocked";
264
+ task.fields.control.blockedReason = `Paused by ${options.approver?.trim() || "a user"}.`;
265
+ }
266
+ await writeStoredTask(task);
267
+ return `Paused task ${id}. Use /tasks resume ${id} when it should continue.`;
268
+ }
269
+ export async function resumeTask(options, idInput) {
270
+ const id = normalizeTaskId(idInput);
271
+ const task = await readStoredTask(options.channelDir, id);
272
+ if (!task)
273
+ return `Task not found: ${id}`;
274
+ if (task.fields.status !== "paused")
275
+ return `Task ${id} is ${task.fields.status}, not paused.`;
276
+ task.fields.status = "in-progress";
277
+ task.fields.wake = undefined;
278
+ if (task.fields.control) {
279
+ task.fields.control.lastOutcome = "pending";
280
+ task.fields.control.blockedReason = undefined;
281
+ }
282
+ await writeStoredTask(task);
283
+ return `Resumed task ${id}; the task driver will pick it up on its next scan.`;
284
+ }
285
+ async function runTask(options, idInput) {
286
+ const id = normalizeTaskId(idInput);
287
+ const task = await readStoredTask(options.channelDir, id);
288
+ if (!task)
289
+ return `Task not found: ${id}`;
290
+ if (["done", "cancelled", "escalated"].includes(task.fields.status)) {
291
+ return `Task ${id} is ${task.fields.status} and cannot be run.`;
292
+ }
293
+ if (task.fields.status === "paused")
294
+ task.fields.status = "in-progress";
295
+ task.fields.wake = undefined;
296
+ if (task.fields.control) {
297
+ task.fields.control.lastOutcome = "pending";
298
+ task.fields.control.blockedReason = undefined;
299
+ }
300
+ await writeStoredTask(task);
301
+ const now = new Date();
302
+ const claim = task.fields.control ? await claimTaskAttempt(options.channelDir, id, now) : undefined;
303
+ const enqueued = await options.dispatchTask?.(id);
304
+ if (!enqueued && claim)
305
+ await releaseTaskAttemptClaim(options.channelDir, id, claim, now);
306
+ return enqueued
307
+ ? `Enqueued task ${id} for an immediate attempt.`
308
+ : `Task ${id} is ready. Start or use the DingTalk daemon for automatic dispatch, or send a normal prompt in this session to advance it.`;
309
+ }
310
+ function renderUsageLine(entry) {
311
+ const control = entry.frontmatter.control;
312
+ if (!control)
313
+ return `- ${entry.id}: legacy task (no governed usage recorded)`;
314
+ const verification = control.verification;
315
+ return [
316
+ `- ${entry.id} — ${entry.title}`,
317
+ ` attempts: ${control.usage.attempts}/${control.budget.maxAttempts}`,
318
+ ` tokens: ${control.usage.tokens}`,
319
+ ` cost: $${control.usage.costUsd.toFixed(4)}`,
320
+ ` wall time: ${control.usage.wallTimeMinutes.toFixed(1)}m`,
321
+ ` last outcome: ${control.lastOutcome}`,
322
+ ` verification: ${verification.mode}/${verification.status}`,
323
+ ].join("\n");
324
+ }
325
+ async function taskStats(options, idInput) {
326
+ if (idInput) {
327
+ const id = normalizeTaskId(idInput);
328
+ const task = await readStoredTask(options.channelDir, id, true, true);
329
+ if (!task)
330
+ return `Task not found: ${id}`;
331
+ const entry = {
332
+ id,
333
+ title: extractTaskTitle(task.body, id),
334
+ frontmatter: {
335
+ readable: true,
336
+ status: task.fields.status,
337
+ wake: task.fields.wake,
338
+ recurrence: task.fields.recurrence,
339
+ control: task.fields.control,
340
+ },
341
+ actionable: false,
342
+ };
343
+ return `# Task Stats\n\n${renderUsageLine(entry)}`;
344
+ }
345
+ const entries = await readActiveTasks(tasksDir(options.channelDir));
346
+ const governed = entries.filter((entry) => entry.frontmatter.control);
347
+ const totals = governed.reduce((total, entry) => {
348
+ const usage = entry.frontmatter.control.usage;
349
+ total.attempts += usage.attempts;
350
+ total.tokens += usage.tokens;
351
+ total.costUsd += usage.costUsd;
352
+ total.wallTimeMinutes += usage.wallTimeMinutes;
353
+ return total;
354
+ }, { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 });
355
+ const verified = governed.filter((entry) => entry.frontmatter.control?.verification.status === "passed").length;
356
+ const stalled = governed.filter((entry) => entry.frontmatter.control?.lastOutcome === "failed").length;
357
+ return [
358
+ "# Task Stats",
359
+ "",
360
+ `governed tasks: ${governed.length}/${entries.length}`,
361
+ `attempts: ${totals.attempts}`,
362
+ `tokens: ${totals.tokens}`,
363
+ `cost: $${totals.costUsd.toFixed(4)}`,
364
+ `wall time: ${totals.wallTimeMinutes.toFixed(1)}m`,
365
+ `verification PASS: ${verified}`,
366
+ `last-run failures: ${stalled}`,
367
+ "",
368
+ ...governed.map(renderUsageLine),
369
+ ].join("\n");
370
+ }
144
371
  async function showTask(channelDir, id) {
145
372
  const dir = tasksDir(channelDir);
146
373
  const taskId = normalizeTaskId(id);
@@ -192,6 +419,39 @@ async function doctor(options) {
192
419
  issues.push(issue(`tasks/${entry.id}.md has unreadable frontmatter; wake/status cannot be trusted.`, `Fix tasks/${entry.id}.md so it starts with readable status/wake/recurrence frontmatter.`));
193
420
  continue;
194
421
  }
422
+ if (entry.frontmatter.controlReadable === false) {
423
+ issues.push(issue(`tasks/${entry.id}.md has invalid control metadata; governance is fail-open but cannot be enforced.`, `Use task_manage set or repair the one-line control JSON before allowing the task to run.`));
424
+ continue;
425
+ }
426
+ const control = entry.frontmatter.control;
427
+ if (control) {
428
+ const storedTask = await readStoredTask(options.channelDir, entry.id);
429
+ const violation = taskBudgetViolation(control, now);
430
+ if (violation) {
431
+ 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.`));
432
+ }
433
+ for (const relatedId of [control.parent, ...control.dependsOn].filter((value) => Boolean(value))) {
434
+ if (!activeIds.has(relatedId) && !archivedIds.has(relatedId)) {
435
+ issues.push(issue(`tasks/${entry.id}.md points to missing related task ${relatedId}.`, `Create ${relatedId}, or remove it from parent/dependsOn with task_manage set.`));
436
+ }
437
+ }
438
+ if (control.sideEffects === "external" && control.externalApproval !== "granted") {
439
+ 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}.`));
440
+ }
441
+ if (control.externalApproval === "granted" &&
442
+ storedTask &&
443
+ control.approvalBodyHash !== taskBodyHash(storedTask.body)) {
444
+ 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.`));
445
+ }
446
+ if (control.worktree && !existsSync(control.worktree.path)) {
447
+ issues.push(issue(`tasks/${entry.id}.md records a missing worktree path: ${control.worktree.path}.`, `Clear the stale worktree metadata or create/reassign an isolated worktree.`));
448
+ }
449
+ if (status !== "done" && control.verification.status === "passed" && control.verification.bodyHash) {
450
+ if (storedTask && taskBodyHash(storedTask.body) !== control.verification.bodyHash) {
451
+ 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.`));
452
+ }
453
+ }
454
+ }
195
455
  if (status === "done" && !isParseableSchedule(events, entry.id)) {
196
456
  issues.push(issue(`tasks/${entry.id}.md is done but still in the active directory.`, `Ask the agent to archive one-shot task ${entry.id}, or add a parseable .schedule event if it is recurring.`));
197
457
  }
@@ -208,8 +468,12 @@ async function doctor(options) {
208
468
  if (entry.frontmatter.recurrence && !isParseableSchedule(events, entry.id)) {
209
469
  issues.push(issue(`tasks/${entry.id}.md has recurrence but no parseable ${taskScheduleEventName(options.channelId, entry.id)} event.`, `Create or repair events/${taskScheduleEventName(options.channelId, entry.id)}.json as a periodic event.`));
210
470
  }
471
+ if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
472
+ 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.`));
473
+ }
211
474
  const checkin = eventKey(events, entry.id, "checkin");
212
475
  if (checkin && isTaskCheckinEvent(checkin)) {
476
+ issues.push(issue(`events/${checkin.filename} is a legacy task checkin; native wake handling makes it redundant.`, `Delete events/${checkin.filename} and keep the task wake value as the single resume condition.`));
213
477
  const wakeMs = validWakeMs(entry);
214
478
  const atMs = new Date(checkin.event.at).getTime();
215
479
  if (wakeMs === undefined) {
@@ -219,9 +483,21 @@ async function doctor(options) {
219
483
  issues.push(issue(`tasks/${entry.id}.md wake does not match its .checkin event time.`, `Sync tasks/${entry.id}.md wake with events/${checkin.filename} at ${checkin.event.at}.`));
220
484
  }
221
485
  }
222
- else if (status === "awaiting-user" && validWakeMs(entry) !== undefined) {
223
- issues.push(issue(`tasks/${entry.id}.md is awaiting-user with wake set but has no parseable .checkin event.`, `Create task.${options.channelId}.${entry.id}.checkin as a one-shot event for the wake time, or clear wake.`));
224
- }
486
+ }
487
+ const parentGraph = new Map();
488
+ const dependencyGraph = new Map();
489
+ for (const entry of entries) {
490
+ const control = entry.frontmatter.control;
491
+ if (!control)
492
+ continue;
493
+ parentGraph.set(entry.id, control.parent ? [control.parent] : []);
494
+ dependencyGraph.set(entry.id, control.dependsOn);
495
+ }
496
+ for (const cycle of relationCycles(parentGraph)) {
497
+ issues.push(issue(`Task parent cycle detected: ${cycle.join(" → ")}.`, `Use task_manage set to clear or correct one parent link in this cycle.`));
498
+ }
499
+ for (const cycle of relationCycles(dependencyGraph)) {
500
+ issues.push(issue(`Task dependency cycle detected: ${cycle.join(" → ")}.`, `Use task_manage set to remove one dependsOn edge before the driver can continue these tasks.`));
225
501
  }
226
502
  for (const event of events) {
227
503
  if (!event.id || !event.use) {
@@ -257,7 +533,7 @@ export async function handleTasksCommand(options) {
257
533
  command = parseTasksCommand(options.args);
258
534
  }
259
535
  catch (error) {
260
- const message = error instanceof Error ? error.message : String(error);
536
+ const message = errorMessage(error);
261
537
  return `${message}\n\n${usage()}`;
262
538
  }
263
539
  try {
@@ -268,12 +544,22 @@ export async function handleTasksCommand(options) {
268
544
  return await showTask(options.channelDir, command.id);
269
545
  case "archive":
270
546
  return await listArchive(options.channelDir);
547
+ case "approve":
548
+ return await approveTask(options, command.id);
549
+ case "pause":
550
+ return await pauseTask(options, command.id);
551
+ case "resume":
552
+ return await resumeTask(options, command.id);
553
+ case "run":
554
+ return await runTask(options, command.id);
555
+ case "stats":
556
+ return await taskStats(options, command.id);
271
557
  case "doctor":
272
558
  return await doctor(options);
273
559
  }
274
560
  }
275
561
  catch (error) {
276
- const message = error instanceof Error ? error.message : String(error);
562
+ const message = errorMessage(error);
277
563
  return `Could not ${command.action} tasks: ${message}`;
278
564
  }
279
565
  }
@@ -0,0 +1,32 @@
1
+ import type { PipiclawTaskDriverSettings } from "../settings.js";
2
+ import { type TaskLedgerEntry } from "../shared/task-ledger.js";
3
+ import type { DingTalkEvent } from "./dingtalk.js";
4
+ export interface TaskDriverOptions {
5
+ workspaceDir: string;
6
+ getKnownChannelIds?: () => Iterable<string>;
7
+ isChannelActive: (channelId: string) => boolean;
8
+ dispatch: (event: DingTalkEvent) => boolean | Promise<boolean>;
9
+ getSettings: () => PipiclawTaskDriverSettings;
10
+ intervalMs?: number;
11
+ }
12
+ export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
13
+ export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
14
+ /**
15
+ * Native, token-gated driver for the persistent task ledger.
16
+ *
17
+ * The scan itself is deterministic and cheap. It wakes at most one actionable task
18
+ * per channel, skips active channels, backs off unchanged ledgers, and round-robins
19
+ * dispatches so a busy channel cannot starve the rest. `wake` is therefore sufficient
20
+ * to resume a task; users do not need to install a heartbeat event or sensor script.
21
+ */
22
+ export declare class TaskDriver {
23
+ private readonly options;
24
+ private timer;
25
+ private running;
26
+ private nextChannelIndex;
27
+ private readonly attempts;
28
+ constructor(options: TaskDriverOptions);
29
+ start(): void;
30
+ stop(): void;
31
+ runOnce(now?: Date): Promise<void>;
32
+ }