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