@oyasmi/pipiclaw 0.9.2-beta.6 → 0.9.3-beta.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 (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +14 -0
  40. package/dist/memory/render.js +28 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -4,22 +4,17 @@ import { discoverWorkspaceChannelIds } from "../channel/channel-index.js";
4
4
  import { dedupeChannelIdsByDirectory, getChannelDir, isChannelId } from "../channel/channel-paths.js";
5
5
  import * as log from "../log.js";
6
6
  import { PLAYBOOKS_DIR } from "../paths.js";
7
- import { parseLocalTime } from "../shared/local-time.js";
8
7
  import { errorMessage } from "../shared/text-utils.js";
9
- import { taskBudgetViolation } from "../tasks/control.js";
10
- import { normalizeTaskFields, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
11
- import { activateWaitingTask, escalateTask, openRecurringTaskCycle, updateStoredTask } from "../tasks/store.js";
12
- import { nextTaskWake } from "../tasks/task-schedule.js";
8
+ import { checkBudget, IDLE_STEP_LIMIT } from "../tasks/budget.js";
9
+ import { readActiveTasks } from "../tasks/ledger.js";
10
+ import { readTaskLog } from "../tasks/log.js";
11
+ import { expireTicket, openCycle, pauseTask, redeemTicket } from "../tasks/store.js";
13
12
  /** Short debounce so a burst of nudges collapses into a single rescan. */
14
13
  const NUDGE_DEBOUNCE_MS = 50;
15
14
  /** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
16
15
  const MIN_SLEEP_MS = 250;
17
- /** Consecutive no-progress wakes before the governor pauses a task (spec 029, D5). */
18
- const FUTILE_WAKE_LIMIT = 3;
19
- /** Wakes-per-cycle ceiling: a deliberately generous circuit breaker, not a normal governance
20
- * path (deadline and futileCount are). Guards only against a task that keeps "progressing"
21
- * without ever converging or hitting its deadline. */
22
- const MAX_WAKES_PER_CYCLE = 500;
16
+ /** A task dispatched this recently is assumed still in flight; do not queue it twice. */
17
+ const REDISPATCH_GUARD_MS = 30_000;
23
18
  /**
24
19
  * Channels this driver should scan. Live ids come first so a channel discovered on disk under
25
20
  * its escaped directory name never displaces the real id the runner map already knows.
@@ -33,158 +28,83 @@ export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
33
28
  function attemptKey(channelId, taskId) {
34
29
  return `${channelId}\0${taskId}`;
35
30
  }
36
- /**
37
- * What "this task moved" means to the driver.
38
- *
39
- * Do not use mtime/size here: routine frontmatter rewrites (status/note churn) must not read as
40
- * progress, or governed tasks would retry at the short continuation interval forever.
41
- *
42
- * `latestNote` is deliberately absent (spec 031, D7): it is the model's own account of its work,
43
- * so including it let a wake that did nothing but append a note reset the futile counter forever,
44
- * and let a wake that changed real files count as stalled. The task's own effect tally stands in
45
- * for the work itself instead — per task, not per channel, so a neighbour's activity (including
46
- * the user chatting) neither certifies progress here nor hides a task that is spinning.
47
- *
48
- * `entry.plan` is absent for the same reason (spec 037, D5): checking off a Plan step is a
49
- * model-reported claim, not evidence of an effect. If plan state fed the fingerprint, ticking a
50
- * checkbox would reset the futile counter and buy the short retry tier — a governor bypass this
51
- * driver must not offer. The Plan is a capsule/agenda display concern only.
52
- *
53
- * nextAction is also a model-written explanation, not evidence of an effect. Including it would
54
- * let a progress/set call reset the futile counter without changing the task's externally
55
- * observable work.
56
- */
57
- function taskFingerprint(entry, effects) {
58
- const control = entry.frontmatter.control;
59
- return [
60
- entry.frontmatter.readable ? "readable" : "unreadable",
61
- entry.frontmatter.status ?? "",
62
- entry.frontmatter.wake ?? "",
63
- entry.frontmatter.schedule ?? "",
64
- control?.verification.status ?? "",
65
- control?.waitingFor ?? "",
66
- entry.frontmatter.enabled === false ? "disabled" : "enabled",
67
- control?.stop?.reason ?? "",
68
- control?.cycleId ?? "",
69
- `effects:${effects}`,
70
- ].join("\0");
31
+ function channelType(channelId) {
32
+ return channelId.startsWith("group_")
33
+ ? { type: "group", conversationType: "2" }
34
+ : { type: "dm", conversationType: "1" };
71
35
  }
72
36
  /**
73
- * How long a task must wait after its last attempt, in three tiers.
74
- *
75
- * Backoff and cadence are different jobs, and one delay used to do both: any wake that changed
76
- * the ledger — including one that wrote code — waited out the same continuation delay as one that
77
- * only edited a note. A twenty-step task therefore spent well over an hour purely idle, which is
78
- * fatal for the "drive an external agent in small steps" shape this driver exists for.
79
- *
80
- * So the tiers are keyed on evidence, not on the boolean "something changed":
81
- * - this task's effect tally grew ⇒ its last wake actually did something ⇒ continue at once;
82
- * - the ledger changed with no effect (status/note churn) ⇒ the ordinary continuation delay;
83
- * - nothing changed ⇒ the long stalled-retry backoff, and the futile counter keeps running.
84
- *
85
- * Nothing here relaxes the stop-losses: the fast tier still counts toward `MAX_WAKES_PER_CYCLE`
86
- * and the futile-wake limit, so a task that spins productively-looking still hits the governor —
87
- * just sooner in wall time instead of an hour per step.
37
+ * Stable, provenance-derived dispatch id for a task step (spec 031, D1; spec 051 keeps the shape).
38
+ * A step inside a cycle is genuinely new work each time, so the dispatch moment disambiguates it;
39
+ * collapsing two steps onto one durable record would silently drop the later one.
88
40
  */
89
- function attemptDelayMs(attempt, fingerprint, effects, settings) {
90
- // A dispatch the channel refused never ran; retry it on the short delay regardless of state.
91
- if (!attempt.accepted)
92
- return settings.continuationDelayMinutes * 60_000;
93
- if (attempt.fingerprint === fingerprint)
94
- return settings.stalledRetryMinutes * 60_000;
95
- if (effects > attempt.effects)
96
- return 0;
97
- return settings.continuationDelayMinutes * 60_000;
98
- }
99
- function isEligible(attempt, fingerprint, effects, nowMs, settings) {
100
- if (!attempt)
101
- return true;
102
- return nowMs - attempt.atMs >= attemptDelayMs(attempt, fingerprint, effects, settings);
103
- }
104
- /**
105
- * Stable, provenance-derived dispatch id for a task wake (spec 031, D1).
106
- *
107
- * A scheduled task has a real occurrence — its `wake` — so retries of that occurrence collapse
108
- * onto one durable record. A task that is simply actionable has no occurrence identity, so the
109
- * dispatch time is used: two separate wakes of the same task are genuinely separate work, and
110
- * collapsing them would silently drop the later one.
111
- */
112
- function taskDispatchId(channelId, entry, nowMs) {
113
- const occurrence = entry.frontmatter.control?.cycleId ?? entry.frontmatter.wake ?? `t${nowMs}`;
114
- return `task:${channelId}:${entry.id}:${occurrence}`;
41
+ function stepDispatchId(channelId, entry, nowMs) {
42
+ return `task:${channelId}:${entry.id}:${entry.fields.cycle?.id ?? "-"}:${nowMs}`;
115
43
  }
116
44
  export function createTaskDriverEvent(channelId, entry, nowMs) {
117
- const repairOnly = !entry.frontmatter.readable || entry.frontmatter.controlReadable === false;
45
+ const repairOnly = !entry.readable || entry.legacy;
118
46
  const repair = repairOnly
119
- ? ` Task metadata is not readable; repair only the frontmatter/control in tasks/${entry.id}.md, then stop. ` +
120
- `Do not execute the task goal or any external action. Read ${join(PLAYBOOKS_DIR, "task-driving.md")} for the repair path.`
47
+ ? ` Task metadata is not readable; repair only the frontmatter in tasks/${entry.id}.md, then stop. ` +
48
+ `Do not execute the task goal or any external action. Read ${join(PLAYBOOKS_DIR, "task-loop.md")} for the repair path.`
121
49
  : "";
122
- const control = entry.frontmatter.control;
123
50
  const capsule = [
124
- `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "active"};`,
125
- // Surfacing the Plan's progress and current step here is the point of spec 037, D2/D4: the
126
- // model no longer has to re-derive "what step am I on" from latestNote/nextAction each wake.
51
+ `Task capsule: title=${entry.title}; state=${entry.fields.state};`,
52
+ entry.fields.cycle ? `cycle=${entry.fields.cycle.id} (${entry.fields.cycle.steps} steps);` : "",
127
53
  entry.plan
128
54
  ? `plan=${entry.plan.done}/${entry.plan.total} done, current=${entry.plan.current?.id ?? "none"};`
129
55
  : "",
130
- entry.latestNote ? `latest=${entry.latestNote};` : "",
131
- control?.nextAction ? `next=${control.nextAction};` : "",
132
56
  ]
133
57
  .filter(Boolean)
134
58
  .join(" ");
135
59
  return {
136
- type: channelId.startsWith("group_") ? "group" : "dm",
60
+ ...channelType(channelId),
137
61
  channelId,
138
62
  user: "TASK_DRIVER",
139
63
  userName: "TASK_DRIVER",
140
64
  text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
141
- `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-driving.md")} before acting. ` +
65
+ `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-loop.md")} before acting. ` +
142
66
  (repairOnly
143
- ? "After the metadata is repaired, leave task work for a later wake. "
144
- : "Advance the next concrete step under the task's current goal, control, acceptance, and verification state. ") +
145
- `If complete or waiting, use the matching task_close/task_update action from the playbook. ` +
146
- "For a recurring occurrence intentionally not run because it is duplicate or already satisfied, call task_close outcome=skip with the reason, then respond with exactly [SILENT]. " +
147
- "If no task state or tool action is needed and this wake produces no user-visible result, respond with exactly [SILENT].",
67
+ ? "After the metadata is repaired, leave task work for a later step. "
68
+ : "Advance the next concrete step under the task's current goal, plan and acceptance state. ") +
69
+ "End the step with task_step_end (continue / park / done / blocked).",
148
70
  ts: String(nowMs),
149
- conversationType: channelId.startsWith("group_") ? "2" : "1",
150
- dispatchId: taskDispatchId(channelId, entry, nowMs),
71
+ dispatchId: stepDispatchId(channelId, entry, nowMs),
151
72
  };
152
73
  }
153
- /** sleeping + a schedule cadence + a valid wake that is due → time to open the next cycle. */
154
- function isCycleStartReady(entry, nowMs) {
155
- return (entry.frontmatter.status === "sleeping" &&
156
- entry.frontmatter.enabled !== false &&
157
- Boolean(entry.frontmatter.schedule) &&
158
- entry.wakeMs !== undefined &&
159
- entry.wakeMs <= nowMs);
160
- }
161
- /** sleeping + schedule but no parseable wake → self-heal target (recompute wake, zero token). */
162
- function needsWakeHeal(entry) {
163
- return entry.frontmatter.status === "sleeping" && Boolean(entry.frontmatter.schedule) && entry.wakeMs === undefined;
164
- }
165
- export function taskGovernorReceipt(channelId, entry, reason, nowMs) {
74
+ /**
75
+ * The deterministic receipt a runtime stop produces (spec 051, D11). It is delivered directly,
76
+ * without opening a model turn: the user needs to know their task stopped, and spending an LLM
77
+ * call to phrase that is exactly the kind of cost this design removes.
78
+ */
79
+ export function taskStopReceipt(channelId, entry, reason, nowMs) {
166
80
  return {
167
- type: channelId.startsWith("group_") ? "group" : "dm",
81
+ ...channelType(channelId),
168
82
  channelId,
169
83
  user: "TASK_DRIVER",
170
84
  userName: "TASK_DRIVER",
171
85
  text: `任务 ${entry.id}(${entry.title})已停止自动执行:${reason}\n` +
172
- `当前阶段:${entry.frontmatter.status ?? "active"}${entry.frontmatter.control?.cycleId ? `;周期:${entry.frontmatter.control.cycleId}` : ""}\n` +
173
- `继续:/tasks resume ${entry.id}\n立即执行:/tasks run ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
86
+ `当前阶段:${entry.fields.state}${entry.fields.cycle ? `;周期:${entry.fields.cycle.id}` : ""}\n` +
87
+ `查看:/tasks show ${entry.id}\n继续:/tasks resume ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
174
88
  ts: String(nowMs),
175
- conversationType: channelId.startsWith("group_") ? "2" : "1",
176
- // Keyed on the cause, not the moment: re-detecting the same violation before the user has
177
- // acted must not queue a second identical escalation, while a different cause still does.
178
- dispatchId: `task:${channelId}:${entry.id}:escalation:${createHash("sha256").update(reason).digest("hex").slice(0, 12)}`,
89
+ // Keyed on the cause, not the moment: re-detecting the same stop before the user has acted
90
+ // must not queue a second identical receipt, while a different cause still does.
91
+ dispatchId: `task:${channelId}:${entry.id}:stop:${createHash("sha256").update(reason).digest("hex").slice(0, 12)}`,
179
92
  };
180
93
  }
181
94
  /**
182
- * Native, token-gated driver for the persistent task ledger.
95
+ * Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9).
96
+ *
97
+ * Four jobs, in this order per channel: redeem due `time`/`schedule` tickets, apply the backstop
98
+ * to expired ones, open cycles for recurring tasks, and queue one step for a runnable task.
99
+ * `run`/`job`/`ask`/`signal` tickets are never polled — their owners push them — so the scan
100
+ * stays a cheap read of a handful of frontmatters.
183
101
  *
184
- * The scan itself is deterministic and cheap. It wakes at most one actionable task
185
- * per channel, skips active channels, backs off unchanged ledgers, and round-robins
186
- * dispatches so a busy channel cannot starve the rest. `wake` is therefore sufficient
187
- * to resume a task; users do not need to install a heartbeat event or sensor script.
102
+ * What is deliberately *not* here any more: the ten-field ledger fingerprint, the process-local
103
+ * effect ledger, the futile-wake and wake-per-cycle counters, and the three-tier backoff table.
104
+ * They existed to guess whether a wake had accomplished anything; in production they fired twice
105
+ * in four months while the failure that actually happened — a task parked with no redeemable
106
+ * source, silent for 13 days — was invisible to all of them. Stopping is now the loop's own job
107
+ * (a budget it can see) and liveness is the ticket's (a backstop the runtime enforces).
188
108
  */
189
109
  export class TaskDriver {
190
110
  constructor(options) {
@@ -194,14 +114,12 @@ export class TaskDriver {
194
114
  this.loopActive = false;
195
115
  this.running = false;
196
116
  this.nextChannelIndex = 0;
197
- this.attempts = new Map();
117
+ /** Last dispatch time per task, so one in-flight step is not queued again on the next tick. */
118
+ this.lastDispatchMs = new Map();
198
119
  /**
199
- * Last task id dispatched per channel. Cross-channel fairness is handled by
200
- * `nextChannelIndex`, but within one channel every tick used to pick the first ready
201
- * candidate in sort order — an actively-progressing task keeps winning that slot forever,
202
- * starving every other ready task (including its own unlocked dependents) in the same
203
- * channel. Remembering the last pick and starting the search just after it gives ready
204
- * candidates in a channel the same round-robin fairness across ticks.
120
+ * Last task id dispatched per channel. Starting the search just after it gives every ready
121
+ * task in a channel the same round-robin fairness an actively-progressing task would
122
+ * otherwise monopolise.
205
123
  */
206
124
  this.lastDispatchedTaskId = new Map();
207
125
  }
@@ -232,9 +150,9 @@ export class TaskDriver {
232
150
  }
233
151
  }
234
152
  /**
235
- * In-process wake: after a turn ends or a task file is written, re-scan promptly instead
236
- * of waiting out the current sleep. The timer is a hint; the scan re-reads every file, so
237
- * a stale or missed nudge only costs one capped sleep of latency, never correctness.
153
+ * In-process wake: after a step ends or a task file is written, re-scan promptly instead of
154
+ * waiting out the current sleep. This is what makes `outcome: continue` cost nothing — the
155
+ * next step is queued on the same nudge rather than after a continuation delay.
238
156
  */
239
157
  nudge() {
240
158
  if (!this.loopActive || this.nudgeTimer)
@@ -278,36 +196,91 @@ export class TaskDriver {
278
196
  if (this.nextWakeMs === undefined || candidate < this.nextWakeMs)
279
197
  this.nextWakeMs = candidate;
280
198
  }
281
- collectHorizons(entries, nowMs) {
199
+ /** Stop one task and notify. Delivery failure is logged, never fatal: the durable stop already happened. */
200
+ async notifyStop(channelId, entry, reason, nowMs) {
201
+ try {
202
+ await this.options.notify?.(taskStopReceipt(channelId, entry, reason, nowMs));
203
+ }
204
+ catch (error) {
205
+ log.logWarning(`[${channelId}] Task stop receipt failed`, errorMessage(error));
206
+ }
207
+ }
208
+ /**
209
+ * Deterministic, zero-token maintenance for one channel: redeem due tickets, apply expiry
210
+ * backstops, open recurring cycles. Runs whether or not the channel is busy — only model
211
+ * dispatch is gated on an idle channel.
212
+ */
213
+ async maintain(channelDir, channelId, entries, now) {
214
+ const nowMs = now.getTime();
215
+ let changed = false;
282
216
  for (const entry of entries) {
283
- if (entry.frontmatter.enabled !== false)
284
- this.noteHorizon(entry.wakeMs, nowMs);
285
- const control = entry.frontmatter.control;
286
- if (entry.frontmatter.enabled !== false &&
287
- control?.deadline &&
288
- (entry.frontmatter.status === "active" || entry.frontmatter.status === "waiting") &&
289
- !entry.frontmatter.archiveOutcome) {
290
- this.noteHorizon(parseLocalTime(control.deadline), nowMs);
217
+ if (entry.fields.paused || entry.fields.state !== "parked")
218
+ continue;
219
+ const ticket = entry.fields.ticket;
220
+ if (!ticket)
221
+ continue;
222
+ // A due timer redeems into an open task; a due schedule opens the next cycle outright.
223
+ if (entry.dueMs !== undefined && entry.dueMs <= nowMs) {
224
+ if (ticket.kind === "schedule") {
225
+ const opened = await openCycle(channelDir, entry.id, now).catch((error) => {
226
+ log.logWarning(`[${channelId}] Could not open next cycle for ${entry.id}`, errorMessage(error));
227
+ return undefined;
228
+ });
229
+ if (opened) {
230
+ changed = true;
231
+ log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
232
+ }
233
+ }
234
+ else if (await redeemTicket(channelDir, entry.id, (current) => current.kind === ticket.kind)) {
235
+ changed = true;
236
+ }
237
+ continue;
291
238
  }
239
+ if (entry.expired) {
240
+ const expiry = await expireTicket(channelDir, entry.id);
241
+ if (!expiry)
242
+ continue;
243
+ changed = true;
244
+ if (expiry.outcome === "paused") {
245
+ log.logWarning(`[${channelId}] Task ${entry.id} paused: ticket expired twice`, expiry.ticket);
246
+ await this.notifyStop(channelId, entry, `等待未兑现(${expiry.ticket}),已连续两次超过兜底时限`, nowMs);
247
+ }
248
+ else {
249
+ log.logInfo(`[${channelId}] Task ${entry.id} reopened after its ticket expired`, expiry.ticket);
250
+ }
251
+ continue;
252
+ }
253
+ this.noteHorizon(entry.dueMs, nowMs);
254
+ this.noteHorizon(new Date(ticket.by).getTime(), nowMs);
292
255
  }
256
+ return changed;
293
257
  }
294
258
  /**
295
- * Escalate one task to the governor and best-effort notify, returning whether it actually
296
- * escalated (a caller only needs to react — reset attempt state, log — when it did). The
297
- * notify failure itself is never fatal to the escalation: `escalateTask` already made the
298
- * durable disable; a delivery hiccup is logged and swallowed, not retried here.
259
+ * Stop a loop that is talking to itself: two consecutive steps that produced no tool call at
260
+ * all. This is the honest replacement for v3's futile-wake counter — the loop log records what
261
+ * each step actually did, so "no progress" is an observed fact rather than a fingerprint
262
+ * comparison a `echo x` could defeat.
299
263
  */
300
- async escalateAndNotify(channelDir, channelId, entry, reason, nowMs) {
301
- if (!(await escalateTask(channelDir, entry.id, reason)))
302
- return false;
303
- const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
304
- try {
305
- await this.options.notify?.(receipt);
306
- }
307
- catch (error) {
308
- log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
264
+ async detectIdleLoop(channelDir, channelId, entries, nowMs) {
265
+ let paused = false;
266
+ for (const entry of entries) {
267
+ const cycle = entry.fields.cycle;
268
+ if (!cycle || cycle.steps < IDLE_STEP_LIMIT)
269
+ continue;
270
+ const steps = (await readTaskLog(channelDir, entry.id, { cycle: cycle.id, kinds: ["step"] })).slice(-IDLE_STEP_LIMIT);
271
+ if (steps.length < IDLE_STEP_LIMIT)
272
+ continue;
273
+ const idle = steps.every((record) => record.kind === "step" && record.tools.length === 0);
274
+ if (!idle)
275
+ continue;
276
+ const reason = `连续 ${IDLE_STEP_LIMIT} 步没有任何工具调用,循环已停下等你确认`;
277
+ if (await pauseTask(channelDir, entry.id, { by: "runtime", reason })) {
278
+ paused = true;
279
+ log.logWarning(`[${channelId}] Task ${entry.id} paused: idle loop`, reason);
280
+ await this.notifyStop(channelId, entry, reason, nowMs);
281
+ }
309
282
  }
310
- return true;
283
+ return paused;
311
284
  }
312
285
  async runOnce(now = new Date()) {
313
286
  if (this.options.isEnabled?.() === false || this.running)
@@ -319,7 +292,7 @@ export class TaskDriver {
319
292
  try {
320
293
  const channels = await discoverTaskChannels(this.options.workspaceDir, this.options.getKnownChannelIds?.());
321
294
  if (channels.length === 0) {
322
- this.attempts.clear();
295
+ this.lastDispatchMs.clear();
323
296
  return;
324
297
  }
325
298
  const seen = new Set();
@@ -336,166 +309,56 @@ export class TaskDriver {
336
309
  let entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
337
310
  for (const entry of entries)
338
311
  seen.add(attemptKey(channelId, entry.id));
339
- this.collectHorizons(entries, nowMs);
340
- for (const entry of entries) {
341
- if (entry.frontmatter.enabled !== false &&
342
- recurringTaskMissedOccurrence({
343
- status: entry.frontmatter.status ?? "active",
344
- schedule: entry.frontmatter.schedule,
345
- control: entry.frontmatter.control,
346
- }, now)) {
347
- log.logWarning(`[${channelId}] Task ${entry.id} has a missed recurring occurrence; keeping the current cycle open`);
348
- }
312
+ if (await this.maintain(channelDir, channelId, entries, now)) {
313
+ entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
349
314
  }
350
- // Zero-token self-heal: a sleeping recurring task with a missing/unparseable wake (usually a
351
- // hand edit that bypassed the runtime) gets its next occurrence recomputed via the same
352
- // `normalizeTaskFields` write-path invariant, rather than fail-open into an accidental cycle.
315
+ if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
316
+ continue;
317
+ // A task that has already run out of budget must not spend one more model call to
318
+ // discover that (D6). Checked before dispatch, and paired with a receipt so the user
319
+ // learns why it stopped and what to type to give it more rope.
320
+ const budgeted = [];
353
321
  for (const entry of entries) {
354
- if (entry.frontmatter.status !== "sleeping" || entry.frontmatter.enabled === false)
322
+ if (!entry.runnable)
355
323
  continue;
356
- if (!entry.frontmatter.schedule) {
357
- await this.escalateAndNotify(channelDir, channelId, entry, "sleeping recurring task has no schedule", nowMs);
324
+ const status = checkBudget(entry.fields, now);
325
+ if (!status.breach || !status.reason) {
326
+ budgeted.push(entry);
358
327
  continue;
359
328
  }
360
- const scheduleWake = nextTaskWake(entry.frontmatter.schedule, now);
361
- if (!scheduleWake) {
362
- await this.escalateAndNotify(channelDir, channelId, entry, `sleeping task has invalid schedule: ${entry.frontmatter.schedule}`, nowMs);
363
- continue;
329
+ if (await pauseTask(channelDir, entry.id, { by: "runtime", reason: status.reason })) {
330
+ log.logWarning(`[${channelId}] Task ${entry.id} paused: budget ${status.breach}`, status.reason);
331
+ await this.notifyStop(channelId, entry, status.reason, nowMs);
364
332
  }
365
- if (!needsWakeHeal(entry))
366
- continue;
367
- let healedWake;
368
- await updateStoredTask(channelDir, entry.id, (task) => {
369
- healedWake = normalizeTaskFields(task.fields, now).wake;
370
- task.fields.wake = healedWake;
371
- });
372
- if (!healedWake) {
373
- log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
374
- continue;
375
- }
376
- this.noteHorizon(new Date(healedWake).getTime(), nowMs);
377
- log.logInfo(`[${channelId}] Task driver healed wake for ${entry.id}`, healedWake);
378
333
  }
379
- let governanceHandled = false;
380
- for (const candidate of entries) {
381
- const status = candidate.frontmatter.status;
382
- const control = candidate.frontmatter.control;
383
- if (!control || candidate.frontmatter.archiveOutcome || candidate.frontmatter.enabled === false)
384
- continue;
385
- const escalationReason = taskBudgetViolation(control, nowMs, status);
386
- if (!escalationReason)
387
- continue;
388
- governanceHandled = true;
389
- if (await this.escalateAndNotify(channelDir, channelId, candidate, escalationReason, nowMs)) {
390
- log.logWarning(`[${channelId}] Task driver disabled ${candidate.id} (governor)`, escalationReason);
391
- }
392
- break;
393
- }
394
- if (governanceHandled)
395
- continue;
396
- // Deterministic maintenance above must not wait for an idle channel. Only model dispatch
397
- // and the transitions immediately preceding it are gated by the channel's busy state.
398
- if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
399
- continue;
400
- // Timed waits become active atomically before dispatch. Sleeping due tasks use the same
401
- // runtime cycle-open path as the first occurrence.
402
- let hadDueWaiting = false;
403
- for (const candidate of entries) {
404
- if (candidate.frontmatter.status !== "waiting" || candidate.frontmatter.enabled === false)
405
- continue;
406
- if (candidate.wakeMs !== undefined && candidate.wakeMs <= nowMs) {
407
- hadDueWaiting = true;
408
- await activateWaitingTask(channelDir, candidate.id);
409
- }
410
- }
411
- // A failed activation means another writer won the transition (or disabled the
412
- // task). Re-read before choosing a candidate so a stale waiting capsule can never
413
- // be dispatched as if its atomic active transition had succeeded.
414
- if (hadDueWaiting)
415
- entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
416
- // Actionable tasks and cycle-start-ready recurring tasks share one per-channel slot
417
- // and the same round-robin fairness. A cycle-start-ready task is folded into its next
418
- // cycle deterministically by the runtime (D2) and then dispatched as an ordinary wake.
419
- const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
334
+ const idled = await this.detectIdleLoop(channelDir, channelId, budgeted, nowMs);
335
+ const ready = idled
336
+ ? (await readActiveTasks(join(channelDir, "tasks"), nowMs)).filter((entry) => entry.runnable)
337
+ : budgeted;
338
+ const candidates = ready.filter((entry) => !entry.fields.paused);
420
339
  if (candidates.length === 0)
421
340
  continue;
422
341
  const lastId = this.lastDispatchedTaskId.get(channelId);
423
342
  const lastIndex = lastId ? candidates.findIndex((candidate) => candidate.id === lastId) : -1;
424
- const rotatedCandidates = lastIndex >= 0
343
+ const rotated = lastIndex >= 0
425
344
  ? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
426
345
  : candidates;
427
- let entry = rotatedCandidates[0];
428
- if (!entry || dispatched >= settings.maxDispatchesPerTick)
429
- continue;
430
- // A cycle-start-ready recurring task is reopened in-process before dispatch: fold the
431
- // previous cycle, reset per-cycle control, mark it active. If the write fails we skip
432
- // this tick rather than dispatch a stale sleeping capsule.
433
- if (isCycleStartReady(entry, nowMs)) {
434
- let opened;
435
- try {
436
- opened = await openRecurringTaskCycle(channelDir, entry.id, now);
437
- }
438
- catch (error) {
439
- // A malformed recurring body (e.g. missing History) must not stall the whole tick.
440
- log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`, errorMessage(error));
441
- continue;
442
- }
443
- if (!opened) {
444
- log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`);
445
- continue;
446
- }
447
- // Re-read after the atomic open so the capsule contains the new Current Cycle/Plan,
448
- // rather than the sleeping occurrence's just-closed note.
449
- const refreshed = (await readActiveTasks(join(channelDir, "tasks"), nowMs)).find((candidate) => candidate.id === entry?.id);
450
- entry = refreshed ?? {
451
- ...entry,
452
- frontmatter: {
453
- ...entry.frontmatter,
454
- status: "active",
455
- wake: undefined,
456
- control: opened.document.fields.control,
457
- },
458
- wakeMs: undefined,
459
- actionable: true,
460
- };
461
- log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
462
- }
463
- const key = attemptKey(channelId, entry.id);
464
- const repairOnly = !entry.frontmatter.readable || entry.frontmatter.controlReadable === false;
465
- const effects = this.options.getEffectCount?.(channelId, entry.id) ?? 0;
466
- const fingerprint = taskFingerprint(entry, effects);
467
- const previous = this.attempts.get(key);
468
- if (!isEligible(previous, fingerprint, effects, nowMs, settings))
469
- continue;
470
- // D5: a wake that was accepted and left the ledger fingerprint unchanged made no
471
- // visible progress. Count consecutive such wakes (a changed fingerprint — including
472
- // a progress note or a failure — resets the count); after the limit the governor
473
- // pauses the task and notifies the user, so no silent loop burns tokens forever.
474
- const futileCount = !repairOnly && previous?.accepted && previous.fingerprint === fingerprint ? previous.futileCount + 1 : 0;
475
- if (futileCount >= FUTILE_WAKE_LIMIT) {
476
- const reason = `task made no visible progress in ${FUTILE_WAKE_LIMIT} consecutive wakes`;
477
- if (await this.escalateAndNotify(channelDir, channelId, entry, reason, nowMs)) {
478
- this.attempts.delete(key);
479
- this.lastDispatchedTaskId.set(channelId, entry.id);
480
- log.logWarning(`[${channelId}] Task driver disabled ${entry.id} (governor)`, reason);
481
- }
482
- continue;
483
- }
484
- const cycleId = entry.frontmatter.control?.cycleId;
485
- const wakeCount = !repairOnly && previous && previous.cycleId === cycleId ? previous.wakeCount + 1 : 1;
486
- if (wakeCount > MAX_WAKES_PER_CYCLE) {
487
- const reason = `task exceeded ${MAX_WAKES_PER_CYCLE} wakes in this cycle (runaway failsafe)`;
488
- if (await this.escalateAndNotify(channelDir, channelId, entry, reason, nowMs)) {
489
- this.attempts.delete(key);
490
- this.lastDispatchedTaskId.set(channelId, entry.id);
491
- log.logWarning(`[${channelId}] Task driver disabled ${entry.id} (governor)`, reason);
346
+ const entry = rotated.find((candidate) => {
347
+ const previous = this.lastDispatchMs.get(attemptKey(channelId, candidate.id));
348
+ return previous === undefined || nowMs - previous >= REDISPATCH_GUARD_MS;
349
+ });
350
+ if (!entry) {
351
+ for (const candidate of rotated) {
352
+ const previous = this.lastDispatchMs.get(attemptKey(channelId, candidate.id));
353
+ if (previous !== undefined)
354
+ this.noteHorizon(previous + REDISPATCH_GUARD_MS, nowMs);
492
355
  }
493
356
  continue;
494
357
  }
495
358
  const event = createTaskDriverEvent(channelId, entry, nowMs);
496
359
  const accepted = await this.options.dispatch(event);
497
360
  this.observeDispatch(event, accepted);
498
- this.attempts.set(key, { fingerprint, atMs: nowMs, accepted, effects, futileCount, wakeCount, cycleId });
361
+ this.lastDispatchMs.set(attemptKey(channelId, entry.id), nowMs);
499
362
  this.lastDispatchedTaskId.set(channelId, entry.id);
500
363
  if (accepted) {
501
364
  dispatched++;
@@ -506,19 +369,9 @@ export class TaskDriver {
506
369
  log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
507
370
  }
508
371
  }
509
- for (const key of this.attempts.keys()) {
372
+ for (const key of this.lastDispatchMs.keys()) {
510
373
  if (!seen.has(key))
511
- this.attempts.delete(key);
512
- }
513
- // A backed-off task becomes eligible again at attempt time + its retry delay; wake then
514
- // so an unchanged ledger is still retried without polling. Changed ledgers arrive via
515
- // nudge. Both tiers are noted because which one applies depends on the ledger as it will
516
- // be *then*: `noteHorizon` keeps whichever is next in the future, so the short tier is
517
- // honored on time and the long one is still not missed.
518
- for (const attempt of this.attempts.values()) {
519
- this.noteHorizon(attempt.atMs + settings.continuationDelayMinutes * 60_000, nowMs);
520
- if (attempt.accepted)
521
- this.noteHorizon(attempt.atMs + settings.stalledRetryMinutes * 60_000, nowMs);
374
+ this.lastDispatchMs.delete(key);
522
375
  }
523
376
  const channelSet = new Set(channels);
524
377
  for (const channelId of this.lastDispatchedTaskId.keys()) {