@oyasmi/pipiclaw 0.8.7 → 0.8.8-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.
- package/README.md +14 -14
- package/dist/models/api-keys.js +1 -1
- package/dist/paths.d.ts +8 -0
- package/dist/paths.js +9 -1
- package/dist/playbooks/event-scheduling.md +3 -3
- package/dist/playbooks/task-closeout.md +2 -2
- package/dist/playbooks/task-recurring.md +14 -17
- package/dist/playbooks/task-repair.md +1 -1
- package/dist/runtime/bootstrap.d.ts +3 -2
- package/dist/runtime/bootstrap.js +33 -6
- package/dist/runtime/event-commands.js +1 -3
- package/dist/runtime/events.d.ts +6 -2
- package/dist/runtime/events.js +15 -6
- package/dist/runtime/task-commands.js +25 -6
- package/dist/runtime/task-driver.d.ts +33 -0
- package/dist/runtime/task-driver.js +204 -32
- package/dist/settings.d.ts +2 -0
- package/dist/settings.js +5 -0
- package/dist/shared/task-ledger.d.ts +3 -0
- package/dist/shared/task-ledger.js +41 -1
- package/dist/shared/task-schedule.d.ts +18 -0
- package/dist/shared/task-schedule.js +50 -0
- package/dist/tasks/store.js +1 -0
- package/dist/tools/event-manage.js +6 -10
- package/dist/tools/task-manage.d.ts +2 -0
- package/dist/tools/task-manage.js +84 -9
- package/dist/tui/app.js +1 -1
- package/package.json +1 -1
|
@@ -1,13 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import * as log from "../log.js";
|
|
4
5
|
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
6
|
+
import { isTaskScheduleEvent, taskScheduleEventFilename } from "../shared/task-events.js";
|
|
5
7
|
import { readActiveTasks } from "../shared/task-ledger.js";
|
|
8
|
+
import { nextTaskWake } from "../shared/task-schedule.js";
|
|
6
9
|
import { errorMessage } from "../shared/text-utils.js";
|
|
7
10
|
import { taskBudgetViolation } from "../tasks/control.js";
|
|
8
|
-
import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim } from "../tasks/store.js";
|
|
9
|
-
|
|
11
|
+
import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
|
|
12
|
+
import { parseScheduledEventContent } from "./events.js";
|
|
13
|
+
/** Short debounce so a burst of nudges collapses into a single rescan. */
|
|
14
|
+
const NUDGE_DEBOUNCE_MS = 50;
|
|
15
|
+
/** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
|
|
16
|
+
const MIN_SLEEP_MS = 250;
|
|
10
17
|
const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
|
|
18
|
+
const TERMINAL_STATUSES = new Set(["done", "cancelled", "escalated", "paused"]);
|
|
11
19
|
function isChannelId(value) {
|
|
12
20
|
return CHANNEL_ID_PATTERN.test(value);
|
|
13
21
|
}
|
|
@@ -41,6 +49,7 @@ async function taskFingerprint(_channelDir, entry) {
|
|
|
41
49
|
entry.frontmatter.readable ? "readable" : "unreadable",
|
|
42
50
|
entry.frontmatter.status ?? "",
|
|
43
51
|
entry.frontmatter.wake ?? "",
|
|
52
|
+
entry.frontmatter.schedule ?? "",
|
|
44
53
|
entry.frontmatter.recurrence ?? "",
|
|
45
54
|
entry.latestNote ?? "",
|
|
46
55
|
control?.nextAction ?? "",
|
|
@@ -89,6 +98,37 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
|
89
98
|
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
90
99
|
};
|
|
91
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* A done recurring task whose schedule has come due. This is the one place the driver
|
|
103
|
+
* wakes a `done` task: to open its next cycle. It uses a `[TASK_CYCLE:...]` tag (not
|
|
104
|
+
* `[TASK_DRIVER:...]`) so the turn is not charged an attempt — start-cycle resets usage
|
|
105
|
+
* anyway, matching the retired periodic-event flow.
|
|
106
|
+
*/
|
|
107
|
+
export function createCycleStartEvent(channelId, entry, nowMs) {
|
|
108
|
+
return {
|
|
109
|
+
type: channelId.startsWith("group_") ? "group" : "dm",
|
|
110
|
+
channelId,
|
|
111
|
+
user: "TASK_DRIVER",
|
|
112
|
+
userName: "TASK_DRIVER",
|
|
113
|
+
text: `[TASK_CYCLE:${entry.id}] Start a new cycle for task ${entry.id} (${entry.title}). ` +
|
|
114
|
+
`Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-recurring.md")}, then use ` +
|
|
115
|
+
"task_manage start-cycle with a stable cycleId to fold the previous cycle and begin work.",
|
|
116
|
+
ts: String(nowMs),
|
|
117
|
+
conversationId: "",
|
|
118
|
+
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** status done + a schedule cadence + a valid wake that is due. */
|
|
122
|
+
function isCycleStartReady(entry, nowMs) {
|
|
123
|
+
return (entry.frontmatter.status === "done" &&
|
|
124
|
+
Boolean(entry.frontmatter.schedule) &&
|
|
125
|
+
entry.wakeMs !== undefined &&
|
|
126
|
+
entry.wakeMs <= nowMs);
|
|
127
|
+
}
|
|
128
|
+
/** done + schedule but no parseable wake → self-heal target (recompute wake, zero token). */
|
|
129
|
+
function needsWakeHeal(entry) {
|
|
130
|
+
return entry.frontmatter.status === "done" && Boolean(entry.frontmatter.schedule) && entry.wakeMs === undefined;
|
|
131
|
+
}
|
|
92
132
|
function taskEscalationEvent(channelId, entry, reason, nowMs) {
|
|
93
133
|
return {
|
|
94
134
|
type: channelId.startsWith("group_") ? "group" : "dm",
|
|
@@ -123,31 +163,114 @@ export class TaskDriver {
|
|
|
123
163
|
constructor(options) {
|
|
124
164
|
this.options = options;
|
|
125
165
|
this.timer = null;
|
|
166
|
+
this.nudgeTimer = null;
|
|
167
|
+
this.loopActive = false;
|
|
126
168
|
this.running = false;
|
|
127
169
|
this.nextChannelIndex = 0;
|
|
128
170
|
this.attempts = new Map();
|
|
171
|
+
/**
|
|
172
|
+
* Last task id dispatched per channel. Cross-channel fairness is handled by
|
|
173
|
+
* `nextChannelIndex`, but within one channel every tick used to pick the first ready
|
|
174
|
+
* candidate in sort order — an actively-progressing task keeps winning that slot forever,
|
|
175
|
+
* starving every other ready task (including its own unlocked dependents) in the same
|
|
176
|
+
* channel. Remembering the last pick and starting the search just after it gives ready
|
|
177
|
+
* candidates in a channel the same round-robin fairness across ticks.
|
|
178
|
+
*/
|
|
179
|
+
this.lastDispatchedTaskId = new Map();
|
|
129
180
|
}
|
|
130
181
|
start() {
|
|
131
|
-
if (this.
|
|
182
|
+
if (this.loopActive)
|
|
132
183
|
return;
|
|
133
|
-
this.
|
|
134
|
-
|
|
135
|
-
log.logWarning("Task driver tick failed", errorMessage(error));
|
|
136
|
-
});
|
|
137
|
-
}, this.options.intervalMs ?? DEFAULT_SCAN_INTERVAL_MS);
|
|
138
|
-
this.timer.unref?.();
|
|
184
|
+
this.loopActive = true;
|
|
185
|
+
void this.tick();
|
|
139
186
|
}
|
|
140
187
|
stop() {
|
|
141
|
-
|
|
188
|
+
this.loopActive = false;
|
|
189
|
+
if (this.timer) {
|
|
190
|
+
clearTimeout(this.timer);
|
|
191
|
+
this.timer = null;
|
|
192
|
+
}
|
|
193
|
+
if (this.nudgeTimer) {
|
|
194
|
+
clearTimeout(this.nudgeTimer);
|
|
195
|
+
this.nudgeTimer = null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* In-process wake: after a turn ends or a task file is written, re-scan promptly instead
|
|
200
|
+
* of waiting out the current sleep. The timer is a hint; the scan re-reads every file, so
|
|
201
|
+
* a stale or missed nudge only costs one capped sleep of latency, never correctness.
|
|
202
|
+
*/
|
|
203
|
+
nudge() {
|
|
204
|
+
if (!this.loopActive || this.nudgeTimer)
|
|
142
205
|
return;
|
|
143
|
-
|
|
144
|
-
|
|
206
|
+
if (this.timer) {
|
|
207
|
+
clearTimeout(this.timer);
|
|
208
|
+
this.timer = null;
|
|
209
|
+
}
|
|
210
|
+
this.nudgeTimer = setTimeout(() => {
|
|
211
|
+
this.nudgeTimer = null;
|
|
212
|
+
void this.tick();
|
|
213
|
+
}, NUDGE_DEBOUNCE_MS);
|
|
214
|
+
this.nudgeTimer.unref?.();
|
|
215
|
+
}
|
|
216
|
+
async tick() {
|
|
217
|
+
try {
|
|
218
|
+
await this.runOnce();
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
log.logWarning("Task driver tick failed", errorMessage(error));
|
|
222
|
+
}
|
|
223
|
+
this.scheduleNext();
|
|
224
|
+
}
|
|
225
|
+
scheduleNext() {
|
|
226
|
+
if (!this.loopActive || this.timer || this.nudgeTimer)
|
|
227
|
+
return;
|
|
228
|
+
const settings = this.options.getSettings();
|
|
229
|
+
const capMs = this.options.intervalMs ?? settings.maxSleepMinutes * 60_000;
|
|
230
|
+
const untilNext = this.nextWakeMs !== undefined ? this.nextWakeMs - Date.now() : Number.POSITIVE_INFINITY;
|
|
231
|
+
const sleepMs = Math.max(MIN_SLEEP_MS, Math.min(capMs, untilNext));
|
|
232
|
+
this.timer = setTimeout(() => {
|
|
233
|
+
this.timer = null;
|
|
234
|
+
void this.tick();
|
|
235
|
+
}, sleepMs);
|
|
236
|
+
this.timer.unref?.();
|
|
237
|
+
}
|
|
238
|
+
/** Fold `candidate` into the earliest interesting wake moment. */
|
|
239
|
+
noteHorizon(candidate, nowMs) {
|
|
240
|
+
if (candidate === undefined || !Number.isFinite(candidate) || candidate <= nowMs)
|
|
241
|
+
return;
|
|
242
|
+
if (this.nextWakeMs === undefined || candidate < this.nextWakeMs)
|
|
243
|
+
this.nextWakeMs = candidate;
|
|
244
|
+
}
|
|
245
|
+
collectHorizons(entries, nowMs) {
|
|
246
|
+
for (const entry of entries) {
|
|
247
|
+
this.noteHorizon(entry.wakeMs, nowMs);
|
|
248
|
+
const control = entry.frontmatter.control;
|
|
249
|
+
if (control?.deadline && !TERMINAL_STATUSES.has(entry.frontmatter.status ?? "")) {
|
|
250
|
+
this.noteHorizon(new Date(control.deadline).getTime(), nowMs);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
async hasLiveScheduleEvent(channelId, id) {
|
|
255
|
+
const filename = taskScheduleEventFilename(channelId, id);
|
|
256
|
+
const eventPath = join(this.options.workspaceDir, "events", filename);
|
|
257
|
+
if (!existsSync(eventPath))
|
|
258
|
+
return false;
|
|
259
|
+
try {
|
|
260
|
+
const type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename).type;
|
|
261
|
+
return isTaskScheduleEvent({ use: "schedule", event: { type } });
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
145
266
|
}
|
|
146
267
|
async runOnce(now = new Date()) {
|
|
147
268
|
if (this.options.isEnabled?.() === false || this.running)
|
|
148
269
|
return;
|
|
149
270
|
const settings = this.options.getSettings();
|
|
271
|
+
const nowMs = now.getTime();
|
|
150
272
|
this.running = true;
|
|
273
|
+
this.nextWakeMs = undefined;
|
|
151
274
|
try {
|
|
152
275
|
const channels = await discoverTaskChannels(this.options.workspaceDir, this.options.getKnownChannelIds?.());
|
|
153
276
|
if (channels.length === 0) {
|
|
@@ -163,27 +286,41 @@ export class TaskDriver {
|
|
|
163
286
|
if (!channelId)
|
|
164
287
|
continue;
|
|
165
288
|
const channelDir = join(this.options.workspaceDir, channelId);
|
|
166
|
-
const entries = await readActiveTasks(join(channelDir, "tasks"),
|
|
289
|
+
const entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
|
|
167
290
|
for (const entry of entries)
|
|
168
291
|
seen.add(attemptKey(channelId, entry.id));
|
|
292
|
+
this.collectHorizons(entries, nowMs);
|
|
169
293
|
if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
|
|
170
294
|
continue;
|
|
295
|
+
// Zero-token self-heal: a done recurring task with a missing/unparseable wake gets
|
|
296
|
+
// its next occurrence recomputed deterministically rather than fail-open into an
|
|
297
|
+
// accidental cycle.
|
|
298
|
+
for (const entry of entries) {
|
|
299
|
+
if (!needsWakeHeal(entry))
|
|
300
|
+
continue;
|
|
301
|
+
const next = nextTaskWake(entry.frontmatter.schedule, now);
|
|
302
|
+
if (!next) {
|
|
303
|
+
log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
await updateStoredTask(channelDir, entry.id, (task) => {
|
|
307
|
+
task.fields.wake = next.toISOString();
|
|
308
|
+
});
|
|
309
|
+
this.noteHorizon(next.getTime(), nowMs);
|
|
310
|
+
log.logInfo(`[${channelId}] Task driver healed wake for ${entry.id}`, next.toISOString());
|
|
311
|
+
}
|
|
171
312
|
let governanceHandled = false;
|
|
172
313
|
for (const candidate of entries) {
|
|
173
314
|
const status = candidate.frontmatter.status;
|
|
174
315
|
const control = candidate.frontmatter.control;
|
|
175
|
-
if (!control ||
|
|
176
|
-
status === "done" ||
|
|
177
|
-
status === "cancelled" ||
|
|
178
|
-
status === "escalated" ||
|
|
179
|
-
status === "paused")
|
|
316
|
+
if (!control || TERMINAL_STATUSES.has(status ?? ""))
|
|
180
317
|
continue;
|
|
181
318
|
const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
|
|
182
|
-
const escalationReason = taskBudgetViolation(control,
|
|
319
|
+
const escalationReason = taskBudgetViolation(control, nowMs) ?? terminalDependencyReason(dependencies.reason);
|
|
183
320
|
if (!escalationReason)
|
|
184
321
|
continue;
|
|
185
322
|
governanceHandled = true;
|
|
186
|
-
const accepted = await this.options.dispatch(taskEscalationEvent(channelId, candidate, escalationReason,
|
|
323
|
+
const accepted = await this.options.dispatch(taskEscalationEvent(channelId, candidate, escalationReason, nowMs));
|
|
187
324
|
if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
|
|
188
325
|
dispatched++;
|
|
189
326
|
lastDispatchOffset = offset;
|
|
@@ -193,40 +330,64 @@ export class TaskDriver {
|
|
|
193
330
|
}
|
|
194
331
|
if (governanceHandled)
|
|
195
332
|
continue;
|
|
196
|
-
|
|
333
|
+
// Actionable tasks and cycle-start-ready recurring tasks share one per-channel slot
|
|
334
|
+
// and the same round-robin fairness; only the dispatch text and attempt accounting differ.
|
|
335
|
+
const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
|
|
197
336
|
if (candidates.length === 0)
|
|
198
337
|
continue;
|
|
338
|
+
const lastId = this.lastDispatchedTaskId.get(channelId);
|
|
339
|
+
const lastIndex = lastId ? candidates.findIndex((candidate) => candidate.id === lastId) : -1;
|
|
340
|
+
const rotatedCandidates = lastIndex >= 0
|
|
341
|
+
? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
|
|
342
|
+
: candidates;
|
|
199
343
|
let entry;
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
if (
|
|
344
|
+
let isCycleStart = false;
|
|
345
|
+
for (const candidate of rotatedCandidates) {
|
|
346
|
+
if (candidate.actionable) {
|
|
347
|
+
const control = candidate.frontmatter.control;
|
|
348
|
+
if (control) {
|
|
349
|
+
const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
|
|
350
|
+
if (!dependencies.ready)
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
203
353
|
entry = candidate;
|
|
354
|
+
isCycleStart = false;
|
|
204
355
|
break;
|
|
205
356
|
}
|
|
206
|
-
|
|
207
|
-
|
|
357
|
+
// Migration compat: while a parseable legacy `.schedule` event still owns the
|
|
358
|
+
// cadence, defer to it so the cycle is not opened twice.
|
|
359
|
+
if (await this.hasLiveScheduleEvent(channelId, candidate.id))
|
|
208
360
|
continue;
|
|
209
361
|
entry = candidate;
|
|
362
|
+
isCycleStart = true;
|
|
210
363
|
break;
|
|
211
364
|
}
|
|
212
365
|
if (!entry || dispatched >= settings.maxDispatchesPerTick)
|
|
213
366
|
continue;
|
|
214
367
|
const key = attemptKey(channelId, entry.id);
|
|
215
368
|
let fingerprint = await taskFingerprint(channelDir, entry);
|
|
216
|
-
if (!isEligible(this.attempts.get(key), fingerprint,
|
|
369
|
+
if (!isEligible(this.attempts.get(key), fingerprint, nowMs, settings))
|
|
217
370
|
continue;
|
|
218
|
-
|
|
371
|
+
// Cycle-start does not claim an attempt: start-cycle clears the previous cycle's usage,
|
|
372
|
+
// so a claim would be immediately erased. Normal driving claims as before.
|
|
373
|
+
const claim = !isCycleStart && entry.frontmatter.control
|
|
374
|
+
? await claimTaskAttempt(channelDir, entry.id, now)
|
|
375
|
+
: undefined;
|
|
219
376
|
if (claim) {
|
|
220
377
|
fingerprint = await taskFingerprint(channelDir, entry);
|
|
221
378
|
}
|
|
222
|
-
const
|
|
379
|
+
const event = isCycleStart
|
|
380
|
+
? createCycleStartEvent(channelId, entry, nowMs)
|
|
381
|
+
: createTaskDriverEvent(channelId, entry, nowMs);
|
|
382
|
+
const accepted = await this.options.dispatch(event);
|
|
223
383
|
if (!accepted && claim)
|
|
224
384
|
await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
|
|
225
|
-
this.attempts.set(key, { fingerprint, atMs:
|
|
385
|
+
this.attempts.set(key, { fingerprint, atMs: nowMs, accepted });
|
|
386
|
+
this.lastDispatchedTaskId.set(channelId, entry.id);
|
|
226
387
|
if (accepted) {
|
|
227
388
|
dispatched++;
|
|
228
389
|
lastDispatchOffset = offset;
|
|
229
|
-
log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
|
|
390
|
+
log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}${isCycleStart ? " (cycle-start)" : ""}`);
|
|
230
391
|
}
|
|
231
392
|
else {
|
|
232
393
|
log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
|
|
@@ -236,6 +397,17 @@ export class TaskDriver {
|
|
|
236
397
|
if (!seen.has(key))
|
|
237
398
|
this.attempts.delete(key);
|
|
238
399
|
}
|
|
400
|
+
// A backed-off task becomes eligible again at attempt time + its retry delay; wake then
|
|
401
|
+
// so an unchanged ledger is still retried without polling. Changed ledgers arrive via nudge.
|
|
402
|
+
for (const attempt of this.attempts.values()) {
|
|
403
|
+
const delayMinutes = attempt.accepted ? settings.stalledRetryMinutes : settings.continuationDelayMinutes;
|
|
404
|
+
this.noteHorizon(attempt.atMs + delayMinutes * 60_000, nowMs);
|
|
405
|
+
}
|
|
406
|
+
const channelSet = new Set(channels);
|
|
407
|
+
for (const channelId of this.lastDispatchedTaskId.keys()) {
|
|
408
|
+
if (!channelSet.has(channelId))
|
|
409
|
+
this.lastDispatchedTaskId.delete(channelId);
|
|
410
|
+
}
|
|
239
411
|
this.nextChannelIndex = (start + (lastDispatchOffset >= 0 ? lastDispatchOffset + 1 : 1)) % channels.length;
|
|
240
412
|
}
|
|
241
413
|
finally {
|
package/dist/settings.d.ts
CHANGED
|
@@ -71,6 +71,8 @@ export interface PipiclawTaskDriverSettings {
|
|
|
71
71
|
stalledRetryMinutes: number;
|
|
72
72
|
/** Global enqueue cap per scan, with round-robin fairness across channels. */
|
|
73
73
|
maxDispatchesPerTick: number;
|
|
74
|
+
/** Cap on idle sleep between scans; also the upper bound on how late a manual edit is noticed. */
|
|
75
|
+
maxSleepMinutes: number;
|
|
74
76
|
}
|
|
75
77
|
export interface PipiclawSessionMemorySettings {
|
|
76
78
|
enabled: boolean;
|
package/dist/settings.js
CHANGED
|
@@ -42,6 +42,7 @@ const DEFAULT_TASK_DRIVER = {
|
|
|
42
42
|
continuationDelayMinutes: 5,
|
|
43
43
|
stalledRetryMinutes: 60,
|
|
44
44
|
maxDispatchesPerTick: 4,
|
|
45
|
+
maxSleepMinutes: 15,
|
|
45
46
|
};
|
|
46
47
|
const DEFAULT_SESSION_MEMORY = {
|
|
47
48
|
enabled: true,
|
|
@@ -201,10 +202,14 @@ export class PipiclawSettingsManager {
|
|
|
201
202
|
const maxDispatchesPerTick = Number.isFinite(configured.maxDispatchesPerTick)
|
|
202
203
|
? Math.min(20, Math.max(1, Math.floor(configured.maxDispatchesPerTick)))
|
|
203
204
|
: DEFAULT_TASK_DRIVER.maxDispatchesPerTick;
|
|
205
|
+
const maxSleepMinutes = Number.isFinite(configured.maxSleepMinutes)
|
|
206
|
+
? Math.min(60, Math.max(1, Math.floor(configured.maxSleepMinutes)))
|
|
207
|
+
: DEFAULT_TASK_DRIVER.maxSleepMinutes;
|
|
204
208
|
return {
|
|
205
209
|
continuationDelayMinutes,
|
|
206
210
|
stalledRetryMinutes,
|
|
207
211
|
maxDispatchesPerTick,
|
|
212
|
+
maxSleepMinutes,
|
|
208
213
|
};
|
|
209
214
|
}
|
|
210
215
|
getSessionMemorySettings() {
|
|
@@ -14,6 +14,8 @@ export interface TaskFrontmatter {
|
|
|
14
14
|
readable: boolean;
|
|
15
15
|
status?: string;
|
|
16
16
|
wake?: string;
|
|
17
|
+
/** Five-field cron cadence (host timezone). Present ⇒ this is a recurring task. */
|
|
18
|
+
schedule?: string;
|
|
17
19
|
recurrence?: string;
|
|
18
20
|
control?: TaskControl;
|
|
19
21
|
/** false only when a control field exists but cannot be parsed/validated. */
|
|
@@ -90,6 +92,7 @@ export declare function renderStandardTaskBody(input: TaskSkeletonInput): string
|
|
|
90
92
|
export interface TaskDocumentFields {
|
|
91
93
|
status: string;
|
|
92
94
|
wake?: string;
|
|
95
|
+
schedule?: string;
|
|
93
96
|
recurrence?: string;
|
|
94
97
|
control?: TaskControl;
|
|
95
98
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readdir, readFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { parseTaskControl, taskPriorityRank } from "../tasks/control.js";
|
|
4
|
-
const FRONTMATTER_FIELDS = ["status", "wake", "recurrence", "control"];
|
|
4
|
+
const FRONTMATTER_FIELDS = ["status", "wake", "schedule", "recurrence", "control"];
|
|
5
5
|
const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
6
6
|
export const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
|
|
7
7
|
export const STANDARD_TASK_SECTIONS = [
|
|
@@ -198,6 +198,8 @@ export function renderTaskDocument(fields, body) {
|
|
|
198
198
|
const lines = ["---", `status: ${fields.status}`];
|
|
199
199
|
if (fields.wake)
|
|
200
200
|
lines.push(`wake: ${fields.wake}`);
|
|
201
|
+
if (fields.schedule)
|
|
202
|
+
lines.push(`schedule: ${fields.schedule}`);
|
|
201
203
|
if (fields.recurrence)
|
|
202
204
|
lines.push(`recurrence: ${fields.recurrence}`);
|
|
203
205
|
if (fields.control)
|
|
@@ -296,6 +298,44 @@ export function startTaskCycle(content, cycleId) {
|
|
|
296
298
|
// A nested history heading would be unusual; inserting directly after the
|
|
297
299
|
// canonical History heading remains predictable and preserves all older notes.
|
|
298
300
|
lines.splice(shiftedHistoryStart + 1, 0, ...historyEntry);
|
|
301
|
+
return resetTaskAcceptanceCheckboxes(lines.join("\n"));
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Uncheck every "- [x]" under DoD/Verification.
|
|
305
|
+
*
|
|
306
|
+
* `startTaskCycle` archives the previous cycle's log but never touched these boxes, so a
|
|
307
|
+
* periodic task that finished cycle 1 with a fully checked DoD would open cycle 2 with
|
|
308
|
+
* `uncheckedTaskAcceptanceItems` reporting zero unchecked items — the acceptance gate would
|
|
309
|
+
* silently pass on stale evidence from a cycle that no longer exists.
|
|
310
|
+
*/
|
|
311
|
+
function resetTaskAcceptanceCheckboxes(content) {
|
|
312
|
+
const lines = content.split("\n");
|
|
313
|
+
let section;
|
|
314
|
+
let sectionLevel = 0;
|
|
315
|
+
for (let index = 0; index < lines.length; index++) {
|
|
316
|
+
const line = lines[index] ?? "";
|
|
317
|
+
const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
|
|
318
|
+
if (heading) {
|
|
319
|
+
const level = heading[1]?.length ?? 7;
|
|
320
|
+
if (matchesTaskSectionTitle(heading[2] ?? "", ["DoD"])) {
|
|
321
|
+
section = "DoD";
|
|
322
|
+
sectionLevel = level;
|
|
323
|
+
}
|
|
324
|
+
else if (matchesTaskSectionTitle(heading[2] ?? "", ["Verification", "验收"])) {
|
|
325
|
+
section = "Verification";
|
|
326
|
+
sectionLevel = level;
|
|
327
|
+
}
|
|
328
|
+
else if (section && level <= sectionLevel) {
|
|
329
|
+
section = undefined;
|
|
330
|
+
}
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (!section)
|
|
334
|
+
continue;
|
|
335
|
+
const checkbox = /^(\s*[-*]\s+)\[[xX]\](\s*.*)$/.exec(line);
|
|
336
|
+
if (checkbox)
|
|
337
|
+
lines[index] = `${checkbox[1]}[ ]${checkbox[2]}`;
|
|
338
|
+
}
|
|
299
339
|
return lines.join("\n");
|
|
300
340
|
}
|
|
301
341
|
/** Last non-empty bullet/line under a "当前周期"/"current cycle" heading. */
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cron cadence of a recurring task lives in its `schedule` frontmatter key.
|
|
3
|
+
* Cron is always interpreted in the host timezone — tasks (and events) follow the
|
|
4
|
+
* person on their machine, so no `timezone` field or config exists.
|
|
5
|
+
*/
|
|
6
|
+
/** A task schedule may fire no more often than this (anti-self-nudge floor). */
|
|
7
|
+
export declare const MIN_TASK_SCHEDULE_INTERVAL_MS: number;
|
|
8
|
+
/**
|
|
9
|
+
* Validate a task `schedule` cron: it must parse (host timezone) and fire no more
|
|
10
|
+
* often than every 30 minutes. Throws with an agent-readable message otherwise.
|
|
11
|
+
* Mirrors the `event_manage` periodic gate so both write paths reject the same cron.
|
|
12
|
+
*/
|
|
13
|
+
export declare function validateTaskSchedule(schedule: string): void;
|
|
14
|
+
/**
|
|
15
|
+
* Next occurrence of a task `schedule` strictly after `from`, or undefined when the
|
|
16
|
+
* cron cannot be parsed (the caller decides how to surface that).
|
|
17
|
+
*/
|
|
18
|
+
export declare function nextTaskWake(schedule: string, from?: Date): Date | undefined;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Cron } from "croner";
|
|
2
|
+
import { errorMessage } from "./text-utils.js";
|
|
3
|
+
/**
|
|
4
|
+
* The cron cadence of a recurring task lives in its `schedule` frontmatter key.
|
|
5
|
+
* Cron is always interpreted in the host timezone — tasks (and events) follow the
|
|
6
|
+
* person on their machine, so no `timezone` field or config exists.
|
|
7
|
+
*/
|
|
8
|
+
/** A task schedule may fire no more often than this (anti-self-nudge floor). */
|
|
9
|
+
export const MIN_TASK_SCHEDULE_INTERVAL_MS = 30 * 60 * 1000;
|
|
10
|
+
/**
|
|
11
|
+
* Validate a task `schedule` cron: it must parse (host timezone) and fire no more
|
|
12
|
+
* often than every 30 minutes. Throws with an agent-readable message otherwise.
|
|
13
|
+
* Mirrors the `event_manage` periodic gate so both write paths reject the same cron.
|
|
14
|
+
*/
|
|
15
|
+
export function validateTaskSchedule(schedule) {
|
|
16
|
+
let runs;
|
|
17
|
+
try {
|
|
18
|
+
const cron = new Cron(schedule);
|
|
19
|
+
runs = cron.nextRuns(3);
|
|
20
|
+
cron.stop();
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
throw new Error(`schedule "${schedule}" is not a valid cron: ${errorMessage(error)}`);
|
|
24
|
+
}
|
|
25
|
+
if (runs.length === 0) {
|
|
26
|
+
throw new Error(`schedule "${schedule}" never fires; use a valid five-field cron.`);
|
|
27
|
+
}
|
|
28
|
+
const floorMinutes = Math.round(MIN_TASK_SCHEDULE_INTERVAL_MS / 60_000);
|
|
29
|
+
// Fewer than two upcoming runs means no cadence to rate-limit (e.g. a one-off cron); allow it.
|
|
30
|
+
for (let i = 1; i < runs.length; i++) {
|
|
31
|
+
if (runs[i].getTime() - runs[i - 1].getTime() < MIN_TASK_SCHEDULE_INTERVAL_MS) {
|
|
32
|
+
throw new Error(`schedule "${schedule}" must fire no more often than every ${floorMinutes} minutes.`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Next occurrence of a task `schedule` strictly after `from`, or undefined when the
|
|
38
|
+
* cron cannot be parsed (the caller decides how to surface that).
|
|
39
|
+
*/
|
|
40
|
+
export function nextTaskWake(schedule, from = new Date()) {
|
|
41
|
+
try {
|
|
42
|
+
const cron = new Cron(schedule);
|
|
43
|
+
const next = cron.nextRun(from);
|
|
44
|
+
cron.stop();
|
|
45
|
+
return next ?? undefined;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/tasks/store.js
CHANGED
|
@@ -31,6 +31,7 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
|
|
|
31
31
|
fields: {
|
|
32
32
|
status: frontmatter.status ?? "open",
|
|
33
33
|
wake: frontmatter.wake,
|
|
34
|
+
schedule: frontmatter.schedule,
|
|
34
35
|
recurrence: frontmatter.recurrence,
|
|
35
36
|
control: frontmatter.control,
|
|
36
37
|
},
|
|
@@ -41,14 +41,6 @@ function parseAction(action) {
|
|
|
41
41
|
}
|
|
42
42
|
throw new Error('Unsupported event action. Use "create", "update", or "delete".');
|
|
43
43
|
}
|
|
44
|
-
function validateTimezone(timezone) {
|
|
45
|
-
try {
|
|
46
|
-
new Intl.DateTimeFormat(undefined, { timeZone: timezone });
|
|
47
|
-
}
|
|
48
|
-
catch {
|
|
49
|
-
throw new Error(`Invalid timezone: ${timezone}`);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
44
|
function validateOneShot(event) {
|
|
53
45
|
const atTime = new Date(event.at).getTime();
|
|
54
46
|
if (!Number.isFinite(atTime)) {
|
|
@@ -59,10 +51,9 @@ function validateOneShot(event) {
|
|
|
59
51
|
}
|
|
60
52
|
}
|
|
61
53
|
function validatePeriodic(event) {
|
|
62
|
-
validateTimezone(event.timezone);
|
|
63
54
|
let runs;
|
|
64
55
|
try {
|
|
65
|
-
const cron = new Cron(event.schedule
|
|
56
|
+
const cron = new Cron(event.schedule);
|
|
66
57
|
runs = cron.nextRuns(3);
|
|
67
58
|
cron.stop();
|
|
68
59
|
}
|
|
@@ -193,6 +184,11 @@ export async function manageEvent(options, request) {
|
|
|
193
184
|
}
|
|
194
185
|
}
|
|
195
186
|
const event = validateDefinition(request.definition, eventName, options);
|
|
187
|
+
// Persist the canonical form: a tolerated legacy `timezone` is dropped so freshly written
|
|
188
|
+
// events never carry the deprecated field (cron is always host-timezone now).
|
|
189
|
+
if (event.type === "periodic" && event.legacyTimezone !== undefined) {
|
|
190
|
+
delete event.legacyTimezone;
|
|
191
|
+
}
|
|
196
192
|
const content = `${JSON.stringify(event, null, 2)}\n`;
|
|
197
193
|
await writeFileAtomically(eventPath, content);
|
|
198
194
|
return {
|
|
@@ -31,6 +31,7 @@ declare const taskManageSchema: Type.TObject<{
|
|
|
31
31
|
}>>;
|
|
32
32
|
status: Type.TOptional<Type.TUnion<Type.TLiteral<"blocked" | "paused" | "open" | "in-progress" | "awaiting-user">[]>>;
|
|
33
33
|
wake: Type.TOptional<Type.TString>;
|
|
34
|
+
schedule: Type.TOptional<Type.TString>;
|
|
34
35
|
recurrence: Type.TOptional<Type.TString>;
|
|
35
36
|
note: Type.TOptional<Type.TString>;
|
|
36
37
|
verifierRunId: Type.TOptional<Type.TString>;
|
|
@@ -67,6 +68,7 @@ export interface TaskManageRequest {
|
|
|
67
68
|
manual?: string;
|
|
68
69
|
status?: string;
|
|
69
70
|
wake?: string;
|
|
71
|
+
schedule?: string;
|
|
70
72
|
recurrence?: string;
|
|
71
73
|
note?: string;
|
|
72
74
|
verificationPlan?: string;
|