@oyasmi/pipiclaw 0.8.8 → 0.8.9-beta.2

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 (110) hide show
  1. package/README.md +8 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +3 -2
  4. package/dist/agent/effect-ledger.d.ts +11 -0
  5. package/dist/agent/effect-ledger.js +42 -0
  6. package/dist/agent/job-manager.d.ts +90 -13
  7. package/dist/agent/job-manager.js +235 -20
  8. package/dist/agent/prompt/sections.js +11 -2
  9. package/dist/agent/prompt/types.d.ts +7 -1
  10. package/dist/agent/runner-factory.d.ts +7 -0
  11. package/dist/agent/session-events.js +20 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/log.d.ts +6 -0
  14. package/dist/log.js +12 -0
  15. package/dist/memory/consolidation.d.ts +5 -0
  16. package/dist/memory/consolidation.js +35 -147
  17. package/dist/memory/extraction.d.ts +45 -0
  18. package/dist/memory/extraction.js +227 -0
  19. package/dist/memory/lifecycle.js +5 -0
  20. package/dist/memory/maintenance-jobs.js +7 -0
  21. package/dist/memory/post-turn-review.d.ts +3 -1
  22. package/dist/memory/post-turn-review.js +20 -189
  23. package/dist/memory/recall.d.ts +0 -1
  24. package/dist/memory/recall.js +135 -77
  25. package/dist/memory/sidecar-worker.d.ts +7 -0
  26. package/dist/memory/sidecar-worker.js +23 -5
  27. package/dist/memory/task-digest.js +1 -1
  28. package/dist/paths.d.ts +1 -0
  29. package/dist/paths.js +11 -0
  30. package/dist/playbooks/background-jobs.md +40 -0
  31. package/dist/playbooks/catalog.d.ts +1 -7
  32. package/dist/playbooks/catalog.js +4 -14
  33. package/dist/playbooks/event-scheduling.md +8 -4
  34. package/dist/playbooks/memory-and-learning.md +1 -1
  35. package/dist/playbooks/outbound-media.md +45 -0
  36. package/dist/playbooks/runtime-orientation.md +1 -1
  37. package/dist/playbooks/task-closeout.md +12 -11
  38. package/dist/playbooks/task-delegation.md +11 -5
  39. package/dist/playbooks/task-driving.md +54 -21
  40. package/dist/playbooks/task-planning.md +46 -19
  41. package/dist/runtime/bootstrap.js +29 -4
  42. package/dist/runtime/channel-context.d.ts +33 -0
  43. package/dist/runtime/dingtalk.d.ts +22 -2
  44. package/dist/runtime/dingtalk.js +141 -0
  45. package/dist/runtime/durable-dispatch.d.ts +10 -0
  46. package/dist/runtime/durable-dispatch.js +42 -1
  47. package/dist/runtime/event-validation.d.ts +48 -0
  48. package/dist/runtime/event-validation.js +81 -0
  49. package/dist/runtime/events.d.ts +17 -8
  50. package/dist/runtime/events.js +96 -22
  51. package/dist/runtime/store.d.ts +1 -1
  52. package/dist/runtime/task-commands.js +29 -51
  53. package/dist/runtime/task-driver.d.ts +5 -8
  54. package/dist/runtime/task-driver.js +120 -93
  55. package/dist/runtime/task-migration.d.ts +11 -0
  56. package/dist/runtime/task-migration.js +70 -0
  57. package/dist/settings.d.ts +11 -0
  58. package/dist/settings.js +12 -0
  59. package/dist/shared/recoverable-error.d.ts +26 -0
  60. package/dist/shared/recoverable-error.js +29 -0
  61. package/dist/shared/task-events.d.ts +0 -26
  62. package/dist/shared/task-events.js +0 -15
  63. package/dist/shared/task-ledger.d.ts +32 -8
  64. package/dist/shared/task-ledger.js +66 -17
  65. package/dist/subagents/builtin/explorer.md +16 -0
  66. package/dist/subagents/builtin/researcher.md +17 -0
  67. package/dist/subagents/builtin/verifier.md +17 -0
  68. package/dist/subagents/discovery.d.ts +17 -3
  69. package/dist/subagents/discovery.js +88 -15
  70. package/dist/subagents/tool.d.ts +21 -1
  71. package/dist/subagents/tool.js +140 -12
  72. package/dist/tasks/control.d.ts +4 -0
  73. package/dist/tasks/control.js +3 -0
  74. package/dist/tasks/store.d.ts +28 -1
  75. package/dist/tasks/store.js +63 -6
  76. package/dist/tasks/transitions.d.ts +40 -0
  77. package/dist/tasks/transitions.js +82 -0
  78. package/dist/tools/bash.d.ts +2 -0
  79. package/dist/tools/bash.js +18 -5
  80. package/dist/tools/event-manage.js +28 -77
  81. package/dist/tools/index.d.ts +4 -0
  82. package/dist/tools/index.js +7 -2
  83. package/dist/tools/job.js +2 -2
  84. package/dist/tools/memory-manage.js +0 -1
  85. package/dist/tools/registry.d.ts +29 -8
  86. package/dist/tools/registry.js +39 -22
  87. package/dist/tools/send-media.d.ts +28 -0
  88. package/dist/tools/send-media.js +88 -0
  89. package/dist/tools/task-manage/create.d.ts +2 -0
  90. package/dist/tools/task-manage/create.js +35 -0
  91. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  92. package/dist/tools/task-manage/lifecycle.js +197 -0
  93. package/dist/tools/task-manage/schema.d.ts +43 -0
  94. package/dist/tools/task-manage/schema.js +90 -0
  95. package/dist/tools/task-manage/shared.d.ts +36 -0
  96. package/dist/tools/task-manage/shared.js +247 -0
  97. package/dist/tools/task-manage/types.d.ts +53 -0
  98. package/dist/tools/task-manage/types.js +1 -0
  99. package/dist/tools/task-manage/verification.d.ts +16 -0
  100. package/dist/tools/task-manage/verification.js +112 -0
  101. package/dist/tools/task-manage.d.ts +9 -89
  102. package/dist/tools/task-manage.js +8 -696
  103. package/dist/tools/tool-details.d.ts +44 -0
  104. package/dist/tools/tool-details.js +62 -0
  105. package/dist/tui/app.js +2 -0
  106. package/dist/tui/terminal-media-sender.d.ts +9 -0
  107. package/dist/tui/terminal-media-sender.js +15 -0
  108. package/package.json +2 -2
  109. package/dist/playbooks/task-recurring.md +0 -41
  110. package/dist/playbooks/task-repair.md +0 -45
@@ -9,6 +9,11 @@ export interface TaskDriverOptions {
9
9
  /** Optional observability hook. It runs after every production dispatch attempt. */
10
10
  onDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
11
11
  getSettings: () => PipiclawTaskDriverSettings;
12
+ /**
13
+ * Externally visible effects recorded for a channel so far (spec 031, D7). Defaults to a
14
+ * constant, which simply makes the fingerprint depend on ledger fields alone.
15
+ */
16
+ getEffectCount?: (channelId: string) => number;
12
17
  /** Master autonomy switch (`tools.tasks.enabled`); re-read every tick. Defaults to on. */
13
18
  isEnabled?: () => boolean;
14
19
  /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
@@ -16,13 +21,6 @@ export interface TaskDriverOptions {
16
21
  }
17
22
  export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
18
23
  export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
19
- /**
20
- * A done recurring task whose schedule has come due. This is the one place the driver
21
- * wakes a `done` task: to open its next cycle. It uses a `[TASK_CYCLE:...]` tag (not
22
- * `[TASK_DRIVER:...]`) so the turn is not charged an attempt — start-cycle resets usage
23
- * anyway, matching the retired periodic-event flow.
24
- */
25
- export declare function createCycleStartEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
26
24
  /**
27
25
  * Native, token-gated driver for the persistent task ledger.
28
26
  *
@@ -65,6 +63,5 @@ export declare class TaskDriver {
65
63
  /** Fold `candidate` into the earliest interesting wake moment. */
66
64
  private noteHorizon;
67
65
  private collectHorizons;
68
- private hasLiveScheduleEvent;
69
66
  runOnce(now?: Date): Promise<void>;
70
67
  }
@@ -1,21 +1,21 @@
1
- import { existsSync } from "node:fs";
2
- import { readdir, readFile } from "node:fs/promises";
1
+ import { createHash } from "node:crypto";
2
+ import { readdir } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import * as log from "../log.js";
5
5
  import { PLAYBOOKS_DIR } from "../paths.js";
6
- import { isTaskScheduleEvent, taskScheduleEventFilename } from "../shared/task-events.js";
7
- import { readActiveTasks } from "../shared/task-ledger.js";
8
- import { nextTaskWake } from "../shared/task-schedule.js";
6
+ import { normalizeTaskFields, readActiveTasks } from "../shared/task-ledger.js";
9
7
  import { errorMessage } from "../shared/text-utils.js";
10
8
  import { taskBudgetViolation } from "../tasks/control.js";
11
- import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
12
- import { parseScheduledEventContent } from "./events.js";
9
+ import { claimTaskAttempt, dependencyState, escalateTask, openRecurringTaskCycle, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
10
+ import { TERMINAL_TASK_STATUSES } from "../tasks/transitions.js";
13
11
  /** Short debounce so a burst of nudges collapses into a single rescan. */
14
12
  const NUDGE_DEBOUNCE_MS = 50;
15
13
  /** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
16
14
  const MIN_SLEEP_MS = 250;
15
+ /** Consecutive no-progress wakes before the governor pauses a task (spec 029, D5). */
16
+ const FUTILE_WAKE_LIMIT = 3;
17
17
  const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
18
- const TERMINAL_STATUSES = new Set(["done", "cancelled", "escalated", "paused"]);
18
+ const TERMINAL_STATUSES = TERMINAL_TASK_STATUSES;
19
19
  function isChannelId(value) {
20
20
  return CHANNEL_ID_PATTERN.test(value);
21
21
  }
@@ -40,10 +40,19 @@ export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
40
40
  function attemptKey(channelId, taskId) {
41
41
  return `${channelId}\0${taskId}`;
42
42
  }
43
- async function taskFingerprint(_channelDir, entry) {
44
- // Do not use mtime/size here. Runtime usage accounting deliberately rewrites
45
- // task control after every attempt; treating that bookkeeping as progress made
46
- // governed tasks retry at the short continuation interval forever.
43
+ /**
44
+ * What "this task moved" means to the driver.
45
+ *
46
+ * Do not use mtime/size here. Runtime usage accounting deliberately rewrites task control after
47
+ * every attempt; treating that bookkeeping as progress made governed tasks retry at the short
48
+ * continuation interval forever.
49
+ *
50
+ * `latestNote` is deliberately absent (spec 031, D7): it is the model's own account of its work,
51
+ * so including it let a wake that did nothing but append a note reset the futile counter forever,
52
+ * and let a wake that changed real files count as stalled. The channel's effect tally stands in
53
+ * for the work itself instead.
54
+ */
55
+ function taskFingerprint(entry, effects) {
47
56
  const control = entry.frontmatter.control;
48
57
  return [
49
58
  entry.frontmatter.readable ? "readable" : "unreadable",
@@ -51,11 +60,11 @@ async function taskFingerprint(_channelDir, entry) {
51
60
  entry.frontmatter.wake ?? "",
52
61
  entry.frontmatter.schedule ?? "",
53
62
  entry.frontmatter.recurrence ?? "",
54
- entry.latestNote ?? "",
55
63
  control?.nextAction ?? "",
56
64
  control?.blockedReason ?? "",
57
65
  control?.verification.status ?? "",
58
66
  control?.cycleId ?? "",
67
+ `effects:${effects}`,
59
68
  ].join("\0");
60
69
  }
61
70
  function isEligible(attempt, fingerprint, nowMs, settings) {
@@ -65,6 +74,18 @@ function isEligible(attempt, fingerprint, nowMs, settings) {
65
74
  const delayMinutes = changed || !attempt.accepted ? settings.continuationDelayMinutes : settings.stalledRetryMinutes;
66
75
  return nowMs - attempt.atMs >= delayMinutes * 60_000;
67
76
  }
77
+ /**
78
+ * Stable, provenance-derived dispatch id for a task wake (spec 031, D1).
79
+ *
80
+ * A scheduled task has a real occurrence — its `wake` — so retries of that occurrence collapse
81
+ * onto one durable record. A task that is simply actionable has no occurrence identity, so the
82
+ * dispatch time is used: two separate wakes of the same task are genuinely separate work, and
83
+ * collapsing them would silently drop the later one.
84
+ */
85
+ function taskDispatchId(channelId, entry, nowMs) {
86
+ const occurrence = entry.frontmatter.wake ?? `t${nowMs}`;
87
+ return `task:${channelId}:${entry.id}:${occurrence}`;
88
+ }
68
89
  export function createTaskDriverEvent(channelId, entry, nowMs) {
69
90
  const verification = entry.frontmatter.control?.verification;
70
91
  const verificationInstruction = entry.frontmatter.status === "verifying"
@@ -74,10 +95,10 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
74
95
  : "";
75
96
  const repair = entry.frontmatter.readable
76
97
  ? ""
77
- : ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-repair.md")}.`;
98
+ : ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-driving.md")}.`;
78
99
  const control = entry.frontmatter.control;
79
100
  const capsule = [
80
- `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "open"};`,
101
+ `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "active"};`,
81
102
  entry.latestNote ? `latest=${entry.latestNote};` : "",
82
103
  control?.nextAction ? `next=${control.nextAction};` : "",
83
104
  control ? `budget=${control.usage.attempts}/${control.budget.maxAttempts} attempts;` : "",
@@ -97,29 +118,10 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
97
118
  ts: String(nowMs),
98
119
  conversationId: "",
99
120
  conversationType: channelId.startsWith("group_") ? "2" : "1",
121
+ dispatchId: taskDispatchId(channelId, entry, nowMs),
100
122
  };
101
123
  }
102
- /**
103
- * A done recurring task whose schedule has come due. This is the one place the driver
104
- * wakes a `done` task: to open its next cycle. It uses a `[TASK_CYCLE:...]` tag (not
105
- * `[TASK_DRIVER:...]`) so the turn is not charged an attempt — start-cycle resets usage
106
- * anyway, matching the retired periodic-event flow.
107
- */
108
- export function createCycleStartEvent(channelId, entry, nowMs) {
109
- return {
110
- type: channelId.startsWith("group_") ? "group" : "dm",
111
- channelId,
112
- user: "TASK_DRIVER",
113
- userName: "TASK_DRIVER",
114
- text: `[TASK_CYCLE:${entry.id}] Start a new cycle for task ${entry.id} (${entry.title}). ` +
115
- `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-recurring.md")}, then use ` +
116
- "task_manage start-cycle with a stable cycleId to fold the previous cycle and begin work.",
117
- ts: String(nowMs),
118
- conversationId: "",
119
- conversationType: channelId.startsWith("group_") ? "2" : "1",
120
- };
121
- }
122
- /** status done + a schedule cadence + a valid wake that is due. */
124
+ /** status done + a schedule cadence + a valid wake that is due → time to open the next cycle. */
123
125
  function isCycleStartReady(entry, nowMs) {
124
126
  return (entry.frontmatter.status === "done" &&
125
127
  Boolean(entry.frontmatter.schedule) &&
@@ -137,17 +139,20 @@ function taskEscalationEvent(channelId, entry, reason, nowMs) {
137
139
  user: "TASK_DRIVER",
138
140
  userName: "TASK_DRIVER",
139
141
  text: `[TASK_ESCALATION:${entry.id}] Task ${entry.id} (${entry.title}) was stopped by the deterministic task ` +
140
- `governor: ${reason}. Read ${join(PLAYBOOKS_DIR, "task-repair.md")}, diagnose before changing control, ` +
142
+ `governor: ${reason}. Read ${join(PLAYBOOKS_DIR, "task-driving.md")}, diagnose before changing control, ` +
141
143
  "inform the user of the cause and recovery, and do not continue implementation in this run.",
142
144
  ts: String(nowMs),
143
145
  conversationId: "",
144
146
  conversationType: channelId.startsWith("group_") ? "2" : "1",
147
+ // Keyed on the cause, not the moment: re-detecting the same violation before the user has
148
+ // acted must not queue a second identical escalation, while a different cause still does.
149
+ dispatchId: `task:${channelId}:${entry.id}:escalation:${createHash("sha256").update(reason).digest("hex").slice(0, 12)}`,
145
150
  };
146
151
  }
147
152
  function terminalDependencyReason(reason) {
148
153
  return reason?.includes(" is missing") ||
149
154
  reason?.includes(" is cancelled") ||
150
- reason?.includes(" is escalated") ||
155
+ reason?.includes(" is paused by the governor") ||
151
156
  reason?.includes("dependency cycle")
152
157
  ? reason
153
158
  : undefined;
@@ -260,19 +265,6 @@ export class TaskDriver {
260
265
  }
261
266
  }
262
267
  }
263
- async hasLiveScheduleEvent(channelId, id) {
264
- const filename = taskScheduleEventFilename(channelId, id);
265
- const eventPath = join(this.options.workspaceDir, "events", filename);
266
- if (!existsSync(eventPath))
267
- return false;
268
- try {
269
- const type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename).type;
270
- return isTaskScheduleEvent({ use: "schedule", event: { type } });
271
- }
272
- catch {
273
- return false;
274
- }
275
- }
276
268
  async runOnce(now = new Date()) {
277
269
  if (this.options.isEnabled?.() === false || this.running)
278
270
  return;
@@ -301,22 +293,23 @@ export class TaskDriver {
301
293
  this.collectHorizons(entries, nowMs);
302
294
  if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
303
295
  continue;
304
- // Zero-token self-heal: a done recurring task with a missing/unparseable wake gets
305
- // its next occurrence recomputed deterministically rather than fail-open into an
306
- // accidental cycle.
296
+ // Zero-token self-heal: a done recurring task with a missing/unparseable wake (usually a
297
+ // hand edit that bypassed the runtime) gets its next occurrence recomputed via the same
298
+ // `normalizeTaskFields` write-path invariant, rather than fail-open into an accidental cycle.
307
299
  for (const entry of entries) {
308
300
  if (!needsWakeHeal(entry))
309
301
  continue;
310
- const next = nextTaskWake(entry.frontmatter.schedule, now);
311
- if (!next) {
302
+ let healedWake;
303
+ await updateStoredTask(channelDir, entry.id, (task) => {
304
+ healedWake = normalizeTaskFields(task.fields).wake;
305
+ task.fields.wake = healedWake;
306
+ });
307
+ if (!healedWake) {
312
308
  log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
313
309
  continue;
314
310
  }
315
- await updateStoredTask(channelDir, entry.id, (task) => {
316
- task.fields.wake = next.toISOString();
317
- });
318
- this.noteHorizon(next.getTime(), nowMs);
319
- log.logInfo(`[${channelId}] Task driver healed wake for ${entry.id}`, next.toISOString());
311
+ this.noteHorizon(new Date(healedWake).getTime(), nowMs);
312
+ log.logInfo(`[${channelId}] Task driver healed wake for ${entry.id}`, healedWake);
320
313
  }
321
314
  let governanceHandled = false;
322
315
  for (const candidate of entries) {
@@ -335,14 +328,15 @@ export class TaskDriver {
335
328
  if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
336
329
  dispatched++;
337
330
  lastDispatchOffset = offset;
338
- log.logWarning(`[${channelId}] Task driver escalated ${candidate.id}`, escalationReason);
331
+ log.logWarning(`[${channelId}] Task driver paused ${candidate.id} (governor)`, escalationReason);
339
332
  }
340
333
  break;
341
334
  }
342
335
  if (governanceHandled)
343
336
  continue;
344
337
  // Actionable tasks and cycle-start-ready recurring tasks share one per-channel slot
345
- // and the same round-robin fairness; only the dispatch text and attempt accounting differ.
338
+ // and the same round-robin fairness. A cycle-start-ready task is folded into its next
339
+ // cycle deterministically by the runtime (D2) and then dispatched as an ordinary wake.
346
340
  const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
347
341
  if (candidates.length === 0)
348
342
  continue;
@@ -352,54 +346,87 @@ export class TaskDriver {
352
346
  ? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
353
347
  : candidates;
354
348
  let entry;
355
- let isCycleStart = false;
356
349
  for (const candidate of rotatedCandidates) {
357
- if (candidate.actionable) {
358
- const control = candidate.frontmatter.control;
359
- if (control) {
360
- const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
361
- if (!dependencies.ready)
362
- continue;
363
- }
364
- entry = candidate;
365
- isCycleStart = false;
366
- break;
350
+ const control = candidate.frontmatter.control;
351
+ if (control) {
352
+ const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
353
+ if (!dependencies.ready)
354
+ continue;
367
355
  }
368
- // Migration compat: while a parseable legacy `.schedule` event still owns the
369
- // cadence, defer to it so the cycle is not opened twice.
370
- if (await this.hasLiveScheduleEvent(channelId, candidate.id))
371
- continue;
372
356
  entry = candidate;
373
- isCycleStart = true;
374
357
  break;
375
358
  }
376
359
  if (!entry || dispatched >= settings.maxDispatchesPerTick)
377
360
  continue;
361
+ // A cycle-start-ready recurring task is reopened in-process before dispatch: fold the
362
+ // previous cycle, reset per-cycle control, mark it active. If the write fails we skip
363
+ // this tick rather than dispatch a stale `done` capsule.
364
+ if (!entry.actionable && isCycleStartReady(entry, nowMs)) {
365
+ let opened;
366
+ try {
367
+ opened = await openRecurringTaskCycle(channelDir, entry.id, now);
368
+ }
369
+ catch (error) {
370
+ // A malformed recurring body (e.g. missing History) must not stall the whole tick.
371
+ log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`, errorMessage(error));
372
+ continue;
373
+ }
374
+ if (!opened) {
375
+ log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`);
376
+ continue;
377
+ }
378
+ entry = {
379
+ ...entry,
380
+ frontmatter: {
381
+ ...entry.frontmatter,
382
+ status: "active",
383
+ wake: undefined,
384
+ control: opened.document.fields.control,
385
+ },
386
+ wakeMs: undefined,
387
+ actionable: true,
388
+ };
389
+ log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
390
+ }
378
391
  const key = attemptKey(channelId, entry.id);
379
- let fingerprint = await taskFingerprint(channelDir, entry);
380
- if (!isEligible(this.attempts.get(key), fingerprint, nowMs, settings))
392
+ const effects = this.options.getEffectCount?.(channelId) ?? 0;
393
+ const fingerprint = taskFingerprint(entry, effects);
394
+ const previous = this.attempts.get(key);
395
+ if (!isEligible(previous, fingerprint, nowMs, settings))
396
+ continue;
397
+ // D5: a wake that was accepted and left the ledger fingerprint unchanged made no
398
+ // visible progress. Count consecutive such wakes (a changed fingerprint — including
399
+ // a progress note or a failure — resets the count); after the limit the governor
400
+ // pauses the task and notifies the user, so no silent loop burns tokens forever.
401
+ const futileCount = previous?.accepted && previous.fingerprint === fingerprint ? previous.futileCount + 1 : 0;
402
+ if (futileCount >= FUTILE_WAKE_LIMIT) {
403
+ const reason = `task made no visible progress in ${FUTILE_WAKE_LIMIT} consecutive wakes`;
404
+ const escalationEvent = taskEscalationEvent(channelId, entry, reason, nowMs);
405
+ const accepted = await this.options.dispatch(escalationEvent);
406
+ this.observeDispatch(escalationEvent, accepted);
407
+ if (accepted && (await escalateTask(channelDir, entry.id, reason))) {
408
+ this.attempts.delete(key);
409
+ this.lastDispatchedTaskId.set(channelId, entry.id);
410
+ dispatched++;
411
+ lastDispatchOffset = offset;
412
+ log.logWarning(`[${channelId}] Task driver paused ${entry.id} (governor)`, reason);
413
+ }
381
414
  continue;
382
- // Cycle-start does not claim an attempt: start-cycle clears the previous cycle's usage,
383
- // so a claim would be immediately erased. Normal driving claims as before.
384
- const claim = !isCycleStart && entry.frontmatter.control
385
- ? await claimTaskAttempt(channelDir, entry.id, now)
386
- : undefined;
387
- if (claim) {
388
- fingerprint = await taskFingerprint(channelDir, entry);
389
415
  }
390
- const event = isCycleStart
391
- ? createCycleStartEvent(channelId, entry, nowMs)
392
- : createTaskDriverEvent(channelId, entry, nowMs);
416
+ // Claiming an attempt only touches usage bookkeeping, which the fingerprint
417
+ // deliberately excludes, so there is nothing to recompute here.
418
+ const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
419
+ const event = createTaskDriverEvent(channelId, entry, nowMs);
393
420
  const accepted = await this.options.dispatch(event);
394
421
  this.observeDispatch(event, accepted);
395
422
  if (!accepted && claim)
396
423
  await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
397
- this.attempts.set(key, { fingerprint, atMs: nowMs, accepted });
424
+ this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, futileCount });
398
425
  this.lastDispatchedTaskId.set(channelId, entry.id);
399
426
  if (accepted) {
400
427
  dispatched++;
401
428
  lastDispatchOffset = offset;
402
- log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}${isCycleStart ? " (cycle-start)" : ""}`);
429
+ log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
403
430
  }
404
431
  else {
405
432
  log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
@@ -0,0 +1,11 @@
1
+ /**
2
+ * One-time migration closing the 027 window (spec 029, D6).
3
+ *
4
+ * Recurrence cadence now lives solely in a task's `schedule` frontmatter; the driver no
5
+ * longer reads legacy canonical `.schedule` periodic events. On daemon start we fold any
6
+ * residual `task.<channelId>.<id>.schedule.json` cron into the owning task's frontmatter
7
+ * (frontmatter wins if it already has a schedule) and delete the event, so there is never
8
+ * "two sources of truth" for a cadence again. Missing/archived tasks simply have their
9
+ * orphaned event removed. Failures are logged and skipped — this must never block startup.
10
+ */
11
+ export declare function migrateLegacyTaskScheduleEvents(workspaceDir: string): Promise<void>;
@@ -0,0 +1,70 @@
1
+ import { readdir, readFile, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import * as log from "../log.js";
4
+ import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
5
+ import { errorMessage } from "../shared/text-utils.js";
6
+ import { updateStoredTask } from "../tasks/store.js";
7
+ import { parseScheduledEventContent } from "./events.js";
8
+ import { discoverTaskChannels } from "./task-driver.js";
9
+ /**
10
+ * One-time migration closing the 027 window (spec 029, D6).
11
+ *
12
+ * Recurrence cadence now lives solely in a task's `schedule` frontmatter; the driver no
13
+ * longer reads legacy canonical `.schedule` periodic events. On daemon start we fold any
14
+ * residual `task.<channelId>.<id>.schedule.json` cron into the owning task's frontmatter
15
+ * (frontmatter wins if it already has a schedule) and delete the event, so there is never
16
+ * "two sources of truth" for a cadence again. Missing/archived tasks simply have their
17
+ * orphaned event removed. Failures are logged and skipped — this must never block startup.
18
+ */
19
+ export async function migrateLegacyTaskScheduleEvents(workspaceDir) {
20
+ const eventsDir = join(workspaceDir, "events");
21
+ let filenames;
22
+ try {
23
+ filenames = (await readdir(eventsDir)).filter((name) => name.endsWith(".json"));
24
+ }
25
+ catch {
26
+ return; // no events directory ⇒ nothing to migrate
27
+ }
28
+ if (filenames.length === 0)
29
+ return;
30
+ const channels = await discoverTaskChannels(workspaceDir);
31
+ for (const filename of filenames) {
32
+ const name = filename.slice(0, -".json".length);
33
+ const channelId = channels.find((id) => name.startsWith(taskEventPrefix(id)));
34
+ if (!channelId)
35
+ continue;
36
+ const parsed = parseTaskEventName(name, channelId);
37
+ if (!parsed || parsed.use !== "schedule")
38
+ continue;
39
+ const eventPath = join(eventsDir, filename);
40
+ let cron;
41
+ try {
42
+ const event = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename);
43
+ if (event.type !== "periodic")
44
+ continue; // not a cadence event; leave it for /events
45
+ cron = event.schedule;
46
+ }
47
+ catch {
48
+ continue; // unparseable ⇒ let /tasks doctor / the user handle it
49
+ }
50
+ try {
51
+ let folded = false;
52
+ const document = await updateStoredTask(join(workspaceDir, channelId), parsed.id, (task) => {
53
+ if (!task.fields.schedule) {
54
+ task.fields.schedule = cron;
55
+ folded = true;
56
+ }
57
+ });
58
+ await unlink(eventPath).catch(() => { });
59
+ if (folded) {
60
+ log.logInfo(`Migrated legacy schedule event ${name} into tasks/${parsed.id}.md`, cron);
61
+ }
62
+ else {
63
+ log.logInfo(`Removed legacy schedule event ${name}`, document ? "task frontmatter already owns a schedule" : "no active task");
64
+ }
65
+ }
66
+ catch (error) {
67
+ log.logWarning(`Could not migrate legacy schedule event ${name}`, errorMessage(error));
68
+ }
69
+ }
70
+ }
@@ -129,6 +129,12 @@ export interface PipiclawSettings {
129
129
  defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
130
130
  /** Single backup model reference (`provider/model`) used when the primary model's turn fails. */
131
131
  fallbackModel?: string | null;
132
+ /**
133
+ * Default model reference (`provider/model`) for sub-agents that don't otherwise name one
134
+ * (spec 032 D5). Lower priority than an invocation's `model` or a predefined agent's
135
+ * frontmatter `model`; falls back to the parent's current model when unset.
136
+ */
137
+ subagentModel?: string | null;
132
138
  compaction?: Partial<PipiclawCompactionSettings>;
133
139
  retry?: Partial<PipiclawRetrySettings>;
134
140
  memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
@@ -187,6 +193,11 @@ export declare class PipiclawSettingsManager {
187
193
  * Empty / whitespace-only values are treated as unset (fallback disabled).
188
194
  */
189
195
  getFallbackModelReference(): string | null;
196
+ /**
197
+ * Default model reference (`provider/model`) for sub-agents, or null when unset.
198
+ * Empty / whitespace-only values are treated as unset (spec 032 D5).
199
+ */
200
+ getSubAgentModelReference(): string | null;
190
201
  getDefaultModel(): string | undefined;
191
202
  getDefaultProvider(): string | undefined;
192
203
  setDefaultModelAndProvider(provider: string, modelId: string): void;
package/dist/settings.js CHANGED
@@ -275,6 +275,18 @@ export class PipiclawSettingsManager {
275
275
  const trimmed = raw.trim();
276
276
  return trimmed.length > 0 ? trimmed : null;
277
277
  }
278
+ /**
279
+ * Default model reference (`provider/model`) for sub-agents, or null when unset.
280
+ * Empty / whitespace-only values are treated as unset (spec 032 D5).
281
+ */
282
+ getSubAgentModelReference() {
283
+ const raw = this.settings.subagentModel;
284
+ if (typeof raw !== "string") {
285
+ return null;
286
+ }
287
+ const trimmed = raw.trim();
288
+ return trimmed.length > 0 ? trimmed : null;
289
+ }
278
290
  getDefaultModel() {
279
291
  return this.settings.defaultModel;
280
292
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * A tool call rejected because of *its own* arguments or an unmet precondition the model can
3
+ * resolve without the user: a missing required field, an id that does not exist, an illegal
4
+ * status transition.
5
+ *
6
+ * This is not a failure of the tool. It is the same class of outcome as bash's non-zero exit
7
+ * code — data the model reacts to — and it is deliberately *not* surfaced to the user as an
8
+ * error, because the model normally fixes it on the next call and a red bubble in the chat
9
+ * would report a fault that never happened.
10
+ *
11
+ * Throw a plain `Error` instead when the user genuinely has to act or know:
12
+ * - a security guard refused the call (the user may need to adjust security.json),
13
+ * - progress needs a human decision (`/tasks approve <id>`),
14
+ * - state is corrupt and needs manual repair,
15
+ * - the tool itself broke (I/O failure, a bug).
16
+ *
17
+ * The test is "can the model resolve this alone?", not "how severe is it?".
18
+ *
19
+ * Lives in `shared/` because domain code raises it (`src/tasks/` transitions) while only the
20
+ * tool layer interprets it: `withToolDetails` converts it at the tool boundary into a normal
21
+ * result carrying `recoverable: true`. That conversion is required — the pi SDK discards
22
+ * thrown error objects and keeps only `error.message`, so the type cannot survive on its own.
23
+ */
24
+ export declare class RecoverableToolError extends Error {
25
+ constructor(message: string);
26
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * A tool call rejected because of *its own* arguments or an unmet precondition the model can
3
+ * resolve without the user: a missing required field, an id that does not exist, an illegal
4
+ * status transition.
5
+ *
6
+ * This is not a failure of the tool. It is the same class of outcome as bash's non-zero exit
7
+ * code — data the model reacts to — and it is deliberately *not* surfaced to the user as an
8
+ * error, because the model normally fixes it on the next call and a red bubble in the chat
9
+ * would report a fault that never happened.
10
+ *
11
+ * Throw a plain `Error` instead when the user genuinely has to act or know:
12
+ * - a security guard refused the call (the user may need to adjust security.json),
13
+ * - progress needs a human decision (`/tasks approve <id>`),
14
+ * - state is corrupt and needs manual repair,
15
+ * - the tool itself broke (I/O failure, a bug).
16
+ *
17
+ * The test is "can the model resolve this alone?", not "how severe is it?".
18
+ *
19
+ * Lives in `shared/` because domain code raises it (`src/tasks/` transitions) while only the
20
+ * tool layer interprets it: `withToolDetails` converts it at the tool boundary into a normal
21
+ * result carrying `recoverable: true`. That conversion is required — the pi SDK discards
22
+ * thrown error objects and keeps only `error.message`, so the type cannot survive on its own.
23
+ */
24
+ export class RecoverableToolError extends Error {
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = "RecoverableToolError";
28
+ }
29
+ }
@@ -2,31 +2,5 @@ export interface ParsedTaskEventName {
2
2
  id: string;
3
3
  use: string;
4
4
  }
5
- export interface TaskEventLike {
6
- id?: string;
7
- use?: string;
8
- event?: {
9
- type: string;
10
- };
11
- }
12
- type EventOf<T> = T extends {
13
- event?: infer E;
14
- } ? E : never;
15
5
  export declare function taskEventPrefix(channelId: string, id?: string): string;
16
- export declare function taskEventName(channelId: string, id: string, use: string): string;
17
- export declare function taskScheduleEventName(channelId: string, id: string): string;
18
- export declare function taskScheduleEventFilename(channelId: string, id: string): string;
19
6
  export declare function parseTaskEventName(name: string, channelId: string): ParsedTaskEventName | undefined;
20
- export declare function isTaskScheduleEvent<T extends TaskEventLike>(info: T): info is T & {
21
- use: "schedule";
22
- event: Extract<EventOf<T>, {
23
- type: "periodic";
24
- }>;
25
- };
26
- export declare function isTaskCheckinEvent<T extends TaskEventLike>(info: T): info is T & {
27
- use: "checkin";
28
- event: Extract<EventOf<T>, {
29
- type: "one-shot";
30
- }>;
31
- };
32
- export {};
@@ -1,15 +1,6 @@
1
1
  export function taskEventPrefix(channelId, id) {
2
2
  return id ? `task.${channelId}.${id}.` : `task.${channelId}.`;
3
3
  }
4
- export function taskEventName(channelId, id, use) {
5
- return `${taskEventPrefix(channelId, id)}${use}`;
6
- }
7
- export function taskScheduleEventName(channelId, id) {
8
- return taskEventName(channelId, id, "schedule");
9
- }
10
- export function taskScheduleEventFilename(channelId, id) {
11
- return `${taskScheduleEventName(channelId, id)}.json`;
12
- }
13
4
  export function parseTaskEventName(name, channelId) {
14
5
  const normalized = name.endsWith(".json") ? name.slice(0, -".json".length) : name;
15
6
  const prefix = taskEventPrefix(channelId);
@@ -21,9 +12,3 @@ export function parseTaskEventName(name, channelId) {
21
12
  return undefined;
22
13
  return { id: rest.slice(0, lastDot), use: rest.slice(lastDot + 1) };
23
14
  }
24
- export function isTaskScheduleEvent(info) {
25
- return info.use === "schedule" && info.event?.type === "periodic";
26
- }
27
- export function isTaskCheckinEvent(info) {
28
- return info.use === "checkin" && info.event?.type === "one-shot";
29
- }