@oyasmi/pipiclaw 0.8.10-beta.2 → 0.8.10-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 (43) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +46 -13
  3. package/dist/agent/commands.js +30 -28
  4. package/dist/agent/effect-ledger.d.ts +13 -4
  5. package/dist/agent/effect-ledger.js +18 -5
  6. package/dist/agent/job-manager.d.ts +9 -0
  7. package/dist/agent/job-manager.js +45 -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/executor.d.ts +2 -0
  12. package/dist/executor.js +1 -0
  13. package/dist/memory/maintenance-gates.d.ts +24 -10
  14. package/dist/memory/maintenance-gates.js +11 -9
  15. package/dist/memory/maintenance-jobs.d.ts +3 -2
  16. package/dist/memory/maintenance-jobs.js +33 -21
  17. package/dist/memory/scheduler.d.ts +7 -2
  18. package/dist/playbooks/task-closeout.md +2 -0
  19. package/dist/playbooks/task-delegation.md +12 -8
  20. package/dist/playbooks/task-driving.md +2 -2
  21. package/dist/playbooks/task-planning.md +1 -1
  22. package/dist/runtime/bootstrap.js +7 -4
  23. package/dist/runtime/delivery.js +31 -6
  24. package/dist/runtime/dingtalk.d.ts +9 -1
  25. package/dist/runtime/dingtalk.js +7 -4
  26. package/dist/runtime/task-commands.js +130 -53
  27. package/dist/runtime/task-driver.js +38 -9
  28. package/dist/shared/task-ledger.js +19 -3
  29. package/dist/subagents/tool.d.ts +1 -0
  30. package/dist/subagents/tool.js +33 -3
  31. package/dist/tasks/control.d.ts +1 -0
  32. package/dist/tasks/control.js +2 -2
  33. package/dist/tasks/verification.d.ts +8 -0
  34. package/dist/tasks/verification.js +4 -1
  35. package/dist/tools/bash.js +12 -12
  36. package/dist/tools/task-manage/lifecycle.js +6 -3
  37. package/dist/tools/task-manage/verification.d.ts +2 -1
  38. package/dist/tools/task-manage/verification.js +2 -1
  39. package/dist/tui/turn-controller.js +3 -3
  40. package/dist/usage/ledger.d.ts +2 -0
  41. package/dist/usage/ledger.js +7 -2
  42. package/dist/usage/render.js +17 -8
  43. package/package.json +1 -1
@@ -5,75 +5,95 @@ import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
5
5
  import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
6
  import { errorMessage } from "../shared/text-utils.js";
7
7
  import { isRecord } from "../shared/type-guards.js";
8
- import { retiredTaskControlKeys, taskBudgetViolation } from "../tasks/control.js";
8
+ import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys, TASK_PRIORITIES, taskBudgetViolation, } from "../tasks/control.js";
9
9
  import { claimTaskAttempt, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
10
10
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
11
11
  import { readVerificationAttestation } from "../tasks/verification.js";
12
12
  import { parseScheduledEventContent } from "./events.js";
13
+ /**
14
+ * Fields `/tasks set` can edit directly.
15
+ *
16
+ * Deliberately a small, flat set: the ones a user already knows they want to change (when it
17
+ * should wake, what it should do next, how much rope it has). Everything structural — status
18
+ * transitions, verification, approval, side effects — stays with `task_manage`, whose state
19
+ * machine those fields belong to. The value is the rest of the line, so it may contain spaces.
20
+ */
21
+ const SETTABLE_TASK_FIELDS = ["wake", "next", "priority", "attempts", "deadline"];
13
22
  function usage() {
14
- return `# Tasks
23
+ return `# 任务
15
24
 
16
- Usage:
25
+ 用法:
17
26
 
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`;
27
+ - \`/tasks\` — 列出本频道进行中的任务
28
+ - \`/tasks show <id>\` — 查看单个任务文件(进行中或已归档)
29
+ - \`/tasks archive\` — 列出已归档(已关闭)的任务
30
+ - \`/tasks approve <id>\` — 显式批准该任务的外部副作用
31
+ - \`/tasks pause <id>\` — 停止该任务的自动唤醒
32
+ - \`/tasks resume <id>\` — 让暂停的任务在下一轮扫描中恢复
33
+ - \`/tasks run <id>\` — 恢复并立即排入一次执行(需要运行时可用)
34
+ - \`/tasks set <id> <${SETTABLE_TASK_FIELDS.join("|")}> <值>\` — 直接改一个字段,不花一个 LLM 回合
35
+ - \`/tasks stats [id]\` — 查看任务级的尝试次数、token、花费与验收结果
36
+ - \`/tasks doctor\` — 只读检查任务/事件一致性`;
27
37
  }
28
38
  function parseTasksCommand(args) {
29
- const parts = args.trim().split(/\s+/).filter(Boolean);
39
+ const trimmed = args.trim();
40
+ const parts = trimmed.split(/\s+/).filter(Boolean);
30
41
  const action = parts[0];
31
42
  if (!action || action === "list") {
32
43
  if (parts.length > 1)
33
- throw new Error("Usage: /tasks list");
44
+ throw new Error("用法:/tasks list");
34
45
  return { action: "list" };
35
46
  }
36
47
  if (action === "show") {
37
48
  const id = parts[1];
38
49
  if (!id || parts.length > 2)
39
- throw new Error("Usage: /tasks show <id>");
50
+ throw new Error("用法:/tasks show <id>");
40
51
  return { action: "show", id };
41
52
  }
42
53
  if (action === "archive") {
43
54
  if (parts.length > 1)
44
- throw new Error("Usage: /tasks archive");
55
+ throw new Error("用法:/tasks archive");
45
56
  return { action: "archive" };
46
57
  }
47
58
  if (action === "doctor") {
48
59
  if (parts.length > 1)
49
- throw new Error("Usage: /tasks doctor");
60
+ throw new Error("用法:/tasks doctor");
50
61
  return { action: "doctor" };
51
62
  }
52
63
  if (action === "approve") {
53
64
  const id = parts[1];
54
65
  if (!id || parts.length > 2)
55
- throw new Error("Usage: /tasks approve <id>");
66
+ throw new Error("用法:/tasks approve <id>");
56
67
  return { action: "approve", id };
57
68
  }
58
69
  if (action === "pause" || action === "resume") {
59
70
  const id = parts[1];
60
71
  if (!id || parts.length > 2)
61
- throw new Error(`Usage: /tasks ${action} <id>`);
72
+ throw new Error(`用法:/tasks ${action} <id>`);
62
73
  return { action, id };
63
74
  }
64
75
  if (action === "run") {
65
76
  const id = parts[1];
66
77
  if (!id || parts.length > 2)
67
- throw new Error("Usage: /tasks run <id>");
78
+ throw new Error("用法:/tasks run <id>");
68
79
  return { action: "run", id };
69
80
  }
81
+ if (action === "set") {
82
+ // Everything after the field name is the value, verbatim — a nextAction is a sentence.
83
+ const match = /^set\s+(\S+)\s+(\S+)\s*([\s\S]*)$/.exec(trimmed);
84
+ const field = match?.[2];
85
+ if (!match || !field || !SETTABLE_TASK_FIELDS.includes(field)) {
86
+ throw new Error(`用法:/tasks set <id> <${SETTABLE_TASK_FIELDS.join("|")}> <值>`);
87
+ }
88
+ return { action: "set", id: match[1], field: field, value: match[3].trim() };
89
+ }
70
90
  if (action === "stats") {
71
91
  const id = parts[1];
72
92
  if (parts.length > 2)
73
- throw new Error("Usage: /tasks stats [id]");
93
+ throw new Error("用法:/tasks stats [id]");
74
94
  return { action: "stats", id };
75
95
  }
76
- throw new Error(`Unknown /tasks action: ${action}`);
96
+ throw new Error(`未知的 /tasks 动作:${action}`);
77
97
  }
78
98
  function tasksDir(channelDir) {
79
99
  return join(channelDir, "tasks");
@@ -178,7 +198,7 @@ async function listTasks(channelDir) {
178
198
  const now = Date.now();
179
199
  const entries = await readActiveTasks(dir, now);
180
200
  if (entries.length === 0) {
181
- return "# Tasks\n\nNo active tasks.";
201
+ return "# 任务\n\n当前没有进行中的任务。";
182
202
  }
183
203
  const blocks = entries.map((entry) => {
184
204
  const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "⚠ unreadable frontmatter";
@@ -207,40 +227,40 @@ async function listTasks(channelDir) {
207
227
  }
208
228
  return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
209
229
  });
210
- return `# Tasks: ${entries.length} active\n\n${blocks.join("\n")}`;
230
+ return `# 任务:${entries.length} 个进行中\n\n${blocks.join("\n")}`;
211
231
  }
212
232
  async function approveTask(options, idInput) {
213
233
  const id = normalizeTaskId(idInput);
214
234
  const task = await readStoredTask(options.channelDir, id);
215
235
  if (!task)
216
- return `Task not found: ${id}`;
236
+ return `找不到任务:${id}`;
217
237
  const control = task.fields.control;
218
238
  if (!control)
219
- return `Task ${id} has no governed control metadata. Ask the agent to normalize it before approval.`;
239
+ return `任务 ${id} 没有受治理的 control 元数据,先让 agent 规范化后再审批。`;
220
240
  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.`;
241
+ return `任务 ${id} 已是 ${task.fields.status},不能再授予外部动作审批。`;
222
242
  }
223
243
  if (control.sideEffects !== "external") {
224
- return `Task ${id} is not marked for external side effects; no approval is required.`;
244
+ return `任务 ${id} 未标记为外部副作用,无需审批。`;
225
245
  }
226
246
  if (control.externalApproval === "granted") {
227
- return `Task ${id} was already approved by ${control.approvalBy ?? "a user"} at ${control.approvedAt ?? "an unknown time"}.`;
247
+ return `任务 ${id} 已由 ${control.approvalBy ?? "某位用户"} 于 ${control.approvedAt ?? "未知时间"} 批准过。`;
228
248
  }
229
249
  control.externalApproval = "granted";
230
250
  control.approvalBy = options.approver?.trim() || "unknown-user";
231
251
  control.approvedAt = new Date().toISOString();
232
252
  control.approvalBodyHash = taskBodyHash(task.body);
233
253
  await writeStoredTask(task);
234
- return `Approved external side effects for task ${id}. Approval is recorded for ${control.approvalBy}.`;
254
+ return `已批准任务 ${id} 的外部副作用,审批人记为 ${control.approvalBy}。`;
235
255
  }
236
256
  export async function pauseTask(options, idInput) {
237
257
  const id = normalizeTaskId(idInput);
238
258
  const task = await readStoredTask(options.channelDir, id);
239
259
  if (!task)
240
- return `Task not found: ${id}`;
260
+ return `找不到任务:${id}`;
241
261
  const from = normalizeStoredStatus(task.fields.status);
242
262
  if (from === "paused")
243
- return `Task ${id} is already paused.`;
263
+ return `任务 ${id} 已经是暂停状态。`;
244
264
  try {
245
265
  resolveTaskTransition("pause", id, from);
246
266
  }
@@ -254,16 +274,16 @@ export async function pauseTask(options, idInput) {
254
274
  task.fields.control.blockedReason = `Paused by ${options.approver?.trim() || "a user"}.`;
255
275
  }
256
276
  await writeStoredTask(task);
257
- return `Paused task ${id}. Use /tasks resume ${id} when it should continue.`;
277
+ return `已暂停任务 ${id}。需要继续时用 /tasks resume ${id}。`;
258
278
  }
259
279
  export async function resumeTask(options, idInput) {
260
280
  const id = normalizeTaskId(idInput);
261
281
  const task = await readStoredTask(options.channelDir, id);
262
282
  if (!task)
263
- return `Task not found: ${id}`;
283
+ return `找不到任务:${id}`;
264
284
  const from = normalizeStoredStatus(task.fields.status);
265
285
  if (from !== "paused")
266
- return `Task ${id} is ${from}, not paused.`;
286
+ return `任务 ${id} 当前是 ${from},并非暂停状态。`;
267
287
  resolveTaskTransition("resume", id, from);
268
288
  task.fields.status = "active";
269
289
  task.fields.wake = undefined;
@@ -272,13 +292,68 @@ export async function resumeTask(options, idInput) {
272
292
  task.fields.control.blockedReason = undefined;
273
293
  }
274
294
  await writeStoredTask(task);
275
- return `Resumed task ${id}; the task driver will pick it up on its next scan.`;
295
+ return `已恢复任务 ${id},任务驱动器下一轮扫描会接上。`;
296
+ }
297
+ /**
298
+ * Edit one task field directly.
299
+ *
300
+ * The alternative — telling the model "change wake to tomorrow 9am" — costs a whole turn and its
301
+ * tokens to reach the same one-line write. Validation is not re-implemented here: `wake` reuses
302
+ * the ledger's ISO8601 rule and everything else goes through `applyTaskControlPatch`, the same
303
+ * function `task_manage set` uses, so the two entry points cannot drift apart.
304
+ */
305
+ async function setTaskField(options, idInput, field, value) {
306
+ const id = normalizeTaskId(idInput);
307
+ const task = await readStoredTask(options.channelDir, id);
308
+ if (!task)
309
+ return `找不到任务:${id}`;
310
+ if (field === "wake") {
311
+ if (!value) {
312
+ task.fields.wake = undefined;
313
+ }
314
+ else if (!Number.isFinite(new Date(value).getTime())) {
315
+ return `wake "${value}" 不是合法的 ISO8601 时间。`;
316
+ }
317
+ else {
318
+ task.fields.wake = value;
319
+ }
320
+ }
321
+ else {
322
+ const control = task.fields.control ?? createDefaultTaskControl();
323
+ try {
324
+ task.fields.control = applyTaskControlPatch(control, field === "next"
325
+ ? { nextAction: value }
326
+ : field === "deadline"
327
+ ? { deadline: value }
328
+ : field === "priority"
329
+ ? { priority: parseTaskPriority(value) }
330
+ : { maxAttempts: parseAttempts(value) });
331
+ }
332
+ catch (error) {
333
+ return errorMessage(error);
334
+ }
335
+ }
336
+ await writeStoredTask(task);
337
+ return `已更新任务 ${id}:${field} = ${value || "(已清除)"}`;
338
+ }
339
+ function parseTaskPriority(value) {
340
+ if (!TASK_PRIORITIES.includes(value)) {
341
+ throw new Error(`priority 必须是 ${TASK_PRIORITIES.join(" / ")} 之一。`);
342
+ }
343
+ return value;
344
+ }
345
+ function parseAttempts(value) {
346
+ const parsed = Number(value);
347
+ if (!Number.isInteger(parsed) || parsed < 1) {
348
+ throw new Error("attempts 必须是不小于 1 的整数。");
349
+ }
350
+ return parsed;
276
351
  }
277
352
  async function runTask(options, idInput) {
278
353
  const id = normalizeTaskId(idInput);
279
354
  const task = await readStoredTask(options.channelDir, id);
280
355
  if (!task)
281
- return `Task not found: ${id}`;
356
+ return `找不到任务:${id}`;
282
357
  const from = normalizeStoredStatus(task.fields.status);
283
358
  try {
284
359
  resolveTaskTransition("run", id, from);
@@ -299,13 +374,13 @@ async function runTask(options, idInput) {
299
374
  if (!enqueued && claim)
300
375
  await releaseTaskAttemptClaim(options.channelDir, id, claim, now);
301
376
  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.`;
377
+ ? `已把任务 ${id} 排入一次立即执行。`
378
+ : `任务 ${id} 已就绪。启动钉钉守护进程可自动派发,或在本会话里直接发一条普通消息推进它。`;
304
379
  }
305
380
  function renderUsageLine(entry) {
306
381
  const control = entry.frontmatter.control;
307
382
  if (!control)
308
- return `- ${entry.id}: legacy task (no governed usage recorded)`;
383
+ return `- ${entry.id}:旧格式任务(没有受治理的用量记录)`;
309
384
  const verification = control.verification;
310
385
  const cycleCost = control.usage.costKnown ? `$${control.usage.costUsd.toFixed(4)}` : "unavailable";
311
386
  return [
@@ -320,7 +395,7 @@ async function taskStats(options, idInput) {
320
395
  const id = normalizeTaskId(idInput);
321
396
  const task = await readStoredTask(options.channelDir, id, true, true);
322
397
  if (!task)
323
- return `Task not found: ${id}`;
398
+ return `找不到任务:${id}`;
324
399
  const entry = {
325
400
  id,
326
401
  title: extractTaskTitle(task.body, id),
@@ -333,7 +408,7 @@ async function taskStats(options, idInput) {
333
408
  },
334
409
  actionable: false,
335
410
  };
336
- return `# Task Stats\n\n${renderUsageLine(entry)}`;
411
+ return `# 任务用量\n\n${renderUsageLine(entry)}`;
337
412
  }
338
413
  const entries = await readActiveTasks(tasksDir(options.channelDir));
339
414
  const governed = entries.filter((entry) => entry.frontmatter.control);
@@ -349,7 +424,7 @@ async function taskStats(options, idInput) {
349
424
  const verified = governed.filter((entry) => entry.frontmatter.control?.verification.status === "passed").length;
350
425
  const stalled = governed.filter((entry) => entry.frontmatter.control?.lastOutcome === "failed").length;
351
426
  return [
352
- "# Task Stats",
427
+ "# 任务用量",
353
428
  "",
354
429
  `governed tasks: ${governed.length}/${entries.length}`,
355
430
  `this cycle: ${totals.attempts} attempts, ${totals.tokens} tokens, ${totals.costKnown ? `$${totals.costUsd.toFixed(4)}` : "cost unavailable"}, ${totals.wallTimeMinutes.toFixed(1)}m`,
@@ -366,20 +441,20 @@ async function showTask(channelDir, id) {
366
441
  const archivePath = resolveTaskPath(dir, taskId, "archive");
367
442
  const path = existsSync(activePath) ? activePath : existsSync(archivePath) ? archivePath : undefined;
368
443
  if (!path) {
369
- return `Task not found: ${taskId}`;
444
+ return `找不到任务:${taskId}`;
370
445
  }
371
- const location = path === archivePath ? " (archived)" : "";
446
+ const location = path === archivePath ? "(已归档)" : "";
372
447
  const content = await readFile(path, "utf-8");
373
- return `# Task: ${taskId}${location}\n\n\`\`\`markdown\n${content}\n\`\`\``;
448
+ return `# 任务:${taskId}${location}\n\n\`\`\`markdown\n${content}\n\`\`\``;
374
449
  }
375
450
  async function listArchive(channelDir) {
376
451
  const dir = join(tasksDir(channelDir), "archive");
377
452
  if (!existsSync(dir)) {
378
- return "# Archived Tasks\n\nNo archived tasks.";
453
+ return "# 已归档任务\n\n暂无已归档任务。";
379
454
  }
380
455
  const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".md")).sort();
381
456
  if (filenames.length === 0) {
382
- return "# Archived Tasks\n\nNo archived tasks.";
457
+ return "# 已归档任务\n\n暂无已归档任务。";
383
458
  }
384
459
  const blocks = [];
385
460
  for (const filename of filenames) {
@@ -392,11 +467,11 @@ async function listArchive(channelDir) {
392
467
  blocks.push(`- ${id}`);
393
468
  }
394
469
  }
395
- return `# Archived Tasks: ${blocks.length}\n\n${blocks.join("\n")}`;
470
+ return `# 已归档任务:${blocks.length}\n\n${blocks.join("\n")}`;
396
471
  }
397
472
  async function doctor(options) {
398
473
  if (!options.workspaceDir || !options.channelId) {
399
- return "# Task Doctor\n\nNot available: workspaceDir and channelId are required.";
474
+ return "# 任务体检\n\n不可用:需要 workspaceDir 与 channelId。";
400
475
  }
401
476
  const now = Date.now();
402
477
  const entries = await readActiveTasks(tasksDir(options.channelDir), now);
@@ -493,9 +568,9 @@ async function doctor(options) {
493
568
  }
494
569
  }
495
570
  if (issues.length === 0) {
496
- return "# Task Doctor\n\nNo task ledger issues found.";
571
+ return "# 任务体检\n\n未发现任务台账问题。";
497
572
  }
498
- return `# Task Doctor\n\nFound ${issues.length} issue${issues.length === 1 ? "" : "s"}:\n\n${issues.join("\n")}`;
573
+ return `# 任务体检\n\n发现 ${issues.length} 个问题:\n\n${issues.join("\n")}`;
499
574
  }
500
575
  export async function handleTasksCommand(options) {
501
576
  let command;
@@ -522,6 +597,8 @@ export async function handleTasksCommand(options) {
522
597
  return await resumeTask(options, command.id);
523
598
  case "run":
524
599
  return await runTask(options, command.id);
600
+ case "set":
601
+ return await setTaskField(options, command.id, command.field, command.value);
525
602
  case "stats":
526
603
  return await taskStats(options, command.id);
527
604
  case "doctor":
@@ -530,6 +607,6 @@ export async function handleTasksCommand(options) {
530
607
  }
531
608
  catch (error) {
532
609
  const message = errorMessage(error);
533
- return `Could not ${command.action} tasks: ${message}`;
610
+ return `执行 /tasks ${command.action} 失败:${message}`;
534
611
  }
535
612
  }
@@ -67,12 +67,37 @@ function taskFingerprint(entry, effects) {
67
67
  `effects:${effects}`,
68
68
  ].join("\0");
69
69
  }
70
- function isEligible(attempt, fingerprint, nowMs, settings) {
70
+ /**
71
+ * How long a task must wait after its last attempt, in three tiers.
72
+ *
73
+ * Backoff and cadence are different jobs, and one delay used to do both: any wake that changed
74
+ * the ledger — including one that wrote code — waited out the same continuation delay as one that
75
+ * only edited a note. A twenty-step task therefore spent well over an hour purely idle, which is
76
+ * fatal for the "drive an external agent in small steps" shape this driver exists for.
77
+ *
78
+ * So the tiers are keyed on evidence, not on the boolean "something changed":
79
+ * - the channel's effect tally grew ⇒ the last wake actually did something ⇒ continue at once;
80
+ * - the ledger changed with no effect (status/note churn) ⇒ the ordinary continuation delay;
81
+ * - nothing changed ⇒ the long stalled-retry backoff, and the futile counter keeps running.
82
+ *
83
+ * Nothing here relaxes the stop-losses: the fast tier still costs one attempt against
84
+ * `budget.maxAttempts`, so a task that spins productively-looking still hits the governor — just
85
+ * sooner in wall time instead of an hour per step.
86
+ */
87
+ function attemptDelayMs(attempt, fingerprint, effects, settings) {
88
+ // A dispatch the channel refused never ran; retry it on the short delay regardless of state.
89
+ if (!attempt.accepted)
90
+ return settings.continuationDelayMinutes * 60_000;
91
+ if (attempt.fingerprint === fingerprint)
92
+ return settings.stalledRetryMinutes * 60_000;
93
+ if (effects > attempt.effects)
94
+ return 0;
95
+ return settings.continuationDelayMinutes * 60_000;
96
+ }
97
+ function isEligible(attempt, fingerprint, effects, nowMs, settings) {
71
98
  if (!attempt)
72
99
  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;
100
+ return nowMs - attempt.atMs >= attemptDelayMs(attempt, fingerprint, effects, settings);
76
101
  }
77
102
  /**
78
103
  * Stable, provenance-derived dispatch id for a task wake (spec 031, D1).
@@ -375,7 +400,7 @@ export class TaskDriver {
375
400
  const effects = this.options.getEffectCount?.(channelId) ?? 0;
376
401
  const fingerprint = taskFingerprint(entry, effects);
377
402
  const previous = this.attempts.get(key);
378
- if (!isEligible(previous, fingerprint, nowMs, settings))
403
+ if (!isEligible(previous, fingerprint, effects, nowMs, settings))
379
404
  continue;
380
405
  // D5: a wake that was accepted and left the ledger fingerprint unchanged made no
381
406
  // visible progress. Count consecutive such wakes (a changed fingerprint — including
@@ -404,7 +429,7 @@ export class TaskDriver {
404
429
  this.observeDispatch(event, accepted);
405
430
  if (!accepted && claim)
406
431
  await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
407
- this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, futileCount });
432
+ this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, effects, futileCount });
408
433
  this.lastDispatchedTaskId.set(channelId, entry.id);
409
434
  if (accepted) {
410
435
  dispatched++;
@@ -420,10 +445,14 @@ export class TaskDriver {
420
445
  this.attempts.delete(key);
421
446
  }
422
447
  // 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.
448
+ // so an unchanged ledger is still retried without polling. Changed ledgers arrive via
449
+ // nudge. Both tiers are noted because which one applies depends on the ledger as it will
450
+ // be *then*: `noteHorizon` keeps whichever is next in the future, so the short tier is
451
+ // honored on time and the long one is still not missed.
424
452
  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);
453
+ this.noteHorizon(attempt.atMs + settings.continuationDelayMinutes * 60_000, nowMs);
454
+ if (attempt.accepted)
455
+ this.noteHorizon(attempt.atMs + settings.stalledRetryMinutes * 60_000, nowMs);
427
456
  }
428
457
  const channelSet = new Set(channels);
429
458
  for (const channelId of this.lastDispatchedTaskId.keys()) {
@@ -1,4 +1,4 @@
1
- import { readdir, readFile } from "node:fs/promises";
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { parseTaskControl, taskPriorityRank } from "../tasks/control.js";
4
4
  import { normalizeStoredStatus, TERMINAL_TASK_STATUSES, wasLegacyEscalated } from "../tasks/transitions.js";
@@ -642,6 +642,21 @@ function toEntry(id, content, now) {
642
642
  latestNote: extractLatestNote(content),
643
643
  };
644
644
  }
645
+ const parseCache = new Map();
646
+ /** Bound the cache for a long-lived daemon: far above any real ledger, and cheap to refill. */
647
+ const PARSE_CACHE_LIMIT = 512;
648
+ async function readEntry(path, id, now) {
649
+ const stats = await stat(path);
650
+ const cached = parseCache.get(path);
651
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
652
+ return { ...cached.entry, actionable: isTaskActionable(cached.entry.frontmatter, now) };
653
+ }
654
+ const entry = toEntry(id, await readFile(path, "utf-8"), now);
655
+ if (parseCache.size >= PARSE_CACHE_LIMIT)
656
+ parseCache.clear();
657
+ parseCache.set(path, { mtimeMs: stats.mtimeMs, ctimeMs: stats.ctimeMs, size: stats.size, entry });
658
+ return entry;
659
+ }
645
660
  /**
646
661
  * Read every `.md` file in `tasks/` (root only — the `archive/` subdirectory is not
647
662
  * scanned), returning entries sorted actionable-first. A file that cannot be read is
@@ -661,11 +676,12 @@ export async function readActiveTasks(tasksDir, now = Date.now()) {
661
676
  if (!dirent.isFile() || !dirent.name.endsWith(".md"))
662
677
  continue;
663
678
  const id = dirent.name.slice(0, -".md".length);
679
+ const path = join(tasksDir, dirent.name);
664
680
  try {
665
- const content = await readFile(join(tasksDir, dirent.name), "utf-8");
666
- entries.push(toEntry(id, content, now));
681
+ entries.push(await readEntry(path, id, now));
667
682
  }
668
683
  catch {
684
+ parseCache.delete(path);
669
685
  entries.push({
670
686
  id,
671
687
  title: id,
@@ -19,6 +19,7 @@ declare const subagentSchema: Type.TObject<{
19
19
  effort: Type.TOptional<Type.TUnion<[Type.TLiteral<"quick">, Type.TLiteral<"standard">, Type.TLiteral<"deep">]>>;
20
20
  context: Type.TOptional<Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"session">, Type.TLiteral<"relevant">]>>;
21
21
  paths: Type.TOptional<Type.TArray<Type.TString>>;
22
+ workingDirectory: Type.TOptional<Type.TString>;
22
23
  purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
23
24
  taskId: Type.TOptional<Type.TString>;
24
25
  returns: Type.TOptional<Type.TUnion<[Type.TLiteral<"text">, Type.TLiteral<"artifact">]>>;
@@ -1,3 +1,4 @@
1
+ import { existsSync, statSync } from "node:fs";
1
2
  import { mkdir, writeFile } from "node:fs/promises";
2
3
  import { isAbsolute, join, relative, resolve } from "node:path";
3
4
  import { Agent } from "@earendil-works/pi-agent-core";
@@ -9,7 +10,6 @@ import { formatModelReference } from "../models/utils.js";
9
10
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
10
11
  import { splitH1Sections } from "../shared/markdown-sections.js";
11
12
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
12
- import { shellEscape } from "../shared/shell-escape.js";
13
13
  import { clipText, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
14
14
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
15
15
  import { readStoredTask } from "../tasks/store.js";
@@ -35,6 +35,9 @@ const subagentSchema = Type.Object({
35
35
  paths: Type.Optional(Type.Array(Type.String(), {
36
36
  description: "Optional preferred file or directory paths for the sub-agent to focus on.",
37
37
  })),
38
+ workingDirectory: Type.Optional(Type.String({
39
+ description: "Optional existing directory to run the sub-agent in (its shell cwd and relative-path root). Use it to work on another checkout — e.g. a `git worktree add`ed one. Defaults to this runtime's own working directory.",
40
+ })),
38
41
  purpose: Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
39
42
  description: 'Use "verify" for an independent, read-only task acceptance check.',
40
43
  })),
@@ -80,13 +83,19 @@ const ARTIFACT_TRUNCATION_HEAD_RATIO = 1;
80
83
  */
81
84
  const CONVERGENCE_WALL_CLOCK_MS = 60_000;
82
85
  const CONVERGENCE_PROMPT = "Your turn/tool-call/wall-time budget for this task is exhausted. Based only on the work you have already completed, respond now with your conclusions: confirmed facts, what remains unfinished, and suggested next steps. Do not call any more tools.";
86
+ /**
87
+ * Pins every command a run issues to the run's working directory. It sets the child's real `cwd`
88
+ * rather than prefixing `cd <dir> &&`: the prefix silently produced a *different* command than the
89
+ * guard inspected, and a directory that cannot be entered surfaced as a shell error inside an
90
+ * otherwise successful command line.
91
+ */
83
92
  class DirectoryExecutor {
84
93
  constructor(base, directory) {
85
94
  this.base = base;
86
95
  this.directory = directory;
87
96
  }
88
97
  exec(command, options) {
89
- return this.base.exec(`cd ${shellEscape(this.directory)} && ${command}`, options);
98
+ return this.base.exec(command, { ...options, cwd: this.directory });
90
99
  }
91
100
  }
92
101
  function safeRunSegment(value) {
@@ -101,6 +110,26 @@ async function prepareArtifactDir(channelDir, runId) {
101
110
  await mkdir(artifactDir, { recursive: true });
102
111
  return artifactDir;
103
112
  }
113
+ /**
114
+ * Resolve the checkout a run works in (spec 036, D3).
115
+ *
116
+ * Spec 036 removed task-owned worktrees on the premise that a caller needing a separate checkout
117
+ * would `git worktree add` on the host and "pass it in as an ordinary working directory" — but no
118
+ * parameter for that ever existed, so every run was pinned to the daemon's own cwd. This is that
119
+ * parameter. Path guards are unaffected: they judge the *resolved absolute* target, so a cwd
120
+ * outside the allowed roots makes relative paths fail exactly as an absolute one there would.
121
+ */
122
+ function resolveRunWorkingDirectory(requested, options) {
123
+ const base = resolve(options.workingDirectory ?? process.cwd());
124
+ const trimmed = requested?.trim();
125
+ if (!trimmed)
126
+ return base;
127
+ const target = resolve(base, trimmed);
128
+ if (!existsSync(target) || !statSync(target).isDirectory()) {
129
+ throw new Error(`workingDirectory "${requested}" is not an existing directory.`);
130
+ }
131
+ return target;
132
+ }
104
133
  async function prepareRunContext(runId, params, options) {
105
134
  const purpose = params.purpose ?? "work";
106
135
  const taskId = params.taskId?.trim() || undefined;
@@ -112,7 +141,7 @@ async function prepareRunContext(runId, params, options) {
112
141
  throw new Error(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
113
142
  }
114
143
  const artifactDir = await prepareArtifactDir(options.channelDir, runId);
115
- const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
144
+ const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
116
145
  return { runId, purpose, taskId, workingDirectory, artifactDir };
117
146
  }
118
147
  async function gitWorkspaceState(executor) {
@@ -584,6 +613,7 @@ export function createSubAgentTool(options) {
584
613
  evidence,
585
614
  workspaceChanged: Boolean(workspaceChanged),
586
615
  subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
616
+ subjectDir: runContext.workingDirectory,
587
617
  });
588
618
  }
589
619
  if (effectiveFailureReason) {
@@ -95,6 +95,7 @@ export interface TaskControlPatch {
95
95
  /** Whether closing this task requires an independent verifier attestation (spec 036, D5). */
96
96
  verificationRequired?: boolean;
97
97
  }
98
+ export declare const TASK_PRIORITIES: readonly TaskPriority[];
98
99
  /**
99
100
  * Control keys that older builds wrote and this one ignores (spec 036, D8).
100
101
  *
@@ -1,5 +1,5 @@
1
1
  import { errorMessage } from "../shared/text-utils.js";
2
- const PRIORITIES = ["low", "normal", "high", "critical"];
2
+ export const TASK_PRIORITIES = ["low", "normal", "high", "critical"];
3
3
  const SIDE_EFFECTS = ["workspace", "external"];
4
4
  const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
5
5
  const OUTCOMES = ["pending", "running", "progress", "blocked", "failed"];
@@ -160,7 +160,7 @@ export function parseTaskControl(raw) {
160
160
  }
161
161
  return {
162
162
  version: 1,
163
- priority: enumValue(value.priority, PRIORITIES, "normal"),
163
+ priority: enumValue(value.priority, TASK_PRIORITIES, "normal"),
164
164
  deadline,
165
165
  nextAction: optionalString(value.nextAction),
166
166
  lastOutcome: enumValue(canonicalEnumValue(value.lastOutcome), OUTCOMES, "pending"),
@@ -19,6 +19,14 @@ export interface VerificationAttestation {
19
19
  workspaceChanged: boolean;
20
20
  /** Git HEAD + working-tree subject that the verifier actually inspected. */
21
21
  subjectHash?: string;
22
+ /**
23
+ * The checkout `subjectHash` was computed in. Recorded so `verify` and `done` recompute the
24
+ * subject where the verifier looked, not wherever the daemon happens to be running: a
25
+ * sub-agent may be pointed at another checkout via `workingDirectory`, and comparing that
26
+ * verdict against the daemon's own cwd would either fail closed forever or — worse — compare
27
+ * a PASS against an unrelated repository. Absent on attestations written before this field.
28
+ */
29
+ subjectDir?: string;
22
30
  }
23
31
  export declare function verificationDir(channelDir: string): string;
24
32
  export declare function verificationAttestationPath(channelDir: string, runId: string): string;