@oyasmi/pipiclaw 0.8.8-beta.1 → 0.8.8
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 +3 -3
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +8 -0
- package/dist/agent/runner-factory.d.ts +2 -0
- 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 +13 -2
- package/dist/runtime/bootstrap.js +8 -2
- 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 +36 -0
- package/dist/runtime/task-driver.js +217 -33
- package/dist/security/path-guard.js +3 -1
- 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/package.json +5 -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 ?? "",
|
|
@@ -83,12 +92,44 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
|
83
92
|
text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
|
|
84
93
|
`Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-driving.md")} before acting. ` +
|
|
85
94
|
"Advance the next concrete step under the task's current control, acceptance, approval, and verification state. " +
|
|
86
|
-
`If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook.${verificationInstruction}
|
|
95
|
+
`If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook.${verificationInstruction} ` +
|
|
96
|
+
"If the task explicitly says there is no change and no tool action is needed, do not call task_manage; respond with exactly [SILENT]. Otherwise, if this wake produces no user-visible change or result, respond with exactly [SILENT].",
|
|
87
97
|
ts: String(nowMs),
|
|
88
98
|
conversationId: "",
|
|
89
99
|
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
90
100
|
};
|
|
91
101
|
}
|
|
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. */
|
|
123
|
+
function isCycleStartReady(entry, nowMs) {
|
|
124
|
+
return (entry.frontmatter.status === "done" &&
|
|
125
|
+
Boolean(entry.frontmatter.schedule) &&
|
|
126
|
+
entry.wakeMs !== undefined &&
|
|
127
|
+
entry.wakeMs <= nowMs);
|
|
128
|
+
}
|
|
129
|
+
/** done + schedule but no parseable wake → self-heal target (recompute wake, zero token). */
|
|
130
|
+
function needsWakeHeal(entry) {
|
|
131
|
+
return entry.frontmatter.status === "done" && Boolean(entry.frontmatter.schedule) && entry.wakeMs === undefined;
|
|
132
|
+
}
|
|
92
133
|
function taskEscalationEvent(channelId, entry, reason, nowMs) {
|
|
93
134
|
return {
|
|
94
135
|
type: channelId.startsWith("group_") ? "group" : "dm",
|
|
@@ -123,31 +164,122 @@ export class TaskDriver {
|
|
|
123
164
|
constructor(options) {
|
|
124
165
|
this.options = options;
|
|
125
166
|
this.timer = null;
|
|
167
|
+
this.nudgeTimer = null;
|
|
168
|
+
this.loopActive = false;
|
|
126
169
|
this.running = false;
|
|
127
170
|
this.nextChannelIndex = 0;
|
|
128
171
|
this.attempts = new Map();
|
|
172
|
+
/**
|
|
173
|
+
* Last task id dispatched per channel. Cross-channel fairness is handled by
|
|
174
|
+
* `nextChannelIndex`, but within one channel every tick used to pick the first ready
|
|
175
|
+
* candidate in sort order — an actively-progressing task keeps winning that slot forever,
|
|
176
|
+
* starving every other ready task (including its own unlocked dependents) in the same
|
|
177
|
+
* channel. Remembering the last pick and starting the search just after it gives ready
|
|
178
|
+
* candidates in a channel the same round-robin fairness across ticks.
|
|
179
|
+
*/
|
|
180
|
+
this.lastDispatchedTaskId = new Map();
|
|
181
|
+
}
|
|
182
|
+
observeDispatch(event, accepted) {
|
|
183
|
+
try {
|
|
184
|
+
this.options.onDispatch?.(event, accepted);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
log.logWarning("Task driver dispatch observer failed", errorMessage(error));
|
|
188
|
+
}
|
|
129
189
|
}
|
|
130
190
|
start() {
|
|
131
|
-
if (this.
|
|
191
|
+
if (this.loopActive)
|
|
132
192
|
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?.();
|
|
193
|
+
this.loopActive = true;
|
|
194
|
+
void this.tick();
|
|
139
195
|
}
|
|
140
196
|
stop() {
|
|
141
|
-
|
|
197
|
+
this.loopActive = false;
|
|
198
|
+
if (this.timer) {
|
|
199
|
+
clearTimeout(this.timer);
|
|
200
|
+
this.timer = null;
|
|
201
|
+
}
|
|
202
|
+
if (this.nudgeTimer) {
|
|
203
|
+
clearTimeout(this.nudgeTimer);
|
|
204
|
+
this.nudgeTimer = null;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* In-process wake: after a turn ends or a task file is written, re-scan promptly instead
|
|
209
|
+
* of waiting out the current sleep. The timer is a hint; the scan re-reads every file, so
|
|
210
|
+
* a stale or missed nudge only costs one capped sleep of latency, never correctness.
|
|
211
|
+
*/
|
|
212
|
+
nudge() {
|
|
213
|
+
if (!this.loopActive || this.nudgeTimer)
|
|
142
214
|
return;
|
|
143
|
-
|
|
144
|
-
|
|
215
|
+
if (this.timer) {
|
|
216
|
+
clearTimeout(this.timer);
|
|
217
|
+
this.timer = null;
|
|
218
|
+
}
|
|
219
|
+
this.nudgeTimer = setTimeout(() => {
|
|
220
|
+
this.nudgeTimer = null;
|
|
221
|
+
void this.tick();
|
|
222
|
+
}, NUDGE_DEBOUNCE_MS);
|
|
223
|
+
this.nudgeTimer.unref?.();
|
|
224
|
+
}
|
|
225
|
+
async tick() {
|
|
226
|
+
try {
|
|
227
|
+
await this.runOnce();
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
log.logWarning("Task driver tick failed", errorMessage(error));
|
|
231
|
+
}
|
|
232
|
+
this.scheduleNext();
|
|
233
|
+
}
|
|
234
|
+
scheduleNext() {
|
|
235
|
+
if (!this.loopActive || this.timer || this.nudgeTimer)
|
|
236
|
+
return;
|
|
237
|
+
const settings = this.options.getSettings();
|
|
238
|
+
const capMs = this.options.intervalMs ?? settings.maxSleepMinutes * 60_000;
|
|
239
|
+
const untilNext = this.nextWakeMs !== undefined ? this.nextWakeMs - Date.now() : Number.POSITIVE_INFINITY;
|
|
240
|
+
const sleepMs = Math.max(MIN_SLEEP_MS, Math.min(capMs, untilNext));
|
|
241
|
+
this.timer = setTimeout(() => {
|
|
242
|
+
this.timer = null;
|
|
243
|
+
void this.tick();
|
|
244
|
+
}, sleepMs);
|
|
245
|
+
this.timer.unref?.();
|
|
246
|
+
}
|
|
247
|
+
/** Fold `candidate` into the earliest interesting wake moment. */
|
|
248
|
+
noteHorizon(candidate, nowMs) {
|
|
249
|
+
if (candidate === undefined || !Number.isFinite(candidate) || candidate <= nowMs)
|
|
250
|
+
return;
|
|
251
|
+
if (this.nextWakeMs === undefined || candidate < this.nextWakeMs)
|
|
252
|
+
this.nextWakeMs = candidate;
|
|
253
|
+
}
|
|
254
|
+
collectHorizons(entries, nowMs) {
|
|
255
|
+
for (const entry of entries) {
|
|
256
|
+
this.noteHorizon(entry.wakeMs, nowMs);
|
|
257
|
+
const control = entry.frontmatter.control;
|
|
258
|
+
if (control?.deadline && !TERMINAL_STATUSES.has(entry.frontmatter.status ?? "")) {
|
|
259
|
+
this.noteHorizon(new Date(control.deadline).getTime(), nowMs);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
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
|
+
}
|
|
145
275
|
}
|
|
146
276
|
async runOnce(now = new Date()) {
|
|
147
277
|
if (this.options.isEnabled?.() === false || this.running)
|
|
148
278
|
return;
|
|
149
279
|
const settings = this.options.getSettings();
|
|
280
|
+
const nowMs = now.getTime();
|
|
150
281
|
this.running = true;
|
|
282
|
+
this.nextWakeMs = undefined;
|
|
151
283
|
try {
|
|
152
284
|
const channels = await discoverTaskChannels(this.options.workspaceDir, this.options.getKnownChannelIds?.());
|
|
153
285
|
if (channels.length === 0) {
|
|
@@ -163,27 +295,43 @@ export class TaskDriver {
|
|
|
163
295
|
if (!channelId)
|
|
164
296
|
continue;
|
|
165
297
|
const channelDir = join(this.options.workspaceDir, channelId);
|
|
166
|
-
const entries = await readActiveTasks(join(channelDir, "tasks"),
|
|
298
|
+
const entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
|
|
167
299
|
for (const entry of entries)
|
|
168
300
|
seen.add(attemptKey(channelId, entry.id));
|
|
301
|
+
this.collectHorizons(entries, nowMs);
|
|
169
302
|
if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
|
|
170
303
|
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.
|
|
307
|
+
for (const entry of entries) {
|
|
308
|
+
if (!needsWakeHeal(entry))
|
|
309
|
+
continue;
|
|
310
|
+
const next = nextTaskWake(entry.frontmatter.schedule, now);
|
|
311
|
+
if (!next) {
|
|
312
|
+
log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
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());
|
|
320
|
+
}
|
|
171
321
|
let governanceHandled = false;
|
|
172
322
|
for (const candidate of entries) {
|
|
173
323
|
const status = candidate.frontmatter.status;
|
|
174
324
|
const control = candidate.frontmatter.control;
|
|
175
|
-
if (!control ||
|
|
176
|
-
status === "done" ||
|
|
177
|
-
status === "cancelled" ||
|
|
178
|
-
status === "escalated" ||
|
|
179
|
-
status === "paused")
|
|
325
|
+
if (!control || TERMINAL_STATUSES.has(status ?? ""))
|
|
180
326
|
continue;
|
|
181
327
|
const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
|
|
182
|
-
const escalationReason = taskBudgetViolation(control,
|
|
328
|
+
const escalationReason = taskBudgetViolation(control, nowMs) ?? terminalDependencyReason(dependencies.reason);
|
|
183
329
|
if (!escalationReason)
|
|
184
330
|
continue;
|
|
185
331
|
governanceHandled = true;
|
|
186
|
-
const
|
|
332
|
+
const escalationEvent = taskEscalationEvent(channelId, candidate, escalationReason, nowMs);
|
|
333
|
+
const accepted = await this.options.dispatch(escalationEvent);
|
|
334
|
+
this.observeDispatch(escalationEvent, accepted);
|
|
187
335
|
if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
|
|
188
336
|
dispatched++;
|
|
189
337
|
lastDispatchOffset = offset;
|
|
@@ -193,40 +341,65 @@ export class TaskDriver {
|
|
|
193
341
|
}
|
|
194
342
|
if (governanceHandled)
|
|
195
343
|
continue;
|
|
196
|
-
|
|
344
|
+
// 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.
|
|
346
|
+
const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
|
|
197
347
|
if (candidates.length === 0)
|
|
198
348
|
continue;
|
|
349
|
+
const lastId = this.lastDispatchedTaskId.get(channelId);
|
|
350
|
+
const lastIndex = lastId ? candidates.findIndex((candidate) => candidate.id === lastId) : -1;
|
|
351
|
+
const rotatedCandidates = lastIndex >= 0
|
|
352
|
+
? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
|
|
353
|
+
: candidates;
|
|
199
354
|
let entry;
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
if (
|
|
355
|
+
let isCycleStart = false;
|
|
356
|
+
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
|
+
}
|
|
203
364
|
entry = candidate;
|
|
365
|
+
isCycleStart = false;
|
|
204
366
|
break;
|
|
205
367
|
}
|
|
206
|
-
|
|
207
|
-
|
|
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))
|
|
208
371
|
continue;
|
|
209
372
|
entry = candidate;
|
|
373
|
+
isCycleStart = true;
|
|
210
374
|
break;
|
|
211
375
|
}
|
|
212
376
|
if (!entry || dispatched >= settings.maxDispatchesPerTick)
|
|
213
377
|
continue;
|
|
214
378
|
const key = attemptKey(channelId, entry.id);
|
|
215
379
|
let fingerprint = await taskFingerprint(channelDir, entry);
|
|
216
|
-
if (!isEligible(this.attempts.get(key), fingerprint,
|
|
380
|
+
if (!isEligible(this.attempts.get(key), fingerprint, nowMs, settings))
|
|
217
381
|
continue;
|
|
218
|
-
|
|
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;
|
|
219
387
|
if (claim) {
|
|
220
388
|
fingerprint = await taskFingerprint(channelDir, entry);
|
|
221
389
|
}
|
|
222
|
-
const
|
|
390
|
+
const event = isCycleStart
|
|
391
|
+
? createCycleStartEvent(channelId, entry, nowMs)
|
|
392
|
+
: createTaskDriverEvent(channelId, entry, nowMs);
|
|
393
|
+
const accepted = await this.options.dispatch(event);
|
|
394
|
+
this.observeDispatch(event, accepted);
|
|
223
395
|
if (!accepted && claim)
|
|
224
396
|
await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
|
|
225
|
-
this.attempts.set(key, { fingerprint, atMs:
|
|
397
|
+
this.attempts.set(key, { fingerprint, atMs: nowMs, accepted });
|
|
398
|
+
this.lastDispatchedTaskId.set(channelId, entry.id);
|
|
226
399
|
if (accepted) {
|
|
227
400
|
dispatched++;
|
|
228
401
|
lastDispatchOffset = offset;
|
|
229
|
-
log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
|
|
402
|
+
log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}${isCycleStart ? " (cycle-start)" : ""}`);
|
|
230
403
|
}
|
|
231
404
|
else {
|
|
232
405
|
log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
|
|
@@ -236,6 +409,17 @@ export class TaskDriver {
|
|
|
236
409
|
if (!seen.has(key))
|
|
237
410
|
this.attempts.delete(key);
|
|
238
411
|
}
|
|
412
|
+
// A backed-off task becomes eligible again at attempt time + its retry delay; wake then
|
|
413
|
+
// so an unchanged ledger is still retried without polling. Changed ledgers arrive via nudge.
|
|
414
|
+
for (const attempt of this.attempts.values()) {
|
|
415
|
+
const delayMinutes = attempt.accepted ? settings.stalledRetryMinutes : settings.continuationDelayMinutes;
|
|
416
|
+
this.noteHorizon(attempt.atMs + delayMinutes * 60_000, nowMs);
|
|
417
|
+
}
|
|
418
|
+
const channelSet = new Set(channels);
|
|
419
|
+
for (const channelId of this.lastDispatchedTaskId.keys()) {
|
|
420
|
+
if (!channelSet.has(channelId))
|
|
421
|
+
this.lastDispatchedTaskId.delete(channelId);
|
|
422
|
+
}
|
|
239
423
|
this.nextChannelIndex = (start + (lastDispatchOffset >= 0 ? lastDispatchOffset + 1 : 1)) % channels.length;
|
|
240
424
|
}
|
|
241
425
|
finally {
|
|
@@ -161,7 +161,9 @@ function isDeniedSystemPath(path) {
|
|
|
161
161
|
return SYSTEM_DENY_PREFIXES.some((prefix) => startsWithPathPrefix(path, normalize(prefix)));
|
|
162
162
|
}
|
|
163
163
|
function matchesConfiguredPath(path, entries, ctx) {
|
|
164
|
-
return entries
|
|
164
|
+
return entries
|
|
165
|
+
.map((entry) => resolveForGuard(resolveConfiguredPath(entry, ctx), ctx))
|
|
166
|
+
.some((entry) => startsWithPathPrefix(path, entry));
|
|
165
167
|
}
|
|
166
168
|
function pathAllowedByDefaults(path, ctx) {
|
|
167
169
|
const homeDir = ctx.homeDir ?? homedir();
|
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;
|