@oyasmi/pipiclaw 0.7.7 → 0.8.0
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 +9 -2
- package/dist/agent/channel-runner.d.ts +3 -0
- package/dist/agent/channel-runner.js +7 -1
- package/dist/agent/commands.js +7 -2
- package/dist/agent/prompt-builder.js +46 -0
- package/dist/agent/types.d.ts +2 -0
- package/dist/memory/task-digest.js +17 -0
- package/dist/runtime/bootstrap.d.ts +5 -0
- package/dist/runtime/bootstrap.js +57 -2
- package/dist/runtime/dingtalk.d.ts +2 -0
- package/dist/runtime/durable-dispatch.d.ts +28 -0
- package/dist/runtime/durable-dispatch.js +144 -0
- package/dist/runtime/events.d.ts +4 -2
- package/dist/runtime/events.js +12 -8
- package/dist/runtime/task-commands.d.ts +6 -0
- package/dist/runtime/task-commands.js +284 -3
- package/dist/runtime/task-driver.d.ts +32 -0
- package/dist/runtime/task-driver.js +270 -0
- package/dist/settings.d.ts +12 -0
- package/dist/settings.js +30 -0
- package/dist/shared/task-ledger.d.ts +27 -0
- package/dist/shared/task-ledger.js +209 -9
- package/dist/subagents/tool.d.ts +13 -0
- package/dist/subagents/tool.js +203 -11
- package/dist/tasks/artifact-subject.d.ts +6 -0
- package/dist/tasks/artifact-subject.js +29 -0
- package/dist/tasks/control.d.ts +83 -0
- package/dist/tasks/control.js +292 -0
- package/dist/tasks/store.d.ts +32 -0
- package/dist/tasks/store.js +142 -0
- package/dist/tasks/verification.d.ts +23 -0
- package/dist/tasks/verification.js +68 -0
- package/dist/tools/registry.d.ts +1 -1
- package/dist/tools/registry.js +6 -5
- package/dist/tools/task-manage.d.ts +37 -3
- package/dist/tools/task-manage.js +385 -28
- package/package.json +1 -1
|
@@ -3,6 +3,8 @@ import { readdir, readFile } from "node:fs/promises";
|
|
|
3
3
|
import { join, resolve, sep } from "node:path";
|
|
4
4
|
import { isTaskCheckinEvent, isTaskScheduleEvent, parseTaskEventName, taskEventPrefix, taskScheduleEventName, } from "../shared/task-events.js";
|
|
5
5
|
import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
|
|
6
|
+
import { taskBudgetViolation } from "../tasks/control.js";
|
|
7
|
+
import { readStoredTask, taskBodyHash, writeStoredTask } from "../tasks/store.js";
|
|
6
8
|
import { parseScheduledEventContent } from "./events.js";
|
|
7
9
|
function usage() {
|
|
8
10
|
return `# Tasks
|
|
@@ -12,6 +14,11 @@ Usage:
|
|
|
12
14
|
- \`/tasks\` — list active tasks in this channel
|
|
13
15
|
- \`/tasks show <id>\` — show a single task file (active or archived)
|
|
14
16
|
- \`/tasks archive\` — list archived (closed) tasks
|
|
17
|
+
- \`/tasks approve <id>\` — explicitly approve this task's external side effects
|
|
18
|
+
- \`/tasks pause <id>\` — stop automatic wake-ups for a task
|
|
19
|
+
- \`/tasks resume <id>\` — make a paused task eligible for the next driver scan
|
|
20
|
+
- \`/tasks run <id>\` — resume and immediately enqueue one task attempt when the runtime is available
|
|
21
|
+
- \`/tasks stats [id]\` — show task-level attempt, token, cost, and verification outcomes
|
|
15
22
|
- \`/tasks doctor\` — check task/event consistency without changing files`;
|
|
16
23
|
}
|
|
17
24
|
function parseTasksCommand(args) {
|
|
@@ -38,6 +45,30 @@ function parseTasksCommand(args) {
|
|
|
38
45
|
throw new Error("Usage: /tasks doctor");
|
|
39
46
|
return { action: "doctor" };
|
|
40
47
|
}
|
|
48
|
+
if (action === "approve") {
|
|
49
|
+
const id = parts[1];
|
|
50
|
+
if (!id || parts.length > 2)
|
|
51
|
+
throw new Error("Usage: /tasks approve <id>");
|
|
52
|
+
return { action: "approve", id };
|
|
53
|
+
}
|
|
54
|
+
if (action === "pause" || action === "resume") {
|
|
55
|
+
const id = parts[1];
|
|
56
|
+
if (!id || parts.length > 2)
|
|
57
|
+
throw new Error(`Usage: /tasks ${action} <id>`);
|
|
58
|
+
return { action, id };
|
|
59
|
+
}
|
|
60
|
+
if (action === "run") {
|
|
61
|
+
const id = parts[1];
|
|
62
|
+
if (!id || parts.length > 2)
|
|
63
|
+
throw new Error("Usage: /tasks run <id>");
|
|
64
|
+
return { action: "run", id };
|
|
65
|
+
}
|
|
66
|
+
if (action === "stats") {
|
|
67
|
+
const id = parts[1];
|
|
68
|
+
if (parts.length > 2)
|
|
69
|
+
throw new Error("Usage: /tasks stats [id]");
|
|
70
|
+
return { action: "stats", id };
|
|
71
|
+
}
|
|
41
72
|
throw new Error(`Unknown /tasks action: ${action}`);
|
|
42
73
|
}
|
|
43
74
|
function tasksDir(channelDir) {
|
|
@@ -117,6 +148,35 @@ function validWakeMs(entry) {
|
|
|
117
148
|
function issue(problem, nextStep) {
|
|
118
149
|
return `- ${problem}\n Next step: ${nextStep}`;
|
|
119
150
|
}
|
|
151
|
+
function relationCycles(graph) {
|
|
152
|
+
const visited = new Set();
|
|
153
|
+
const active = new Set();
|
|
154
|
+
const stack = [];
|
|
155
|
+
const cycles = new Map();
|
|
156
|
+
const visit = (id) => {
|
|
157
|
+
if (active.has(id)) {
|
|
158
|
+
const start = stack.indexOf(id);
|
|
159
|
+
const cycle = [...stack.slice(start), id];
|
|
160
|
+
const key = [...new Set(cycle)].sort().join("\0");
|
|
161
|
+
cycles.set(key, cycle);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (visited.has(id))
|
|
165
|
+
return;
|
|
166
|
+
visited.add(id);
|
|
167
|
+
active.add(id);
|
|
168
|
+
stack.push(id);
|
|
169
|
+
for (const next of graph.get(id) ?? []) {
|
|
170
|
+
if (graph.has(next))
|
|
171
|
+
visit(next);
|
|
172
|
+
}
|
|
173
|
+
stack.pop();
|
|
174
|
+
active.delete(id);
|
|
175
|
+
};
|
|
176
|
+
for (const id of graph.keys())
|
|
177
|
+
visit(id);
|
|
178
|
+
return Array.from(cycles.values());
|
|
179
|
+
}
|
|
120
180
|
async function readActiveTaskContent(channelDir, id) {
|
|
121
181
|
try {
|
|
122
182
|
return await readFile(join(tasksDir(channelDir), `${id}.md`), "utf-8");
|
|
@@ -135,12 +195,174 @@ async function listTasks(channelDir) {
|
|
|
135
195
|
const blocks = entries.map((entry) => {
|
|
136
196
|
const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
|
|
137
197
|
const detail = [` status: ${status}`, `wake: ${relativeWake(entry.wakeMs, now)}`];
|
|
198
|
+
const control = entry.frontmatter.control;
|
|
199
|
+
if (control) {
|
|
200
|
+
detail.push(`priority: ${control.priority}`);
|
|
201
|
+
detail.push(`attempts: ${control.usage.attempts}/${control.budget.maxAttempts}`);
|
|
202
|
+
detail.push(`verify: ${control.verification.mode}/${control.verification.status}`);
|
|
203
|
+
if (control.isolation !== "shared")
|
|
204
|
+
detail.push(`isolation: ${control.isolation}`);
|
|
205
|
+
if (control.sideEffects !== "workspace") {
|
|
206
|
+
detail.push(`effects: ${control.sideEffects}/${control.externalApproval}`);
|
|
207
|
+
}
|
|
208
|
+
if (control.deadline)
|
|
209
|
+
detail.push(`deadline: ${control.deadline}`);
|
|
210
|
+
if (control.parent)
|
|
211
|
+
detail.push(`parent: ${control.parent}`);
|
|
212
|
+
if (control.dependsOn.length > 0)
|
|
213
|
+
detail.push(`depends: ${control.dependsOn.join(",")}`);
|
|
214
|
+
if (control.nextAction)
|
|
215
|
+
detail.push(`next: ${control.nextAction}`);
|
|
216
|
+
if (control.worktree?.branch)
|
|
217
|
+
detail.push(`branch: ${control.worktree.branch}`);
|
|
218
|
+
}
|
|
138
219
|
if (entry.frontmatter.recurrence)
|
|
139
220
|
detail.push(`recurrence: ${entry.frontmatter.recurrence}`);
|
|
140
221
|
return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
|
|
141
222
|
});
|
|
142
223
|
return `# Tasks: ${entries.length} active\n\n${blocks.join("\n")}`;
|
|
143
224
|
}
|
|
225
|
+
async function approveTask(options, idInput) {
|
|
226
|
+
const id = normalizeTaskId(idInput);
|
|
227
|
+
const task = await readStoredTask(options.channelDir, id);
|
|
228
|
+
if (!task)
|
|
229
|
+
return `Task not found: ${id}`;
|
|
230
|
+
const control = task.fields.control;
|
|
231
|
+
if (!control)
|
|
232
|
+
return `Task ${id} has no governed control metadata. Ask the agent to normalize it before approval.`;
|
|
233
|
+
if (task.fields.status === "done" || task.fields.status === "cancelled" || task.fields.status === "escalated") {
|
|
234
|
+
return `Task ${id} is ${task.fields.status} and cannot receive a new external-action approval.`;
|
|
235
|
+
}
|
|
236
|
+
if (control.sideEffects !== "external") {
|
|
237
|
+
return `Task ${id} is not marked for external side effects; no approval is required.`;
|
|
238
|
+
}
|
|
239
|
+
if (control.externalApproval === "granted") {
|
|
240
|
+
return `Task ${id} was already approved by ${control.approvalBy ?? "a user"} at ${control.approvedAt ?? "an unknown time"}.`;
|
|
241
|
+
}
|
|
242
|
+
control.externalApproval = "granted";
|
|
243
|
+
control.approvalBy = options.approver?.trim() || "unknown-user";
|
|
244
|
+
control.approvedAt = new Date().toISOString();
|
|
245
|
+
control.approvalBodyHash = taskBodyHash(task.body);
|
|
246
|
+
await writeStoredTask(task);
|
|
247
|
+
return `Approved external side effects for task ${id}. Approval is recorded for ${control.approvalBy}.`;
|
|
248
|
+
}
|
|
249
|
+
export async function pauseTask(options, idInput) {
|
|
250
|
+
const id = normalizeTaskId(idInput);
|
|
251
|
+
const task = await readStoredTask(options.channelDir, id);
|
|
252
|
+
if (!task)
|
|
253
|
+
return `Task not found: ${id}`;
|
|
254
|
+
if (["done", "cancelled", "escalated"].includes(task.fields.status)) {
|
|
255
|
+
return `Task ${id} is ${task.fields.status} and cannot be paused.`;
|
|
256
|
+
}
|
|
257
|
+
if (task.fields.status === "paused")
|
|
258
|
+
return `Task ${id} is already paused.`;
|
|
259
|
+
task.fields.status = "paused";
|
|
260
|
+
task.fields.wake = undefined;
|
|
261
|
+
if (task.fields.control) {
|
|
262
|
+
task.fields.control.lastOutcome = "blocked";
|
|
263
|
+
task.fields.control.blockedReason = `Paused by ${options.approver?.trim() || "a user"}.`;
|
|
264
|
+
}
|
|
265
|
+
await writeStoredTask(task);
|
|
266
|
+
return `Paused task ${id}. Use /tasks resume ${id} when it should continue.`;
|
|
267
|
+
}
|
|
268
|
+
export async function resumeTask(options, idInput) {
|
|
269
|
+
const id = normalizeTaskId(idInput);
|
|
270
|
+
const task = await readStoredTask(options.channelDir, id);
|
|
271
|
+
if (!task)
|
|
272
|
+
return `Task not found: ${id}`;
|
|
273
|
+
if (task.fields.status !== "paused")
|
|
274
|
+
return `Task ${id} is ${task.fields.status}, not paused.`;
|
|
275
|
+
task.fields.status = "in-progress";
|
|
276
|
+
task.fields.wake = undefined;
|
|
277
|
+
if (task.fields.control) {
|
|
278
|
+
task.fields.control.lastOutcome = "pending";
|
|
279
|
+
task.fields.control.blockedReason = undefined;
|
|
280
|
+
}
|
|
281
|
+
await writeStoredTask(task);
|
|
282
|
+
return `Resumed task ${id}; the task driver will pick it up on its next scan.`;
|
|
283
|
+
}
|
|
284
|
+
async function runTask(options, idInput) {
|
|
285
|
+
const id = normalizeTaskId(idInput);
|
|
286
|
+
const task = await readStoredTask(options.channelDir, id);
|
|
287
|
+
if (!task)
|
|
288
|
+
return `Task not found: ${id}`;
|
|
289
|
+
if (["done", "cancelled", "escalated"].includes(task.fields.status)) {
|
|
290
|
+
return `Task ${id} is ${task.fields.status} and cannot be run.`;
|
|
291
|
+
}
|
|
292
|
+
if (task.fields.status === "paused")
|
|
293
|
+
task.fields.status = "in-progress";
|
|
294
|
+
task.fields.wake = undefined;
|
|
295
|
+
if (task.fields.control) {
|
|
296
|
+
task.fields.control.lastOutcome = "pending";
|
|
297
|
+
task.fields.control.blockedReason = undefined;
|
|
298
|
+
}
|
|
299
|
+
await writeStoredTask(task);
|
|
300
|
+
const enqueued = await options.dispatchTask?.(id);
|
|
301
|
+
return enqueued
|
|
302
|
+
? `Enqueued task ${id} for an immediate attempt.`
|
|
303
|
+
: `Task ${id} is ready. Start or use the DingTalk daemon for automatic dispatch, or send a normal prompt in this session to advance it.`;
|
|
304
|
+
}
|
|
305
|
+
function renderUsageLine(entry) {
|
|
306
|
+
const control = entry.frontmatter.control;
|
|
307
|
+
if (!control)
|
|
308
|
+
return `- ${entry.id}: legacy task (no governed usage recorded)`;
|
|
309
|
+
const verification = control.verification;
|
|
310
|
+
return [
|
|
311
|
+
`- ${entry.id} — ${entry.title}`,
|
|
312
|
+
` attempts: ${control.usage.attempts}/${control.budget.maxAttempts}`,
|
|
313
|
+
` tokens: ${control.usage.tokens}`,
|
|
314
|
+
` cost: $${control.usage.costUsd.toFixed(4)}`,
|
|
315
|
+
` wall time: ${control.usage.wallTimeMinutes.toFixed(1)}m`,
|
|
316
|
+
` last outcome: ${control.lastOutcome}`,
|
|
317
|
+
` verification: ${verification.mode}/${verification.status}`,
|
|
318
|
+
].join("\n");
|
|
319
|
+
}
|
|
320
|
+
async function taskStats(options, idInput) {
|
|
321
|
+
if (idInput) {
|
|
322
|
+
const id = normalizeTaskId(idInput);
|
|
323
|
+
const task = await readStoredTask(options.channelDir, id, true, true);
|
|
324
|
+
if (!task)
|
|
325
|
+
return `Task not found: ${id}`;
|
|
326
|
+
const entry = {
|
|
327
|
+
id,
|
|
328
|
+
title: extractTaskTitle(task.body, id),
|
|
329
|
+
frontmatter: {
|
|
330
|
+
readable: true,
|
|
331
|
+
status: task.fields.status,
|
|
332
|
+
wake: task.fields.wake,
|
|
333
|
+
recurrence: task.fields.recurrence,
|
|
334
|
+
control: task.fields.control,
|
|
335
|
+
},
|
|
336
|
+
actionable: false,
|
|
337
|
+
};
|
|
338
|
+
return `# Task Stats\n\n${renderUsageLine(entry)}`;
|
|
339
|
+
}
|
|
340
|
+
const entries = await readActiveTasks(tasksDir(options.channelDir));
|
|
341
|
+
const governed = entries.filter((entry) => entry.frontmatter.control);
|
|
342
|
+
const totals = governed.reduce((total, entry) => {
|
|
343
|
+
const usage = entry.frontmatter.control.usage;
|
|
344
|
+
total.attempts += usage.attempts;
|
|
345
|
+
total.tokens += usage.tokens;
|
|
346
|
+
total.costUsd += usage.costUsd;
|
|
347
|
+
total.wallTimeMinutes += usage.wallTimeMinutes;
|
|
348
|
+
return total;
|
|
349
|
+
}, { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 });
|
|
350
|
+
const verified = governed.filter((entry) => entry.frontmatter.control?.verification.status === "passed").length;
|
|
351
|
+
const stalled = governed.filter((entry) => entry.frontmatter.control?.lastOutcome === "failed").length;
|
|
352
|
+
return [
|
|
353
|
+
"# Task Stats",
|
|
354
|
+
"",
|
|
355
|
+
`governed tasks: ${governed.length}/${entries.length}`,
|
|
356
|
+
`attempts: ${totals.attempts}`,
|
|
357
|
+
`tokens: ${totals.tokens}`,
|
|
358
|
+
`cost: $${totals.costUsd.toFixed(4)}`,
|
|
359
|
+
`wall time: ${totals.wallTimeMinutes.toFixed(1)}m`,
|
|
360
|
+
`verification PASS: ${verified}`,
|
|
361
|
+
`last-run failures: ${stalled}`,
|
|
362
|
+
"",
|
|
363
|
+
...governed.map(renderUsageLine),
|
|
364
|
+
].join("\n");
|
|
365
|
+
}
|
|
144
366
|
async function showTask(channelDir, id) {
|
|
145
367
|
const dir = tasksDir(channelDir);
|
|
146
368
|
const taskId = normalizeTaskId(id);
|
|
@@ -192,6 +414,39 @@ async function doctor(options) {
|
|
|
192
414
|
issues.push(issue(`tasks/${entry.id}.md has unreadable frontmatter; wake/status cannot be trusted.`, `Fix tasks/${entry.id}.md so it starts with readable status/wake/recurrence frontmatter.`));
|
|
193
415
|
continue;
|
|
194
416
|
}
|
|
417
|
+
if (entry.frontmatter.controlReadable === false) {
|
|
418
|
+
issues.push(issue(`tasks/${entry.id}.md has invalid control metadata; governance is fail-open but cannot be enforced.`, `Use task_manage set or repair the one-line control JSON before allowing the task to run.`));
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
const control = entry.frontmatter.control;
|
|
422
|
+
if (control) {
|
|
423
|
+
const storedTask = await readStoredTask(options.channelDir, entry.id);
|
|
424
|
+
const violation = taskBudgetViolation(control, now);
|
|
425
|
+
if (violation) {
|
|
426
|
+
issues.push(issue(`tasks/${entry.id}.md exceeds its control limit: ${violation}.`, `Review the task, then explicitly raise its budget/deadline or cancel it; the driver will escalate it.`));
|
|
427
|
+
}
|
|
428
|
+
for (const relatedId of [control.parent, ...control.dependsOn].filter((value) => Boolean(value))) {
|
|
429
|
+
if (!activeIds.has(relatedId) && !archivedIds.has(relatedId)) {
|
|
430
|
+
issues.push(issue(`tasks/${entry.id}.md points to missing related task ${relatedId}.`, `Create ${relatedId}, or remove it from parent/dependsOn with task_manage set.`));
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (control.sideEffects === "external" && control.externalApproval !== "granted") {
|
|
434
|
+
issues.push(issue(`tasks/${entry.id}.md requires external side effects but has no user approval.`, `After reviewing the proposed action, a user must run /tasks approve ${entry.id}.`));
|
|
435
|
+
}
|
|
436
|
+
if (control.externalApproval === "granted" &&
|
|
437
|
+
storedTask &&
|
|
438
|
+
control.approvalBodyHash !== taskBodyHash(storedTask.body)) {
|
|
439
|
+
issues.push(issue(`tasks/${entry.id}.md changed after external-action approval was granted.`, `Review the current action and run /tasks approve ${entry.id} again.`));
|
|
440
|
+
}
|
|
441
|
+
if (control.worktree && !existsSync(control.worktree.path)) {
|
|
442
|
+
issues.push(issue(`tasks/${entry.id}.md records a missing worktree path: ${control.worktree.path}.`, `Clear the stale worktree metadata or create/reassign an isolated worktree.`));
|
|
443
|
+
}
|
|
444
|
+
if (status !== "done" && control.verification.status === "passed" && control.verification.bodyHash) {
|
|
445
|
+
if (storedTask && taskBodyHash(storedTask.body) !== control.verification.bodyHash) {
|
|
446
|
+
issues.push(issue(`tasks/${entry.id}.md changed after its recorded independent PASS.`, `Run a fresh purpose=verify sub-agent and import its attestation before completion.`));
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
195
450
|
if (status === "done" && !isParseableSchedule(events, entry.id)) {
|
|
196
451
|
issues.push(issue(`tasks/${entry.id}.md is done but still in the active directory.`, `Ask the agent to archive one-shot task ${entry.id}, or add a parseable .schedule event if it is recurring.`));
|
|
197
452
|
}
|
|
@@ -208,8 +463,12 @@ async function doctor(options) {
|
|
|
208
463
|
if (entry.frontmatter.recurrence && !isParseableSchedule(events, entry.id)) {
|
|
209
464
|
issues.push(issue(`tasks/${entry.id}.md has recurrence but no parseable ${taskScheduleEventName(options.channelId, entry.id)} event.`, `Create or repair events/${taskScheduleEventName(options.channelId, entry.id)}.json as a periodic event.`));
|
|
210
465
|
}
|
|
466
|
+
if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
|
|
467
|
+
issues.push(issue(`tasks/${entry.id}.md has an invalid wake value (${entry.frontmatter.wake}); the native driver will treat it as due.`, `Use task_manage set or progress to replace wake with ISO8601, or clear it if the task should continue now.`));
|
|
468
|
+
}
|
|
211
469
|
const checkin = eventKey(events, entry.id, "checkin");
|
|
212
470
|
if (checkin && isTaskCheckinEvent(checkin)) {
|
|
471
|
+
issues.push(issue(`events/${checkin.filename} is a legacy task checkin; native wake handling makes it redundant.`, `Delete events/${checkin.filename} and keep the task wake value as the single resume condition.`));
|
|
213
472
|
const wakeMs = validWakeMs(entry);
|
|
214
473
|
const atMs = new Date(checkin.event.at).getTime();
|
|
215
474
|
if (wakeMs === undefined) {
|
|
@@ -219,9 +478,21 @@ async function doctor(options) {
|
|
|
219
478
|
issues.push(issue(`tasks/${entry.id}.md wake does not match its .checkin event time.`, `Sync tasks/${entry.id}.md wake with events/${checkin.filename} at ${checkin.event.at}.`));
|
|
220
479
|
}
|
|
221
480
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
481
|
+
}
|
|
482
|
+
const parentGraph = new Map();
|
|
483
|
+
const dependencyGraph = new Map();
|
|
484
|
+
for (const entry of entries) {
|
|
485
|
+
const control = entry.frontmatter.control;
|
|
486
|
+
if (!control)
|
|
487
|
+
continue;
|
|
488
|
+
parentGraph.set(entry.id, control.parent ? [control.parent] : []);
|
|
489
|
+
dependencyGraph.set(entry.id, control.dependsOn);
|
|
490
|
+
}
|
|
491
|
+
for (const cycle of relationCycles(parentGraph)) {
|
|
492
|
+
issues.push(issue(`Task parent cycle detected: ${cycle.join(" → ")}.`, `Use task_manage set to clear or correct one parent link in this cycle.`));
|
|
493
|
+
}
|
|
494
|
+
for (const cycle of relationCycles(dependencyGraph)) {
|
|
495
|
+
issues.push(issue(`Task dependency cycle detected: ${cycle.join(" → ")}.`, `Use task_manage set to remove one dependsOn edge before the driver can continue these tasks.`));
|
|
225
496
|
}
|
|
226
497
|
for (const event of events) {
|
|
227
498
|
if (!event.id || !event.use) {
|
|
@@ -268,6 +539,16 @@ export async function handleTasksCommand(options) {
|
|
|
268
539
|
return await showTask(options.channelDir, command.id);
|
|
269
540
|
case "archive":
|
|
270
541
|
return await listArchive(options.channelDir);
|
|
542
|
+
case "approve":
|
|
543
|
+
return await approveTask(options, command.id);
|
|
544
|
+
case "pause":
|
|
545
|
+
return await pauseTask(options, command.id);
|
|
546
|
+
case "resume":
|
|
547
|
+
return await resumeTask(options, command.id);
|
|
548
|
+
case "run":
|
|
549
|
+
return await runTask(options, command.id);
|
|
550
|
+
case "stats":
|
|
551
|
+
return await taskStats(options, command.id);
|
|
271
552
|
case "doctor":
|
|
272
553
|
return await doctor(options);
|
|
273
554
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { PipiclawTaskDriverSettings } from "../settings.js";
|
|
2
|
+
import { type TaskLedgerEntry } from "../shared/task-ledger.js";
|
|
3
|
+
import type { DingTalkEvent } from "./dingtalk.js";
|
|
4
|
+
export interface TaskDriverOptions {
|
|
5
|
+
workspaceDir: string;
|
|
6
|
+
getKnownChannelIds?: () => Iterable<string>;
|
|
7
|
+
isChannelActive: (channelId: string) => boolean;
|
|
8
|
+
dispatch: (event: DingTalkEvent) => boolean | Promise<boolean>;
|
|
9
|
+
getSettings: () => PipiclawTaskDriverSettings;
|
|
10
|
+
intervalMs?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
|
|
13
|
+
export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
|
|
14
|
+
/**
|
|
15
|
+
* Native, token-gated driver for the persistent task ledger.
|
|
16
|
+
*
|
|
17
|
+
* The scan itself is deterministic and cheap. It wakes at most one actionable task
|
|
18
|
+
* per channel, skips active channels, backs off unchanged ledgers, and round-robins
|
|
19
|
+
* dispatches so a busy channel cannot starve the rest. `wake` is therefore sufficient
|
|
20
|
+
* to resume a task; users do not need to install a heartbeat event or sensor script.
|
|
21
|
+
*/
|
|
22
|
+
export declare class TaskDriver {
|
|
23
|
+
private readonly options;
|
|
24
|
+
private timer;
|
|
25
|
+
private running;
|
|
26
|
+
private nextChannelIndex;
|
|
27
|
+
private readonly attempts;
|
|
28
|
+
constructor(options: TaskDriverOptions);
|
|
29
|
+
start(): void;
|
|
30
|
+
stop(): void;
|
|
31
|
+
runOnce(now?: Date): Promise<void>;
|
|
32
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import * as log from "../log.js";
|
|
4
|
+
import { taskEventName } from "../shared/task-events.js";
|
|
5
|
+
import { readActiveTasks } from "../shared/task-ledger.js";
|
|
6
|
+
import { taskBudgetViolation } from "../tasks/control.js";
|
|
7
|
+
import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim } from "../tasks/store.js";
|
|
8
|
+
import { parseScheduledEventContent } from "./events.js";
|
|
9
|
+
const DEFAULT_SCAN_INTERVAL_MS = 60_000;
|
|
10
|
+
const LEGACY_CHECKIN_HANDOFF_GRACE_MS = 2 * 60_000;
|
|
11
|
+
const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
|
|
12
|
+
function isChannelId(value) {
|
|
13
|
+
return CHANNEL_ID_PATTERN.test(value);
|
|
14
|
+
}
|
|
15
|
+
export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
|
|
16
|
+
const channels = new Set();
|
|
17
|
+
for (const channelId of knownChannelIds) {
|
|
18
|
+
if (isChannelId(channelId))
|
|
19
|
+
channels.add(channelId);
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const entries = await readdir(workspaceDir, { withFileTypes: true });
|
|
23
|
+
for (const entry of entries) {
|
|
24
|
+
if (entry.isDirectory() && isChannelId(entry.name))
|
|
25
|
+
channels.add(entry.name);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// A missing/unreadable workspace simply has no tasks to drive this tick.
|
|
30
|
+
}
|
|
31
|
+
return Array.from(channels).sort();
|
|
32
|
+
}
|
|
33
|
+
function attemptKey(channelId, taskId) {
|
|
34
|
+
return `${channelId}\0${taskId}`;
|
|
35
|
+
}
|
|
36
|
+
async function taskFingerprint(_channelDir, entry) {
|
|
37
|
+
// Do not use mtime/size here. Runtime usage accounting deliberately rewrites
|
|
38
|
+
// task control after every attempt; treating that bookkeeping as progress made
|
|
39
|
+
// governed tasks retry at the short continuation interval forever.
|
|
40
|
+
const control = entry.frontmatter.control;
|
|
41
|
+
return [
|
|
42
|
+
entry.frontmatter.readable ? "readable" : "unreadable",
|
|
43
|
+
entry.frontmatter.status ?? "",
|
|
44
|
+
entry.frontmatter.wake ?? "",
|
|
45
|
+
entry.frontmatter.recurrence ?? "",
|
|
46
|
+
entry.latestNote ?? "",
|
|
47
|
+
control?.nextAction ?? "",
|
|
48
|
+
control?.blockedReason ?? "",
|
|
49
|
+
control?.verification.status ?? "",
|
|
50
|
+
control?.cycleId ?? "",
|
|
51
|
+
].join("\0");
|
|
52
|
+
}
|
|
53
|
+
function isEligible(attempt, fingerprint, nowMs, settings) {
|
|
54
|
+
if (!attempt)
|
|
55
|
+
return true;
|
|
56
|
+
const changed = attempt.fingerprint !== fingerprint;
|
|
57
|
+
const delayMinutes = changed || !attempt.accepted ? settings.continuationDelayMinutes : settings.stalledRetryMinutes;
|
|
58
|
+
return nowMs - attempt.atMs >= delayMinutes * 60_000;
|
|
59
|
+
}
|
|
60
|
+
async function hasLiveLegacyCheckin(workspaceDir, channelId, taskId, nowMs) {
|
|
61
|
+
const name = taskEventName(channelId, taskId, "checkin");
|
|
62
|
+
const path = join(workspaceDir, "events", `${name}.json`);
|
|
63
|
+
try {
|
|
64
|
+
const event = parseScheduledEventContent(await readFile(path, "utf-8"), `${name}.json`);
|
|
65
|
+
if (event.type !== "one-shot")
|
|
66
|
+
return false;
|
|
67
|
+
const atMs = new Date(event.at).getTime();
|
|
68
|
+
return Number.isFinite(atMs) && atMs >= nowMs - LEGACY_CHECKIN_HANDOFF_GRACE_MS;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
75
|
+
const verification = entry.frontmatter.control?.verification;
|
|
76
|
+
const verificationInstruction = entry.frontmatter.status === "verifying"
|
|
77
|
+
? verification?.status === "passed"
|
|
78
|
+
? " Independent verification already passed for the current artifact; finish the task with task_manage done and specific evidence."
|
|
79
|
+
: " This task is a verification candidate: call subagent with purpose=verify and taskId, then import its runId with task_manage verify. Do not implement more changes before the verifier reports."
|
|
80
|
+
: "";
|
|
81
|
+
const repair = entry.frontmatter.readable
|
|
82
|
+
? ""
|
|
83
|
+
: " Its frontmatter is unreadable: repair it before using task_manage, and do not silently skip the task.";
|
|
84
|
+
const control = entry.frontmatter.control;
|
|
85
|
+
const capsule = [
|
|
86
|
+
`Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "open"};`,
|
|
87
|
+
entry.latestNote ? `latest=${entry.latestNote};` : "",
|
|
88
|
+
control?.nextAction ? `next=${control.nextAction};` : "",
|
|
89
|
+
control ? `budget=${control.usage.attempts}/${control.budget.maxAttempts} attempts;` : "",
|
|
90
|
+
]
|
|
91
|
+
.filter(Boolean)
|
|
92
|
+
.join(" ");
|
|
93
|
+
return {
|
|
94
|
+
type: channelId.startsWith("group_") ? "group" : "dm",
|
|
95
|
+
channelId,
|
|
96
|
+
user: "TASK_DRIVER",
|
|
97
|
+
userName: "TASK_DRIVER",
|
|
98
|
+
text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} Open tasks/${entry.id}.md, advance the next ` +
|
|
99
|
+
"concrete step, respect its control metadata (budget, dependencies, isolation, and side-effect approval), and " +
|
|
100
|
+
"verify the work against its DoD. If it remains open, atomically record what changed, the " +
|
|
101
|
+
"next step, status, and any future wake with task_manage progress (or carefully update the task file if that " +
|
|
102
|
+
"tool is unavailable). For independent verification, delegate a purpose=verify subagent and register its run " +
|
|
103
|
+
"with task_manage verify before task_manage done. Never perform external side effects unless approval is granted. " +
|
|
104
|
+
"If complete, use task_manage done with specific evidence. If no user-visible update " +
|
|
105
|
+
`is needed, respond with [SILENT].${verificationInstruction}`,
|
|
106
|
+
ts: String(nowMs),
|
|
107
|
+
conversationId: "",
|
|
108
|
+
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function taskEscalationEvent(channelId, entry, reason, nowMs) {
|
|
112
|
+
return {
|
|
113
|
+
type: channelId.startsWith("group_") ? "group" : "dm",
|
|
114
|
+
channelId,
|
|
115
|
+
user: "TASK_DRIVER",
|
|
116
|
+
userName: "TASK_DRIVER",
|
|
117
|
+
text: `[TASK_ESCALATION:${entry.id}] Task ${entry.id} (${entry.title}) was stopped by the deterministic task ` +
|
|
118
|
+
`governor: ${reason}. Inform the user concisely, explain the actionable recovery (adjust the task control ` +
|
|
119
|
+
"metadata, resolve the dependency, or explicitly cancel/reopen it), and do not continue the task in this run.",
|
|
120
|
+
ts: String(nowMs),
|
|
121
|
+
conversationId: "",
|
|
122
|
+
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function terminalDependencyReason(reason) {
|
|
126
|
+
return reason?.includes(" is missing") ||
|
|
127
|
+
reason?.includes(" is cancelled") ||
|
|
128
|
+
reason?.includes(" is escalated") ||
|
|
129
|
+
reason?.includes("dependency cycle")
|
|
130
|
+
? reason
|
|
131
|
+
: undefined;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Native, token-gated driver for the persistent task ledger.
|
|
135
|
+
*
|
|
136
|
+
* The scan itself is deterministic and cheap. It wakes at most one actionable task
|
|
137
|
+
* per channel, skips active channels, backs off unchanged ledgers, and round-robins
|
|
138
|
+
* dispatches so a busy channel cannot starve the rest. `wake` is therefore sufficient
|
|
139
|
+
* to resume a task; users do not need to install a heartbeat event or sensor script.
|
|
140
|
+
*/
|
|
141
|
+
export class TaskDriver {
|
|
142
|
+
constructor(options) {
|
|
143
|
+
this.options = options;
|
|
144
|
+
this.timer = null;
|
|
145
|
+
this.running = false;
|
|
146
|
+
this.nextChannelIndex = 0;
|
|
147
|
+
this.attempts = new Map();
|
|
148
|
+
}
|
|
149
|
+
start() {
|
|
150
|
+
if (this.timer)
|
|
151
|
+
return;
|
|
152
|
+
this.timer = setInterval(() => {
|
|
153
|
+
void this.runOnce().catch((error) => {
|
|
154
|
+
log.logWarning("Task driver tick failed", error instanceof Error ? error.message : String(error));
|
|
155
|
+
});
|
|
156
|
+
}, this.options.intervalMs ?? DEFAULT_SCAN_INTERVAL_MS);
|
|
157
|
+
this.timer.unref?.();
|
|
158
|
+
}
|
|
159
|
+
stop() {
|
|
160
|
+
if (!this.timer)
|
|
161
|
+
return;
|
|
162
|
+
clearInterval(this.timer);
|
|
163
|
+
this.timer = null;
|
|
164
|
+
}
|
|
165
|
+
async runOnce(now = new Date()) {
|
|
166
|
+
const settings = this.options.getSettings();
|
|
167
|
+
if (!settings.enabled || this.running)
|
|
168
|
+
return;
|
|
169
|
+
this.running = true;
|
|
170
|
+
try {
|
|
171
|
+
const channels = await discoverTaskChannels(this.options.workspaceDir, this.options.getKnownChannelIds?.());
|
|
172
|
+
if (channels.length === 0) {
|
|
173
|
+
this.attempts.clear();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const seen = new Set();
|
|
177
|
+
const start = this.nextChannelIndex % channels.length;
|
|
178
|
+
let dispatched = 0;
|
|
179
|
+
let lastDispatchOffset = -1;
|
|
180
|
+
for (let offset = 0; offset < channels.length; offset++) {
|
|
181
|
+
const channelId = channels[(start + offset) % channels.length];
|
|
182
|
+
if (!channelId)
|
|
183
|
+
continue;
|
|
184
|
+
const channelDir = join(this.options.workspaceDir, channelId);
|
|
185
|
+
const entries = await readActiveTasks(join(channelDir, "tasks"), now.getTime());
|
|
186
|
+
for (const entry of entries)
|
|
187
|
+
seen.add(attemptKey(channelId, entry.id));
|
|
188
|
+
if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
|
|
189
|
+
continue;
|
|
190
|
+
let governanceHandled = false;
|
|
191
|
+
for (const candidate of entries) {
|
|
192
|
+
const status = candidate.frontmatter.status;
|
|
193
|
+
const control = candidate.frontmatter.control;
|
|
194
|
+
if (!control ||
|
|
195
|
+
status === "done" ||
|
|
196
|
+
status === "cancelled" ||
|
|
197
|
+
status === "escalated" ||
|
|
198
|
+
status === "paused")
|
|
199
|
+
continue;
|
|
200
|
+
const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
|
|
201
|
+
const escalationReason = taskBudgetViolation(control, now.getTime()) ?? terminalDependencyReason(dependencies.reason);
|
|
202
|
+
if (!escalationReason)
|
|
203
|
+
continue;
|
|
204
|
+
governanceHandled = true;
|
|
205
|
+
const accepted = await this.options.dispatch(taskEscalationEvent(channelId, candidate, escalationReason, now.getTime()));
|
|
206
|
+
if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
|
|
207
|
+
dispatched++;
|
|
208
|
+
lastDispatchOffset = offset;
|
|
209
|
+
log.logWarning(`[${channelId}] Task driver escalated ${candidate.id}`, escalationReason);
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
if (governanceHandled)
|
|
214
|
+
continue;
|
|
215
|
+
const candidates = entries.filter((candidate) => candidate.actionable);
|
|
216
|
+
if (candidates.length === 0)
|
|
217
|
+
continue;
|
|
218
|
+
let entry;
|
|
219
|
+
for (const candidate of candidates) {
|
|
220
|
+
const control = candidate.frontmatter.control;
|
|
221
|
+
if (!control) {
|
|
222
|
+
entry = candidate;
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
|
|
226
|
+
if (!dependencies.ready)
|
|
227
|
+
continue;
|
|
228
|
+
entry = candidate;
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
if (!entry || dispatched >= settings.maxDispatchesPerTick)
|
|
232
|
+
continue;
|
|
233
|
+
// Upgrade compatibility: while a legacy task-owned one-shot is still
|
|
234
|
+
// about to deliver this same wake, let it own the handoff. Once it is
|
|
235
|
+
// consumed (or stale for >2m), the native driver becomes the recovery path.
|
|
236
|
+
if (await hasLiveLegacyCheckin(this.options.workspaceDir, channelId, entry.id, now.getTime())) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const key = attemptKey(channelId, entry.id);
|
|
240
|
+
let fingerprint = await taskFingerprint(channelDir, entry);
|
|
241
|
+
if (!isEligible(this.attempts.get(key), fingerprint, now.getTime(), settings))
|
|
242
|
+
continue;
|
|
243
|
+
const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
|
|
244
|
+
if (claim) {
|
|
245
|
+
fingerprint = await taskFingerprint(channelDir, entry);
|
|
246
|
+
}
|
|
247
|
+
const accepted = await this.options.dispatch(createTaskDriverEvent(channelId, entry, now.getTime()));
|
|
248
|
+
if (!accepted && claim)
|
|
249
|
+
await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
|
|
250
|
+
this.attempts.set(key, { fingerprint, atMs: now.getTime(), accepted });
|
|
251
|
+
if (accepted) {
|
|
252
|
+
dispatched++;
|
|
253
|
+
lastDispatchOffset = offset;
|
|
254
|
+
log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
for (const key of this.attempts.keys()) {
|
|
261
|
+
if (!seen.has(key))
|
|
262
|
+
this.attempts.delete(key);
|
|
263
|
+
}
|
|
264
|
+
this.nextChannelIndex = (start + (lastDispatchOffset >= 0 ? lastDispatchOffset + 1 : 1)) % channels.length;
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
this.running = false;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|