@oyasmi/pipiclaw 0.7.6 → 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 +13 -0
- package/dist/agent/channel-runner.d.ts +3 -0
- package/dist/agent/channel-runner.js +14 -4
- package/dist/agent/commands.js +8 -2
- package/dist/agent/prompt-builder.js +46 -0
- package/dist/agent/session-events.js +5 -0
- package/dist/agent/types.d.ts +2 -0
- package/dist/memory/recall.js +6 -0
- package/dist/memory/task-digest.js +17 -0
- package/dist/models/api-keys.d.ts +5 -1
- package/dist/models/api-keys.js +10 -4
- package/dist/runtime/bootstrap.d.ts +5 -0
- package/dist/runtime/bootstrap.js +59 -2
- package/dist/runtime/dingtalk.d.ts +2 -0
- package/dist/runtime/dingtalk.js +13 -1
- 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 +9 -0
- package/dist/runtime/task-commands.js +429 -2
- 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/atomic-file.js +23 -3
- package/dist/shared/task-events.d.ts +32 -0
- package/dist/shared/task-events.js +29 -0
- package/dist/shared/task-ledger.d.ts +53 -0
- package/dist/shared/task-ledger.js +246 -8
- package/dist/subagents/tool.d.ts +13 -0
- package/dist/subagents/tool.js +229 -15
- 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 -4
- package/dist/tools/task-manage.d.ts +51 -3
- package/dist/tools/task-manage.js +491 -37
- package/dist/tools/web-fetch.js +3 -0
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.js +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { readdir, readFile } from "node:fs/promises";
|
|
3
3
|
import { join, resolve, sep } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { isTaskCheckinEvent, isTaskScheduleEvent, parseTaskEventName, taskEventPrefix, taskScheduleEventName, } from "../shared/task-events.js";
|
|
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";
|
|
8
|
+
import { parseScheduledEventContent } from "./events.js";
|
|
5
9
|
function usage() {
|
|
6
10
|
return `# Tasks
|
|
7
11
|
|
|
@@ -9,7 +13,13 @@ Usage:
|
|
|
9
13
|
|
|
10
14
|
- \`/tasks\` — list active tasks in this channel
|
|
11
15
|
- \`/tasks show <id>\` — show a single task file (active or archived)
|
|
12
|
-
- \`/tasks archive\` — list archived (closed) tasks
|
|
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
|
|
22
|
+
- \`/tasks doctor\` — check task/event consistency without changing files`;
|
|
13
23
|
}
|
|
14
24
|
function parseTasksCommand(args) {
|
|
15
25
|
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
@@ -30,6 +40,35 @@ function parseTasksCommand(args) {
|
|
|
30
40
|
throw new Error("Usage: /tasks archive");
|
|
31
41
|
return { action: "archive" };
|
|
32
42
|
}
|
|
43
|
+
if (action === "doctor") {
|
|
44
|
+
if (parts.length > 1)
|
|
45
|
+
throw new Error("Usage: /tasks doctor");
|
|
46
|
+
return { action: "doctor" };
|
|
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
|
+
}
|
|
33
72
|
throw new Error(`Unknown /tasks action: ${action}`);
|
|
34
73
|
}
|
|
35
74
|
function tasksDir(channelDir) {
|
|
@@ -56,6 +95,96 @@ function relativeWake(wakeMs, now) {
|
|
|
56
95
|
const rel = minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.round(minutes / 60)}h` : `${Math.round(minutes / 1440)}d`;
|
|
57
96
|
return `${iso} (${rel})`;
|
|
58
97
|
}
|
|
98
|
+
function eventDir(workspaceDir) {
|
|
99
|
+
return join(workspaceDir, "events");
|
|
100
|
+
}
|
|
101
|
+
async function readArchivedTaskIds(channelDir) {
|
|
102
|
+
const archiveDir = join(tasksDir(channelDir), "archive");
|
|
103
|
+
const ids = new Set();
|
|
104
|
+
if (!existsSync(archiveDir))
|
|
105
|
+
return ids;
|
|
106
|
+
for (const filename of await readdir(archiveDir)) {
|
|
107
|
+
if (filename.endsWith(".md"))
|
|
108
|
+
ids.add(filename.slice(0, -".md".length));
|
|
109
|
+
}
|
|
110
|
+
return ids;
|
|
111
|
+
}
|
|
112
|
+
async function readTaskEvents(workspaceDir, channelId) {
|
|
113
|
+
const dir = eventDir(workspaceDir);
|
|
114
|
+
if (!existsSync(dir))
|
|
115
|
+
return [];
|
|
116
|
+
const prefix = taskEventPrefix(channelId);
|
|
117
|
+
const events = [];
|
|
118
|
+
for (const filename of (await readdir(dir)).filter((name) => name.endsWith(".json")).sort()) {
|
|
119
|
+
const name = filename.slice(0, -".json".length);
|
|
120
|
+
if (!name.startsWith(prefix))
|
|
121
|
+
continue;
|
|
122
|
+
const split = parseTaskEventName(name, channelId);
|
|
123
|
+
const info = { filename, name, ...(split ?? {}) };
|
|
124
|
+
try {
|
|
125
|
+
info.event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
info.error = error instanceof Error ? error.message : String(error);
|
|
129
|
+
}
|
|
130
|
+
events.push(info);
|
|
131
|
+
}
|
|
132
|
+
return events;
|
|
133
|
+
}
|
|
134
|
+
function eventKey(events, id, use) {
|
|
135
|
+
return events.find((event) => event.id === id && event.use === use);
|
|
136
|
+
}
|
|
137
|
+
function isParseableSchedule(events, id) {
|
|
138
|
+
const schedule = eventKey(events, id, "schedule");
|
|
139
|
+
return schedule ? isTaskScheduleEvent(schedule) : false;
|
|
140
|
+
}
|
|
141
|
+
function validWakeMs(entry) {
|
|
142
|
+
const wake = entry.frontmatter.wake;
|
|
143
|
+
if (!wake)
|
|
144
|
+
return undefined;
|
|
145
|
+
const ms = new Date(wake).getTime();
|
|
146
|
+
return Number.isFinite(ms) ? ms : undefined;
|
|
147
|
+
}
|
|
148
|
+
function issue(problem, nextStep) {
|
|
149
|
+
return `- ${problem}\n Next step: ${nextStep}`;
|
|
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
|
+
}
|
|
180
|
+
async function readActiveTaskContent(channelDir, id) {
|
|
181
|
+
try {
|
|
182
|
+
return await readFile(join(tasksDir(channelDir), `${id}.md`), "utf-8");
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
59
188
|
async function listTasks(channelDir) {
|
|
60
189
|
const dir = tasksDir(channelDir);
|
|
61
190
|
const now = Date.now();
|
|
@@ -66,12 +195,174 @@ async function listTasks(channelDir) {
|
|
|
66
195
|
const blocks = entries.map((entry) => {
|
|
67
196
|
const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
|
|
68
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
|
+
}
|
|
69
219
|
if (entry.frontmatter.recurrence)
|
|
70
220
|
detail.push(`recurrence: ${entry.frontmatter.recurrence}`);
|
|
71
221
|
return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
|
|
72
222
|
});
|
|
73
223
|
return `# Tasks: ${entries.length} active\n\n${blocks.join("\n")}`;
|
|
74
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
|
+
}
|
|
75
366
|
async function showTask(channelDir, id) {
|
|
76
367
|
const dir = tasksDir(channelDir);
|
|
77
368
|
const taskId = normalizeTaskId(id);
|
|
@@ -107,6 +398,130 @@ async function listArchive(channelDir) {
|
|
|
107
398
|
}
|
|
108
399
|
return `# Archived Tasks: ${blocks.length}\n\n${blocks.join("\n")}`;
|
|
109
400
|
}
|
|
401
|
+
async function doctor(options) {
|
|
402
|
+
if (!options.workspaceDir || !options.channelId) {
|
|
403
|
+
return "# Task Doctor\n\nNot available: workspaceDir and channelId are required.";
|
|
404
|
+
}
|
|
405
|
+
const now = Date.now();
|
|
406
|
+
const entries = await readActiveTasks(tasksDir(options.channelDir), now);
|
|
407
|
+
const activeIds = new Set(entries.map((entry) => entry.id));
|
|
408
|
+
const archivedIds = await readArchivedTaskIds(options.channelDir);
|
|
409
|
+
const events = await readTaskEvents(options.workspaceDir, options.channelId);
|
|
410
|
+
const issues = [];
|
|
411
|
+
for (const entry of entries) {
|
|
412
|
+
const status = entry.frontmatter.status ?? "open";
|
|
413
|
+
if (!entry.frontmatter.readable) {
|
|
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.`));
|
|
415
|
+
continue;
|
|
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
|
+
}
|
|
450
|
+
if (status === "done" && !isParseableSchedule(events, entry.id)) {
|
|
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.`));
|
|
452
|
+
}
|
|
453
|
+
const content = await readActiveTaskContent(options.channelDir, entry.id);
|
|
454
|
+
if (content === undefined) {
|
|
455
|
+
issues.push(issue(`tasks/${entry.id}.md could not be read during doctor checks.`, `Open tasks/${entry.id}.md manually and repair permissions or file contents.`));
|
|
456
|
+
}
|
|
457
|
+
else {
|
|
458
|
+
const missing = missingStandardTaskSections(content);
|
|
459
|
+
if (missing.length > 0) {
|
|
460
|
+
issues.push(issue(`tasks/${entry.id}.md is missing standard section(s): ${missing.join(", ")}.`, `Ask the agent to normalize tasks/${entry.id}.md to the standard task skeleton.`));
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (entry.frontmatter.recurrence && !isParseableSchedule(events, entry.id)) {
|
|
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.`));
|
|
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
|
+
}
|
|
469
|
+
const checkin = eventKey(events, entry.id, "checkin");
|
|
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.`));
|
|
472
|
+
const wakeMs = validWakeMs(entry);
|
|
473
|
+
const atMs = new Date(checkin.event.at).getTime();
|
|
474
|
+
if (wakeMs === undefined) {
|
|
475
|
+
issues.push(issue(`tasks/${entry.id}.md has a .checkin event but no valid wake value.`, `Set tasks/${entry.id}.md wake to ${checkin.event.at}, or delete the stale .checkin event.`));
|
|
476
|
+
}
|
|
477
|
+
else if (Number.isFinite(atMs) && Math.abs(atMs - wakeMs) > 60_000) {
|
|
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}.`));
|
|
479
|
+
}
|
|
480
|
+
}
|
|
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.`));
|
|
496
|
+
}
|
|
497
|
+
for (const event of events) {
|
|
498
|
+
if (!event.id || !event.use) {
|
|
499
|
+
issues.push(issue(`events/${event.filename} does not follow task.<channelId>.<taskId>.<use>.json.`, "Rename the event to the task-owned naming convention or manage it as a normal event."));
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
if (event.error) {
|
|
503
|
+
issues.push(issue(`events/${event.filename} is not parseable: ${event.error}`, `Fix or delete events/${event.filename}; invalid task-owned events cannot be trusted.`));
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
if (!activeIds.has(event.id) && !archivedIds.has(event.id)) {
|
|
507
|
+
issues.push(issue(`events/${event.filename} points to missing task ${event.id}.`, `Delete events/${event.filename}, or recreate tasks/${event.id}.md if that task still exists conceptually.`));
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
if (archivedIds.has(event.id)) {
|
|
511
|
+
issues.push(issue(`events/${event.filename} points to archived task ${event.id}; closed tasks should have no live events.`, `Delete events/${event.filename}; archived tasks should not wake the agent.`));
|
|
512
|
+
}
|
|
513
|
+
if (event.use === "schedule" && !isTaskScheduleEvent(event)) {
|
|
514
|
+
issues.push(issue(`events/${event.filename} is a schedule event but is not periodic.`, `Change events/${event.filename} to type periodic, or rename it away from .schedule.`));
|
|
515
|
+
}
|
|
516
|
+
if (event.use === "checkin" && !isTaskCheckinEvent(event)) {
|
|
517
|
+
issues.push(issue(`events/${event.filename} is a checkin event but is not one-shot.`, `Change events/${event.filename} to type one-shot, or rename it away from .checkin.`));
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
if (issues.length === 0) {
|
|
521
|
+
return "# Task Doctor\n\nNo task ledger issues found.";
|
|
522
|
+
}
|
|
523
|
+
return `# Task Doctor\n\nFound ${issues.length} issue${issues.length === 1 ? "" : "s"}:\n\n${issues.join("\n")}`;
|
|
524
|
+
}
|
|
110
525
|
export async function handleTasksCommand(options) {
|
|
111
526
|
let command;
|
|
112
527
|
try {
|
|
@@ -124,6 +539,18 @@ export async function handleTasksCommand(options) {
|
|
|
124
539
|
return await showTask(options.channelDir, command.id);
|
|
125
540
|
case "archive":
|
|
126
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);
|
|
552
|
+
case "doctor":
|
|
553
|
+
return await doctor(options);
|
|
127
554
|
}
|
|
128
555
|
}
|
|
129
556
|
catch (error) {
|
|
@@ -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
|
+
}
|