@oyasmi/pipiclaw 0.8.8-beta.2 → 0.8.9-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +8 -0
  3. package/dist/agent/runner-factory.d.ts +2 -0
  4. package/dist/memory/task-digest.js +1 -1
  5. package/dist/playbooks/task-closeout.md +11 -10
  6. package/dist/playbooks/task-delegation.md +1 -1
  7. package/dist/playbooks/task-driving.md +6 -7
  8. package/dist/playbooks/task-planning.md +7 -5
  9. package/dist/playbooks/task-recurring.md +7 -4
  10. package/dist/playbooks/task-repair.md +7 -7
  11. package/dist/runtime/bootstrap.d.ts +12 -1
  12. package/dist/runtime/bootstrap.js +9 -1
  13. package/dist/runtime/task-commands.js +29 -51
  14. package/dist/runtime/task-driver.d.ts +3 -8
  15. package/dist/runtime/task-driver.js +97 -84
  16. package/dist/runtime/task-migration.d.ts +11 -0
  17. package/dist/runtime/task-migration.js +70 -0
  18. package/dist/security/path-guard.js +3 -1
  19. package/dist/shared/task-events.d.ts +0 -26
  20. package/dist/shared/task-events.js +0 -15
  21. package/dist/shared/task-ledger.d.ts +23 -1
  22. package/dist/shared/task-ledger.js +65 -16
  23. package/dist/tasks/control.d.ts +4 -0
  24. package/dist/tasks/control.js +3 -0
  25. package/dist/tasks/store.d.ts +28 -1
  26. package/dist/tasks/store.js +63 -6
  27. package/dist/tasks/transitions.d.ts +40 -0
  28. package/dist/tasks/transitions.js +81 -0
  29. package/dist/tools/task-manage/create.d.ts +2 -0
  30. package/dist/tools/task-manage/create.js +34 -0
  31. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  32. package/dist/tools/task-manage/lifecycle.js +196 -0
  33. package/dist/tools/task-manage/schema.d.ts +43 -0
  34. package/dist/tools/task-manage/schema.js +89 -0
  35. package/dist/tools/task-manage/shared.d.ts +36 -0
  36. package/dist/tools/task-manage/shared.js +246 -0
  37. package/dist/tools/task-manage/types.d.ts +53 -0
  38. package/dist/tools/task-manage/types.js +1 -0
  39. package/dist/tools/task-manage/verification.d.ts +16 -0
  40. package/dist/tools/task-manage/verification.js +111 -0
  41. package/dist/tools/task-manage.d.ts +9 -89
  42. package/dist/tools/task-manage.js +8 -696
  43. package/package.json +5 -1
@@ -1,698 +1,13 @@
1
- import { existsSync } from "node:fs";
2
- import { mkdir, readdir, readFile, rename, unlink } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { Type } from "typebox";
5
- import { parseScheduledEventContent } from "../runtime/events.js";
6
- import { writeFileAtomically } from "../shared/atomic-file.js";
7
- import { isTaskScheduleEvent, taskEventPrefix, taskScheduleEventFilename } from "../shared/task-events.js";
8
- import { appendCurrentCycleNote, normalizeTaskId, parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, renderTaskDocument, startTaskCycle, taskBody, uncheckedTaskAcceptanceItems, } from "../shared/task-ledger.js";
9
- import { nextTaskWake, validateTaskSchedule } from "../shared/task-schedule.js";
10
- import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
11
- import { applyTaskControlPatch, createDefaultTaskControl, invalidateTaskApproval, invalidateTaskVerification, resetTaskControlForCycle, } from "../tasks/control.js";
12
- import { dependencyState, readStoredTask, taskBodyHash } from "../tasks/store.js";
13
- import { readVerificationAttestation } from "../tasks/verification.js";
14
- const SETTABLE_STATUSES = ["open", "in-progress", "awaiting-user", "blocked", "paused"];
15
- const taskControlSchema = Type.Object({
16
- priority: Type.Optional(Type.Union([Type.Literal("low"), Type.Literal("normal"), Type.Literal("high"), Type.Literal("critical")])),
17
- deadline: Type.Optional(Type.String({ description: "ISO8601 deadline; empty string clears it." })),
18
- nextAction: Type.Optional(Type.String({ description: "Concrete next executable step; empty string clears it." })),
19
- lastOutcome: Type.Optional(Type.Union([
20
- Type.Literal("pending"),
21
- Type.Literal("running"),
22
- Type.Literal("progress"),
23
- Type.Literal("blocked"),
24
- Type.Literal("failed"),
25
- Type.Literal("verified"),
26
- ])),
27
- blockedReason: Type.Optional(Type.String({ description: "Why work cannot currently proceed; empty clears it." })),
28
- parent: Type.Optional(Type.String({ description: "Parent task id; empty clears it." })),
29
- dependsOn: Type.Optional(Type.Array(Type.String(), { description: "Task ids that must be done first." })),
30
- isolation: Type.Optional(Type.Union([Type.Literal("shared"), Type.Literal("worktree")])),
31
- sideEffects: Type.Optional(Type.Union([Type.Literal("read-only"), Type.Literal("workspace"), Type.Literal("external")])),
32
- externalApproval: Type.Optional(Type.Union([Type.Literal("not-required"), Type.Literal("required")], {
33
- description: 'External approval can only be granted by a user with "/tasks approve <id>".',
34
- })),
35
- maxAttempts: Type.Optional(Type.Integer({ minimum: 1 })),
36
- maxTokens: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
37
- maxCostUsd: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
38
- maxWallTimeMinutes: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
39
- verificationMode: Type.Optional(Type.Union([Type.Literal("evidence"), Type.Literal("independent")], {
40
- description: 'On create, defaults to "evidence" (maker self-checks the DoD against concrete evidence). Set "independent" only when the task produces a checkable artifact (code, config, a runnable command) that a separate read-only verifier sub-agent can inspect — for research/writing/reminder-style tasks, "evidence" is cheaper and just as trustworthy.',
41
- })),
42
- worktreePath: Type.Optional(Type.String({ description: "Owned worktree path; empty clears it." })),
43
- worktreeBranch: Type.Optional(Type.String()),
44
- });
45
- const taskManageSchema = Type.Object({
46
- label: Type.String({ description: "Brief description of the ledger change (shown to the user)" }),
47
- action: Type.Union([
48
- Type.Literal("create"),
49
- Type.Literal("progress"),
50
- Type.Literal("set"),
51
- Type.Literal("verify"),
52
- Type.Literal("done"),
53
- Type.Literal("cancel"),
54
- Type.Literal("start-cycle"),
55
- Type.Literal("candidate"),
56
- Type.Literal("list"),
57
- ], {
58
- description: '"create" writes a governed task; "progress" atomically checkpoints work; "candidate" requests independent verification; "set" repairs metadata; "verify" imports an independent verifier attestation; "done" closes verified work; "cancel" closes abandoned work; "start-cycle" opens a completed recurring task; "list" returns tasks.',
59
- }),
60
- id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/progress/set/done." })),
61
- title: Type.Optional(Type.String({ description: "Required for create: task title used as the H1 heading." })),
62
- goal: Type.Optional(Type.String({ description: "Required for create: concise task goal." })),
63
- dod: Type.Optional(Type.String({
64
- description: 'Required for create: acceptance criteria as Markdown checklist items, one per line, e.g. "- [ ] <criterion>". Plain prose or a numbered list without checkboxes is rejected — candidate/done can only verify items that are checkable.',
65
- })),
66
- manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
67
- verificationPlan: Type.Optional(Type.String({ description: "Optional for create: deterministic checks the verifier must perform." })),
68
- control: Type.Optional(taskControlSchema),
69
- status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/progress/set. To close a task use action done, not status." })),
70
- wake: Type.Optional(Type.String({
71
- description: "ISO8601 earliest-recheck time for create/progress/set; empty string clears it. The native task driver resumes it; no .checkin event is needed.",
72
- })),
73
- schedule: Type.Optional(Type.String({
74
- description: "Five-field cron cadence (host timezone) that makes this a recurring task; empty string clears it. " +
75
- "On done, the driver sleeps the task until the next occurrence and re-opens it with start-cycle. Min every 30 minutes.",
76
- })),
77
- recurrence: Type.Optional(Type.String({ description: "Human annotation only (e.g. 每周一); empty string clears it." })),
78
- note: Type.Optional(Type.String({
79
- description: "Required for progress: concise Current Cycle entry covering what changed, evidence observed, and the next step.",
80
- })),
81
- verifierRunId: Type.Optional(Type.String({ description: "Required for verify: run id returned by a purpose=verify sub-agent." })),
82
- summary: Type.Optional(Type.String({ description: "Required for done: concise completion summary." })),
83
- evidence: Type.Optional(Type.String({
84
- description: "Required for done: verification evidence (tests, commands, review result, external confirmation, or a clear not-run reason).",
85
- })),
86
- residualRisk: Type.Optional(Type.String({ description: "Optional for done: remaining risk or follow-up note." })),
87
- reason: Type.Optional(Type.String({ description: "Required for cancel: why the task was abandoned." })),
88
- cycleId: Type.Optional(Type.String({ description: "Required for start-cycle: stable id for the newly opened recurring cycle." })),
89
- });
90
- function parseAction(action) {
91
- if (action === "create" ||
92
- action === "progress" ||
93
- action === "candidate" ||
94
- action === "set" ||
95
- action === "verify" ||
96
- action === "done" ||
97
- action === "cancel" ||
98
- action === "start-cycle" ||
99
- action === "list") {
100
- return action;
101
- }
102
- throw new Error("Unsupported task action. Use create, progress, candidate, set, verify, done, cancel, start-cycle, or list.");
103
- }
104
- function tasksDir(options) {
105
- return join(options.channelDir, "tasks");
106
- }
107
- function eventsDir(options) {
108
- return join(options.workspaceDir, "events");
109
- }
110
- function renderTaskFile(fields, body) {
111
- return renderTaskDocument(fields, body);
112
- }
113
- function requiredField(value, field, action) {
114
- const trimmed = value?.trim();
115
- if (!trimmed) {
116
- throw new Error(`action "${action}" requires ${field}.`);
117
- }
118
- return trimmed;
119
- }
120
- function requireNonEmpty(value, field) {
121
- return requiredField(value, field, "done");
122
- }
123
- function markdownValue(value) {
124
- const lines = value.trim().split(/\r?\n/);
125
- if (lines.length === 1)
126
- return lines[0];
127
- return lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join("\n");
128
- }
129
- function appendCompletionEvidence(body, request) {
130
- const summary = requireNonEmpty(request.summary, "summary");
131
- const evidence = requireNonEmpty(request.evidence, "evidence");
132
- const lines = [
133
- "## Completion Evidence",
134
- "",
135
- `- Summary: ${markdownValue(summary)}`,
136
- `- Evidence: ${markdownValue(evidence)}`,
137
- ];
138
- const residualRisk = request.residualRisk?.trim();
139
- if (residualRisk) {
140
- lines.push(`- Residual risk: ${markdownValue(residualRisk)}`);
141
- }
142
- const normalizedBody = body.endsWith("\n") ? body.replace(/\n+$/, "\n") : `${body}\n`;
143
- return `${normalizedBody}\n${lines.join("\n")}\n`;
144
- }
145
- function normalizeCreateStatus(status) {
146
- if (status === undefined)
147
- return "open";
148
- if (SETTABLE_STATUSES.includes(status)) {
149
- return status;
150
- }
151
- throw new Error(`Invalid status "${status}". Use one of ${SETTABLE_STATUSES.join(", ")}.`);
152
- }
153
- function renderTaskSkeleton(request) {
154
- const title = requiredField(request.title, "title", "create");
155
- const goal = requiredField(request.goal, "goal", "create");
156
- const dod = requiredField(request.dod, "dod", "create");
157
- // Independent verification is a real tax (an extra dispatch round plus a verifier
158
- // sub-agent run) that only pays off when there is something a read-only verifier can
159
- // actually check. Default to evidence (maker self-checks the DoD); the tool schema asks
160
- // the model to opt into independent explicitly for tasks with a checkable artifact.
161
- const mode = request.control?.verificationMode ?? "evidence";
162
- const control = applyTaskControlPatch(createDefaultTaskControl(mode), request.control ?? {});
163
- const fields = applySet({ status: normalizeCreateStatus(request.status), control }, request);
164
- const body = renderStandardTaskBody({
165
- title,
166
- goal,
167
- dod,
168
- manual: request.manual,
169
- verificationPlan: request.verificationPlan,
170
- verificationMode: control.verification.mode,
171
- });
172
- return { fields, body };
173
- }
174
- /**
175
- * Read a task file and split it into validated frontmatter and a verbatim body.
176
- * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
177
- * rather than guessed at, so task_manage never silently mangles a body.
178
- */
179
- async function readTaskDocument(taskPath, id, allowControlRepair = false) {
180
- if (!existsSync(taskPath)) {
181
- throw new Error(`Task "${id}" does not exist; create it with task_manage action "create" first.`);
182
- }
183
- const content = await readFile(taskPath, "utf-8");
184
- const frontmatter = parseTaskFrontmatter(content);
185
- if (!frontmatter.readable) {
186
- throw new Error(`Task "${id}" has no readable frontmatter; fix it with edit before using task_manage.`);
187
- }
188
- if (frontmatter.controlReadable === false && !allowControlRepair) {
189
- throw new Error(`Task "${id}" has invalid control metadata; repair it with task_manage action "set" and an explicit control patch first.`);
190
- }
191
- return {
192
- fields: {
193
- status: frontmatter.status ?? "open",
194
- wake: frontmatter.wake,
195
- schedule: frontmatter.schedule,
196
- recurrence: frontmatter.recurrence,
197
- control: frontmatter.control,
198
- },
199
- body: taskBody(content),
200
- };
201
- }
202
- /** Apply a `set` request's optional fields onto the existing frontmatter. */
203
- function applySet(fields, request) {
204
- const next = { ...fields };
205
- if (request.control?.externalApproval === "granted") {
206
- throw new Error('Only a user can grant external-action approval with "/tasks approve <id>".');
207
- }
208
- if (request.status !== undefined) {
209
- if (!SETTABLE_STATUSES.includes(request.status)) {
210
- throw new Error(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or action "done".`);
211
- }
212
- next.status = request.status;
213
- }
214
- if (request.wake !== undefined) {
215
- const trimmed = request.wake.trim();
216
- if (trimmed === "") {
217
- next.wake = undefined;
218
- }
219
- else if (!Number.isFinite(new Date(trimmed).getTime())) {
220
- throw new Error(`wake "${request.wake}" is not a valid ISO8601 date.`);
221
- }
222
- else {
223
- next.wake = trimmed;
224
- }
225
- }
226
- if (request.schedule !== undefined) {
227
- const trimmed = request.schedule.trim();
228
- if (trimmed === "") {
229
- next.schedule = undefined;
230
- }
231
- else {
232
- validateTaskSchedule(trimmed);
233
- next.schedule = trimmed;
234
- }
235
- }
236
- if (request.recurrence !== undefined) {
237
- const trimmed = request.recurrence.trim();
238
- next.recurrence = trimmed === "" ? undefined : trimmed;
239
- }
240
- if (request.control !== undefined) {
241
- next.control = applyTaskControlPatch(next.control ?? createDefaultTaskControl("evidence"), request.control);
242
- }
243
- // A done recurring task sleeps until its next occurrence; changing the cadence of a
244
- // task that is currently done recomputes that wake in the same atomic write.
245
- if (next.status === "done" && next.schedule) {
246
- const nextWake = nextTaskWake(next.schedule);
247
- next.wake = nextWake ? nextWake.toISOString() : undefined;
248
- }
249
- return next;
250
- }
251
- async function validateTaskRelations(options, id, fields) {
252
- const control = fields.control;
253
- if (!control)
254
- return;
255
- if (control.parent === id || control.dependsOn.includes(id)) {
256
- throw new Error(`Task "${id}" cannot be its own parent or dependency.`);
257
- }
258
- for (const relatedId of [control.parent, ...control.dependsOn].filter((value) => Boolean(value))) {
259
- const active = join(tasksDir(options), `${relatedId}.md`);
260
- const archived = join(tasksDir(options), "archive", `${relatedId}.md`);
261
- if (!existsSync(active) && !existsSync(archived)) {
262
- throw new Error(`Related task "${relatedId}" does not exist; create it before linking task "${id}".`);
263
- }
264
- }
265
- if (control.parent) {
266
- const visited = new Set();
267
- let current = control.parent;
268
- while (current) {
269
- if (visited.has(current)) {
270
- throw new Error(`Existing parent chain for "${control.parent}" already contains a cycle.`);
271
- }
272
- if (current === id) {
273
- throw new Error(`Task parent cycle detected while linking "${id}" to "${control.parent}".`);
274
- }
275
- visited.add(current);
276
- const task = await readStoredTask(options.channelDir, current, true);
277
- current = task?.fields.control?.parent;
278
- }
279
- }
280
- for (const dependencyId of control.dependsOn) {
281
- const visited = new Set();
282
- const stack = [dependencyId];
283
- while (stack.length > 0) {
284
- const current = stack.pop();
285
- if (!current || visited.has(current))
286
- continue;
287
- if (current === id) {
288
- throw new Error(`Task dependency cycle detected while linking "${id}" to "${dependencyId}".`);
289
- }
290
- visited.add(current);
291
- const task = await readStoredTask(options.channelDir, current, true);
292
- stack.push(...(task?.fields.control?.dependsOn ?? []));
293
- }
294
- }
295
- }
296
- async function createTask(options, request) {
297
- if (!request.id)
298
- throw new Error('action "create" requires an id.');
299
- const id = normalizeTaskId(request.id);
300
- const dir = tasksDir(options);
301
- const taskPath = join(dir, `${id}.md`);
302
- const archivePath = join(dir, "archive", `${id}.md`);
303
- if (existsSync(taskPath)) {
304
- throw new Error(`Task "${id}" already exists; use action "set" or edit the body instead.`);
305
- }
306
- if (existsSync(archivePath)) {
307
- throw new Error(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
308
- }
309
- const { fields, body } = renderTaskSkeleton(request);
310
- const badDod = uncheckedTaskAcceptanceItems(body).find((item) => item.startsWith("DoD has no checklist items"));
311
- if (badDod)
312
- throw new Error(badDod);
313
- await validateTaskRelations(options, id, fields);
314
- await mkdir(dir, { recursive: true });
315
- await writeFileAtomically(taskPath, renderTaskFile(fields, body));
316
- return {
317
- action: "create",
318
- id,
319
- path: taskPath,
320
- status: fields.status,
321
- notice: `已创建任务 \`${id}\`(status: ${fields.status})。`,
322
- };
323
- }
1
+ import { createTask } from "./task-manage/create.js";
2
+ import { cancelTask, doneTask, listTasks, progressTask, setTask } from "./task-manage/lifecycle.js";
3
+ import { parseAction, taskManageSchema } from "./task-manage/schema.js";
4
+ import { candidateTask, verifyTask } from "./task-manage/verification.js";
324
5
  /**
325
- * On close-out, keep only the task's recurring cadence event
326
- * (`task.<channelId>.<id>.schedule`) and delete every other task-owned event.
327
- *
328
- * A task may also own temporary periodic sensor/check-in events.
329
- * Those are lifecycle check-ins, not proof that the task itself is recurring, so they
330
- * must not prevent a one-shot task from being archived.
6
+ * The `task_manage` dispatcher. Each action lives in a focused module — `create`,
7
+ * `lifecycle` (progress/set/done/cancel/list) and `verification` (candidate/verify) — over a
8
+ * shared helper layer, with the status transition table in `src/tasks/transitions.ts` (spec
9
+ * 029, D7). This entry only routes and wraps the tool.
331
10
  */
332
- async function cleanupTaskEvents(options, id, preserveSchedule = true) {
333
- const dir = eventsDir(options);
334
- if (!existsSync(dir))
335
- return { deleted: [], hasSchedule: false };
336
- const prefix = taskEventPrefix(options.channelId, id);
337
- const scheduleFilename = taskScheduleEventFilename(options.channelId, id);
338
- const deleted = [];
339
- let hasSchedule = false;
340
- for (const filename of (await readdir(dir)).sort()) {
341
- if (!filename.endsWith(".json") || !filename.startsWith(prefix))
342
- continue;
343
- const eventPath = join(dir, filename);
344
- let type;
345
- try {
346
- type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename).type;
347
- }
348
- catch {
349
- continue; // can't classify → leave it for /events to handle
350
- }
351
- if (preserveSchedule &&
352
- filename === scheduleFilename &&
353
- isTaskScheduleEvent({ use: "schedule", event: { type } })) {
354
- hasSchedule = true; // the cadence lives on for the next cycle
355
- continue;
356
- }
357
- await unlink(eventPath);
358
- deleted.push(filename.slice(0, -".json".length));
359
- }
360
- return { deleted, hasSchedule };
361
- }
362
- /**
363
- * Migration compat: a task may still carry a legacy canonical `.schedule` periodic event
364
- * as its cadence truth (pre-027). `start-cycle` accepts such a task even without `schedule`
365
- * frontmatter so an in-flight migration is not blocked mid-cycle.
366
- */
367
- async function hasLegacyScheduleEvent(options, id) {
368
- const eventPath = join(eventsDir(options), taskScheduleEventFilename(options.channelId, id));
369
- if (!existsSync(eventPath))
370
- return false;
371
- try {
372
- const type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), taskScheduleEventFilename(options.channelId, id)).type;
373
- return isTaskScheduleEvent({ use: "schedule", event: { type } });
374
- }
375
- catch {
376
- return false;
377
- }
378
- }
379
- async function setTask(options, request) {
380
- if (!request.id)
381
- throw new Error('action "set" requires an id.');
382
- const id = normalizeTaskId(request.id);
383
- const taskPath = join(tasksDir(options), `${id}.md`);
384
- const { fields, body } = await readTaskDocument(taskPath, id, request.control !== undefined);
385
- if (request.control !== undefined && fields.control === undefined) {
386
- fields.control = createDefaultTaskControl("independent");
387
- }
388
- const nextFields = applySet(fields, request);
389
- await validateTaskRelations(options, id, nextFields);
390
- await writeFileAtomically(taskPath, renderTaskFile(nextFields, body));
391
- return {
392
- action: "set",
393
- id,
394
- path: taskPath,
395
- status: nextFields.status,
396
- notice: `已更新任务 \`${id}\`(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
397
- };
398
- }
399
- async function progressTask(options, request) {
400
- if (!request.id)
401
- throw new Error('action "progress" requires an id.');
402
- const id = normalizeTaskId(request.id);
403
- const note = requiredField(request.note, "note", "progress");
404
- const taskPath = join(tasksDir(options), `${id}.md`);
405
- const { fields, body } = await readTaskDocument(taskPath, id);
406
- if (["done", "cancelled", "escalated", "paused"].includes(fields.status)) {
407
- throw new Error(`Task "${id}" is ${fields.status} and cannot be progressed.`);
408
- }
409
- const nextFields = applySet(fields, request);
410
- await validateTaskRelations(options, id, nextFields);
411
- if (nextFields.control) {
412
- nextFields.control = invalidateTaskVerification(nextFields.control);
413
- nextFields.control = invalidateTaskApproval(nextFields.control);
414
- if (request.status === "blocked" || request.status === "awaiting-user") {
415
- nextFields.control.lastOutcome = "blocked";
416
- }
417
- else if (request.control?.lastOutcome === undefined) {
418
- nextFields.control.lastOutcome = "progress";
419
- if (request.control?.blockedReason === undefined)
420
- nextFields.control.blockedReason = undefined;
421
- }
422
- }
423
- const nextBody = appendCurrentCycleNote(body, note);
424
- await writeFileAtomically(taskPath, renderTaskFile(nextFields, nextBody));
425
- return {
426
- action: "progress",
427
- id,
428
- path: taskPath,
429
- status: nextFields.status,
430
- notice: `已记录任务 \`${id}\` 的进展(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
431
- };
432
- }
433
- /**
434
- * Move a task into the verification lane. The runtime driver will explicitly
435
- * wake a fresh verifier on the next attempt, keeping the maker from grading
436
- * its own work in the same reasoning context.
437
- */
438
- async function candidateTask(options, request) {
439
- if (!request.id)
440
- throw new Error('action "candidate" requires an id.');
441
- const id = normalizeTaskId(request.id);
442
- const note = requiredField(request.note, "note", "candidate");
443
- const taskPath = join(tasksDir(options), `${id}.md`);
444
- const { fields, body } = await readTaskDocument(taskPath, id);
445
- if (["done", "cancelled", "escalated", "paused"].includes(fields.status)) {
446
- throw new Error(`Task "${id}" is ${fields.status} and cannot enter verification.`);
447
- }
448
- const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
449
- if (uncheckedAcceptance.length > 0) {
450
- throw new Error(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before requesting verification.`);
451
- }
452
- const control = fields.control ?? createDefaultTaskControl("independent");
453
- control.verification = { mode: "independent", status: "pending" };
454
- control.lastOutcome = "progress";
455
- control.blockedReason = undefined;
456
- control.nextAction = "Run a purpose=verify sub-agent and import its attestation.";
457
- const nextBody = appendCurrentCycleNote(body, note);
458
- await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "verifying", wake: undefined, control }, nextBody));
459
- return {
460
- action: "candidate",
461
- id,
462
- path: taskPath,
463
- status: "verifying",
464
- notice: `任务 \`${id}\` 已进入独立验收队列;driver 将安排 verifier。`,
465
- };
466
- }
467
- async function verifyTask(options, request) {
468
- if (!request.id)
469
- throw new Error('action "verify" requires an id.');
470
- const id = normalizeTaskId(request.id);
471
- const runId = requiredField(request.verifierRunId, "verifierRunId", "verify");
472
- const task = await readStoredTask(options.channelDir, id);
473
- if (!task)
474
- throw new Error(`Task "${id}" does not exist; create it before verification.`);
475
- const attestation = await readVerificationAttestation(options.channelDir, runId);
476
- if (attestation.taskId !== id) {
477
- throw new Error(`Verification run "${runId}" belongs to task "${attestation.taskId}", not "${id}".`);
478
- }
479
- if (attestation.workspaceChanged) {
480
- throw new Error(`Verification run "${runId}" changed the workspace; rerun a read-only verifier.`);
481
- }
482
- if (attestation.bodyHash !== taskBodyHash(task.body)) {
483
- throw new Error(`Task "${id}" changed after verification run "${runId}"; rerun the verifier on current content.`);
484
- }
485
- if (attestation.subjectHash) {
486
- const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
487
- if (!currentSubject) {
488
- throw new Error(`Verification run "${runId}" is bound to a Git artifact subject, but the current checkout cannot be read. Rerun verification from the project checkout.`);
489
- }
490
- if (currentSubject !== attestation.subjectHash) {
491
- throw new Error(`Task "${id}" artifacts changed after verification run "${runId}"; rerun the verifier.`);
492
- }
493
- }
494
- const control = task.fields.control ?? createDefaultTaskControl("independent");
495
- control.verification = {
496
- mode: "independent",
497
- status: attestation.verdict === "pass" ? "passed" : "failed",
498
- runId,
499
- evidence: attestation.evidence,
500
- bodyHash: attestation.bodyHash,
501
- subjectHash: attestation.subjectHash,
502
- checkedAt: attestation.checkedAt,
503
- };
504
- control.lastOutcome = attestation.verdict === "pass" ? "verified" : "failed";
505
- control.blockedReason = attestation.verdict === "fail" ? attestation.evidence : undefined;
506
- task.fields.control = control;
507
- await writeFileAtomically(task.path, renderTaskFile(task.fields, task.body));
508
- return {
509
- action: "verify",
510
- id,
511
- path: task.path,
512
- status: task.fields.status,
513
- notice: `任务 \`${id}\` 独立验收结果:${attestation.verdict.toUpperCase()}(run: ${runId})。`,
514
- };
515
- }
516
- /**
517
- * `verify` writes control.verification from a real attestation file, but the task Markdown
518
- * itself is writable by the agent's own write/edit tools — nothing stops it from hand-crafting
519
- * a "passed" verification block that was never backed by a real verifier run. Re-check the
520
- * attestation file on the consuming side (done/doctor) too, not just at import time.
521
- */
522
- async function assertVerificationAttestationMatches(channelDir, id, verification) {
523
- if (!verification.runId) {
524
- throw new Error(`Task "${id}" has no verification run id; rerun task_manage verify before done.`);
525
- }
526
- const attestation = await readVerificationAttestation(channelDir, verification.runId);
527
- if (attestation.taskId !== id) {
528
- throw new Error(`Verification run "${verification.runId}" belongs to task "${attestation.taskId}", not "${id}"; rerun verification.`);
529
- }
530
- if (attestation.verdict !== "pass") {
531
- throw new Error(`Verification run "${verification.runId}" recorded a FAIL, not a PASS; rerun verification.`);
532
- }
533
- if (attestation.bodyHash !== verification.bodyHash) {
534
- throw new Error(`Task "${id}" control.verification.bodyHash does not match the attestation for run "${verification.runId}"; rerun task_manage verify.`);
535
- }
536
- }
537
- async function unfinishedChildren(options, parentId) {
538
- const entries = await readActiveTasks(tasksDir(options));
539
- return entries
540
- .filter((entry) => entry.frontmatter.control?.parent === parentId &&
541
- entry.frontmatter.status !== "done" &&
542
- entry.frontmatter.status !== "cancelled")
543
- .map((entry) => entry.id);
544
- }
545
- async function doneTask(options, request) {
546
- if (!request.id)
547
- throw new Error('action "done" requires an id.');
548
- const id = normalizeTaskId(request.id);
549
- const dir = tasksDir(options);
550
- const taskPath = join(dir, `${id}.md`);
551
- const { fields, body } = await readTaskDocument(taskPath, id);
552
- const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
553
- if (uncheckedAcceptance.length > 0) {
554
- throw new Error(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before done.`);
555
- }
556
- const dependencies = await dependencyState(options.channelDir, fields.control?.dependsOn ?? [], id);
557
- if (!dependencies.ready) {
558
- throw new Error(`Task "${id}" cannot be completed: ${dependencies.reason}. Complete its dependencies first.`);
559
- }
560
- const children = await unfinishedChildren(options, id);
561
- if (children.length > 0) {
562
- throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Finish or cancel them first.`);
563
- }
564
- if (fields.control?.sideEffects === "external") {
565
- if (fields.control.externalApproval === "required") {
566
- throw new Error(`Task "${id}" requires explicit external-action approval before it can be completed.`);
567
- }
568
- if (fields.control.externalApproval === "granted" && fields.control.approvalBodyHash !== taskBodyHash(body)) {
569
- throw new Error(`Task "${id}" changed after external-action approval; ask the user to run /tasks approve ${id} again.`);
570
- }
571
- }
572
- if (fields.control?.verification.mode === "independent") {
573
- const verification = fields.control.verification;
574
- if (verification.status !== "passed" || !verification.bodyHash || !verification.runId) {
575
- throw new Error(`Task "${id}" requires an independent PASS. Run a purpose=verify sub-agent, then task_manage verify with its run id.`);
576
- }
577
- if (verification.bodyHash !== taskBodyHash(body)) {
578
- throw new Error(`Task "${id}" changed after its independent PASS; rerun verification before done.`);
579
- }
580
- if (verification.subjectHash) {
581
- const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
582
- if (currentSubject !== verification.subjectHash) {
583
- throw new Error(`Task "${id}" artifacts changed after its independent PASS; rerun verification before done.`);
584
- }
585
- }
586
- await assertVerificationAttestationMatches(options.channelDir, id, verification);
587
- }
588
- const bodyWithEvidence = appendCompletionEvidence(body, request);
589
- if (fields.control) {
590
- fields.control.lastOutcome = "verified";
591
- fields.control.blockedReason = undefined;
592
- }
593
- // A recurring task (schedule frontmatter) sleeps in place until its next occurrence;
594
- // the wake is computed here so "done + wake" fully describes "asleep until next cycle".
595
- const doneFields = fields.schedule
596
- ? { ...fields, status: "done", wake: nextTaskWake(fields.schedule)?.toISOString() }
597
- : { ...fields, status: "done" };
598
- await writeFileAtomically(taskPath, renderTaskFile(doneFields, bodyWithEvidence));
599
- const { deleted, hasSchedule } = await cleanupTaskEvents(options, id);
600
- // Recurring (schedule frontmatter, or a legacy .schedule event during migration) →
601
- // sleeps in place; one-shot → archive.
602
- const recurring = Boolean(fields.schedule) || hasSchedule;
603
- let archived = false;
604
- let finalPath = taskPath;
605
- if (!recurring) {
606
- const archiveDir = join(dir, "archive");
607
- await mkdir(archiveDir, { recursive: true });
608
- finalPath = join(archiveDir, `${id}.md`);
609
- await rename(taskPath, finalPath);
610
- archived = true;
611
- }
612
- const cleanup = deleted.length > 0 ? `,清理事件 ${deleted.join(", ")}` : "";
613
- const disposition = archived ? "已归档" : "周期任务留原地待下次唤醒";
614
- return {
615
- action: "done",
616
- id,
617
- path: finalPath,
618
- status: "done",
619
- archived,
620
- deletedEvents: deleted,
621
- notice: `任务 \`${id}\` 已完成(${disposition}${cleanup})。`,
622
- };
623
- }
624
- async function cancelTask(options, request) {
625
- if (!request.id)
626
- throw new Error('action "cancel" requires an id.');
627
- const id = normalizeTaskId(request.id);
628
- const reason = requiredField(request.reason, "reason", "cancel");
629
- const dir = tasksDir(options);
630
- const taskPath = join(dir, `${id}.md`);
631
- const { fields, body } = await readTaskDocument(taskPath, id);
632
- const children = await unfinishedChildren(options, id);
633
- if (children.length > 0) {
634
- throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Cancel or re-parent them first.`);
635
- }
636
- if (fields.control) {
637
- fields.control.lastOutcome = "blocked";
638
- fields.control.blockedReason = `Cancelled: ${reason}`;
639
- }
640
- const cancelledBody = `${body.replace(/\n+$/, "\n")}\n## Cancellation\n\n- Reason: ${markdownValue(reason)}\n`;
641
- await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "cancelled", wake: undefined }, cancelledBody));
642
- const { deleted } = await cleanupTaskEvents(options, id, false);
643
- const archiveDir = join(dir, "archive");
644
- await mkdir(archiveDir, { recursive: true });
645
- const finalPath = join(archiveDir, `${id}.md`);
646
- await rename(taskPath, finalPath);
647
- return {
648
- action: "cancel",
649
- id,
650
- path: finalPath,
651
- status: "cancelled",
652
- archived: true,
653
- deletedEvents: deleted,
654
- notice: `任务 \`${id}\` 已取消并归档${deleted.length ? `,清理事件 ${deleted.join(", ")}` : ""}。`,
655
- };
656
- }
657
- async function startCycleTask(options, request) {
658
- if (!request.id)
659
- throw new Error('action "start-cycle" requires an id.');
660
- const id = normalizeTaskId(request.id);
661
- const cycleId = requiredField(request.cycleId, "cycleId", "start-cycle");
662
- const taskPath = join(tasksDir(options), `${id}.md`);
663
- const { fields, body } = await readTaskDocument(taskPath, id);
664
- if (fields.status !== "done") {
665
- throw new Error(`Task "${id}" is ${fields.status}, not done. Finish, cancel, or explicitly resolve the current cycle before starting another.`);
666
- }
667
- if (!fields.schedule && !(await hasLegacyScheduleEvent(options, id))) {
668
- throw new Error(`Task "${id}" is not recurring. Add a schedule cron with task_manage set before starting a cycle.`);
669
- }
670
- const control = fields.control ? resetTaskControlForCycle(fields.control, cycleId) : undefined;
671
- const nextBody = startTaskCycle(body, cycleId);
672
- await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "in-progress", wake: undefined, control }, nextBody));
673
- return {
674
- action: "start-cycle",
675
- id,
676
- path: taskPath,
677
- status: "in-progress",
678
- notice: `已开启周期任务 \`${id}\` 的新周期 \`${cycleId}\`。`,
679
- };
680
- }
681
- async function listTasks(options) {
682
- const entries = await readActiveTasks(tasksDir(options));
683
- return {
684
- action: "list",
685
- tasks: entries.map((entry) => ({
686
- id: entry.id,
687
- title: entry.title,
688
- status: entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "unreadable",
689
- wake: entry.frontmatter.wake,
690
- actionable: entry.actionable,
691
- control: entry.frontmatter.control,
692
- })),
693
- notice: `台账共有 ${entries.length} 个 active 任务。`,
694
- };
695
- }
696
11
  export async function manageTask(options, request) {
697
12
  switch (request.action) {
698
13
  case "create":
@@ -709,8 +24,6 @@ export async function manageTask(options, request) {
709
24
  return doneTask(options, request);
710
25
  case "cancel":
711
26
  return cancelTask(options, request);
712
- case "start-cycle":
713
- return startCycleTask(options, request);
714
27
  case "list":
715
28
  return listTasks(options);
716
29
  }
@@ -743,7 +56,6 @@ export function createTaskManageTool(options) {
743
56
  evidence: args.evidence,
744
57
  residualRisk: args.residualRisk,
745
58
  reason: args.reason,
746
- cycleId: args.cycleId,
747
59
  });
748
60
  return {
749
61
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],