@oyasmi/pipiclaw 0.7.7 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +9 -2
  2. package/dist/agent/channel-runner.d.ts +3 -0
  3. package/dist/agent/channel-runner.js +7 -1
  4. package/dist/agent/commands.js +7 -2
  5. package/dist/agent/prompt-builder.js +46 -0
  6. package/dist/agent/types.d.ts +2 -0
  7. package/dist/memory/task-digest.js +17 -0
  8. package/dist/runtime/bootstrap.d.ts +5 -0
  9. package/dist/runtime/bootstrap.js +57 -2
  10. package/dist/runtime/dingtalk.d.ts +2 -0
  11. package/dist/runtime/durable-dispatch.d.ts +28 -0
  12. package/dist/runtime/durable-dispatch.js +144 -0
  13. package/dist/runtime/events.d.ts +4 -2
  14. package/dist/runtime/events.js +12 -8
  15. package/dist/runtime/task-commands.d.ts +6 -0
  16. package/dist/runtime/task-commands.js +284 -3
  17. package/dist/runtime/task-driver.d.ts +32 -0
  18. package/dist/runtime/task-driver.js +270 -0
  19. package/dist/settings.d.ts +12 -0
  20. package/dist/settings.js +30 -0
  21. package/dist/shared/task-ledger.d.ts +27 -0
  22. package/dist/shared/task-ledger.js +209 -9
  23. package/dist/subagents/tool.d.ts +13 -0
  24. package/dist/subagents/tool.js +203 -11
  25. package/dist/tasks/artifact-subject.d.ts +6 -0
  26. package/dist/tasks/artifact-subject.js +29 -0
  27. package/dist/tasks/control.d.ts +83 -0
  28. package/dist/tasks/control.js +292 -0
  29. package/dist/tasks/store.d.ts +32 -0
  30. package/dist/tasks/store.js +142 -0
  31. package/dist/tasks/verification.d.ts +23 -0
  32. package/dist/tasks/verification.js +68 -0
  33. package/dist/tools/registry.d.ts +1 -1
  34. package/dist/tools/registry.js +6 -5
  35. package/dist/tools/task-manage.d.ts +37 -3
  36. package/dist/tools/task-manage.js +385 -28
  37. package/package.json +1 -1
@@ -1,21 +1,46 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
+ import { type TaskControl, type TaskControlPatch } from "../tasks/control.js";
3
4
  declare const taskManageSchema: Type.TObject<{
4
5
  label: Type.TString;
5
- action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"set">, Type.TLiteral<"done">, Type.TLiteral<"list">]>;
6
+ action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"progress">, Type.TLiteral<"set">, Type.TLiteral<"verify">, Type.TLiteral<"done">, Type.TLiteral<"cancel">, Type.TLiteral<"start-cycle">, Type.TLiteral<"candidate">, Type.TLiteral<"list">]>;
6
7
  id: Type.TOptional<Type.TString>;
7
8
  title: Type.TOptional<Type.TString>;
8
9
  goal: Type.TOptional<Type.TString>;
9
10
  dod: Type.TOptional<Type.TString>;
10
11
  manual: Type.TOptional<Type.TString>;
11
- status: Type.TOptional<Type.TUnion<Type.TLiteral<"open" | "blocked" | "in-progress" | "awaiting-user">[]>>;
12
+ verificationPlan: Type.TOptional<Type.TString>;
13
+ control: Type.TOptional<Type.TObject<{
14
+ priority: Type.TOptional<Type.TUnion<[Type.TLiteral<"low">, Type.TLiteral<"normal">, Type.TLiteral<"high">, Type.TLiteral<"critical">]>>;
15
+ deadline: Type.TOptional<Type.TString>;
16
+ nextAction: Type.TOptional<Type.TString>;
17
+ lastOutcome: Type.TOptional<Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"running">, Type.TLiteral<"progress">, Type.TLiteral<"blocked">, Type.TLiteral<"failed">, Type.TLiteral<"verified">]>>;
18
+ blockedReason: Type.TOptional<Type.TString>;
19
+ parent: Type.TOptional<Type.TString>;
20
+ dependsOn: Type.TOptional<Type.TArray<Type.TString>>;
21
+ isolation: Type.TOptional<Type.TUnion<[Type.TLiteral<"shared">, Type.TLiteral<"worktree">]>>;
22
+ sideEffects: Type.TOptional<Type.TUnion<[Type.TLiteral<"read-only">, Type.TLiteral<"workspace">, Type.TLiteral<"external">]>>;
23
+ externalApproval: Type.TOptional<Type.TUnion<[Type.TLiteral<"not-required">, Type.TLiteral<"required">]>>;
24
+ maxAttempts: Type.TOptional<Type.TInteger>;
25
+ maxTokens: Type.TOptional<Type.TNumber>;
26
+ maxCostUsd: Type.TOptional<Type.TNumber>;
27
+ maxWallTimeMinutes: Type.TOptional<Type.TNumber>;
28
+ verificationMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"evidence">, Type.TLiteral<"independent">]>>;
29
+ worktreePath: Type.TOptional<Type.TString>;
30
+ worktreeBranch: Type.TOptional<Type.TString>;
31
+ }>>;
32
+ status: Type.TOptional<Type.TUnion<Type.TLiteral<"blocked" | "paused" | "open" | "in-progress" | "awaiting-user">[]>>;
12
33
  wake: Type.TOptional<Type.TString>;
13
34
  recurrence: Type.TOptional<Type.TString>;
35
+ note: Type.TOptional<Type.TString>;
36
+ verifierRunId: Type.TOptional<Type.TString>;
14
37
  summary: Type.TOptional<Type.TString>;
15
38
  evidence: Type.TOptional<Type.TString>;
16
39
  residualRisk: Type.TOptional<Type.TString>;
40
+ reason: Type.TOptional<Type.TString>;
41
+ cycleId: Type.TOptional<Type.TString>;
17
42
  }>;
18
- export type TaskManageAction = "create" | "set" | "done" | "list";
43
+ export type TaskManageAction = "create" | "progress" | "candidate" | "set" | "verify" | "done" | "cancel" | "start-cycle" | "list";
19
44
  export interface TaskManageResult {
20
45
  action: TaskManageAction;
21
46
  id?: string;
@@ -29,6 +54,7 @@ export interface TaskManageResult {
29
54
  status: string;
30
55
  wake?: string;
31
56
  actionable: boolean;
57
+ control?: TaskControl;
32
58
  }>;
33
59
  notice: string;
34
60
  }
@@ -42,15 +68,23 @@ export interface TaskManageRequest {
42
68
  status?: string;
43
69
  wake?: string;
44
70
  recurrence?: string;
71
+ note?: string;
72
+ verificationPlan?: string;
73
+ control?: TaskControlPatch;
74
+ verifierRunId?: string;
45
75
  summary?: string;
46
76
  evidence?: string;
47
77
  residualRisk?: string;
78
+ reason?: string;
79
+ cycleId?: string;
48
80
  }
49
81
  export interface TaskManageToolOptions {
50
82
  workspaceDir: string;
51
83
  workspacePath: string;
52
84
  channelDir: string;
53
85
  channelId: string;
86
+ /** Project checkout whose artifact state an independent verifier binds to. */
87
+ workingDirectory?: string;
54
88
  }
55
89
  export declare function manageTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
56
90
  export declare function createTaskManageTool(options: TaskManageToolOptions): AgentTool<typeof taskManageSchema>;
@@ -5,34 +5,92 @@ import { Type } from "typebox";
5
5
  import { parseScheduledEventContent } from "../runtime/events.js";
6
6
  import { writeFileAtomically } from "../shared/atomic-file.js";
7
7
  import { isTaskScheduleEvent, taskEventPrefix, taskScheduleEventFilename } from "../shared/task-events.js";
8
- import { normalizeTaskId, parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, taskBody, } from "../shared/task-ledger.js";
9
- const SETTABLE_STATUSES = ["open", "in-progress", "awaiting-user", "blocked"];
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
+ });
10
42
  const taskManageSchema = Type.Object({
11
43
  label: Type.String({ description: "Brief description of the ledger change (shown to the user)" }),
12
- action: Type.Union([Type.Literal("create"), Type.Literal("set"), Type.Literal("done"), Type.Literal("list")], {
13
- description: '"create" writes a standard task skeleton; "set" updates status/wake/recurrence; "done" closes it out and requires summary/evidence; "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.',
14
56
  }),
15
- id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/set/done." })),
57
+ id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/progress/set/done." })),
16
58
  title: Type.Optional(Type.String({ description: "Required for create: task title used as the H1 heading." })),
17
59
  goal: Type.Optional(Type.String({ description: "Required for create: concise task goal." })),
18
60
  dod: Type.Optional(Type.String({ description: "Required for create: acceptance criteria / definition of done." })),
19
61
  manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
20
- status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/set. To close a task use action done, not status." })),
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." })),
21
65
  wake: Type.Optional(Type.String({
22
- 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.",
23
67
  })),
24
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." })),
25
73
  summary: Type.Optional(Type.String({ description: "Required for done: concise completion summary." })),
26
74
  evidence: Type.Optional(Type.String({
27
75
  description: "Required for done: verification evidence (tests, commands, review result, external confirmation, or a clear not-run reason).",
28
76
  })),
29
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." })),
30
80
  });
31
81
  function parseAction(action) {
32
- if (action === "create" || 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") {
33
91
  return action;
34
92
  }
35
- throw new Error('Unsupported task action. Use "create", "set", "done", or "list".');
93
+ throw new Error("Unsupported task action. Use create, progress, set, verify, done, cancel, start-cycle, or list.");
36
94
  }
37
95
  function toWorkspacePath(options, hostPath) {
38
96
  if (hostPath.startsWith(options.workspaceDir)) {
@@ -47,13 +105,7 @@ function eventsDir(options) {
47
105
  return join(options.workspaceDir, "events");
48
106
  }
49
107
  function renderTaskFile(fields, body) {
50
- const lines = ["---", `status: ${fields.status}`];
51
- if (fields.wake)
52
- lines.push(`wake: ${fields.wake}`);
53
- if (fields.recurrence)
54
- lines.push(`recurrence: ${fields.recurrence}`);
55
- lines.push("---");
56
- return `${lines.join("\n")}\n${body}`;
108
+ return renderTaskDocument(fields, body);
57
109
  }
58
110
  function requiredField(value, field, action) {
59
111
  const trimmed = value?.trim();
@@ -99,29 +151,42 @@ function renderTaskSkeleton(request) {
99
151
  const title = requiredField(request.title, "title", "create");
100
152
  const goal = requiredField(request.goal, "goal", "create");
101
153
  const dod = requiredField(request.dod, "dod", "create");
102
- const fields = applySet({ status: normalizeCreateStatus(request.status) }, request);
103
- const body = renderStandardTaskBody({ title, goal, dod, manual: request.manual });
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
+ });
104
165
  return { fields, body };
105
166
  }
106
167
  /**
107
- * 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.
108
169
  * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
109
170
  * rather than guessed at, so task_manage never silently mangles a body.
110
171
  */
111
- async function readTaskDocument(taskPath, id) {
172
+ async function readTaskDocument(taskPath, id, allowControlRepair = false) {
112
173
  if (!existsSync(taskPath)) {
113
- 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.`);
114
175
  }
115
176
  const content = await readFile(taskPath, "utf-8");
116
177
  const frontmatter = parseTaskFrontmatter(content);
117
178
  if (!frontmatter.readable) {
118
179
  throw new Error(`Task "${id}" has no readable frontmatter; fix it with edit before using task_manage.`);
119
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
+ }
120
184
  return {
121
185
  fields: {
122
186
  status: frontmatter.status ?? "open",
123
187
  wake: frontmatter.wake,
124
188
  recurrence: frontmatter.recurrence,
189
+ control: frontmatter.control,
125
190
  },
126
191
  body: taskBody(content),
127
192
  };
@@ -129,6 +194,9 @@ async function readTaskDocument(taskPath, id) {
129
194
  /** Apply a `set` request's optional fields onto the existing frontmatter. */
130
195
  function applySet(fields, request) {
131
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
+ }
132
200
  if (request.status !== undefined) {
133
201
  if (!SETTABLE_STATUSES.includes(request.status)) {
134
202
  throw new Error(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or action "done".`);
@@ -151,8 +219,56 @@ function applySet(fields, request) {
151
219
  const trimmed = request.recurrence.trim();
152
220
  next.recurrence = trimmed === "" ? undefined : trimmed;
153
221
  }
222
+ if (request.control !== undefined) {
223
+ next.control = applyTaskControlPatch(next.control ?? createDefaultTaskControl("evidence"), request.control);
224
+ }
154
225
  return next;
155
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
+ }
156
272
  async function createTask(options, request) {
157
273
  if (!request.id)
158
274
  throw new Error('action "create" requires an id.');
@@ -167,6 +283,7 @@ async function createTask(options, request) {
167
283
  throw new Error(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
168
284
  }
169
285
  const { fields, body } = renderTaskSkeleton(request);
286
+ await validateTaskRelations(options, id, fields);
170
287
  await mkdir(dir, { recursive: true });
171
288
  await writeFileAtomically(taskPath, renderTaskFile(fields, body));
172
289
  return {
@@ -185,7 +302,7 @@ async function createTask(options, request) {
185
302
  * Those are lifecycle check-ins, not proof that the task itself is recurring, so they
186
303
  * must not prevent a one-shot task from being archived.
187
304
  */
188
- async function cleanupTaskEvents(options, id) {
305
+ async function cleanupTaskEvents(options, id, preserveSchedule = true) {
189
306
  const dir = eventsDir(options);
190
307
  if (!existsSync(dir))
191
308
  return { deleted: [], hasSchedule: false };
@@ -204,7 +321,9 @@ async function cleanupTaskEvents(options, id) {
204
321
  catch {
205
322
  continue; // can't classify → leave it for /events to handle
206
323
  }
207
- if (filename === scheduleFilename && isTaskScheduleEvent({ use: "schedule", event: { type } })) {
324
+ if (preserveSchedule &&
325
+ filename === scheduleFilename &&
326
+ isTaskScheduleEvent({ use: "schedule", event: { type } })) {
208
327
  hasSchedule = true; // the cadence lives on for the next cycle
209
328
  continue;
210
329
  }
@@ -218,8 +337,12 @@ async function setTask(options, request) {
218
337
  throw new Error('action "set" requires an id.');
219
338
  const id = normalizeTaskId(request.id);
220
339
  const taskPath = join(tasksDir(options), `${id}.md`);
221
- 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
+ }
222
344
  const nextFields = applySet(fields, request);
345
+ await validateTaskRelations(options, id, nextFields);
223
346
  await writeFileAtomically(taskPath, renderTaskFile(nextFields, body));
224
347
  return {
225
348
  action: "set",
@@ -229,6 +352,128 @@ async function setTask(options, request) {
229
352
  notice: `已更新任务 \`${id}\`(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
230
353
  };
231
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
+ }
232
477
  async function doneTask(options, request) {
233
478
  if (!request.id)
234
479
  throw new Error('action "done" requires an id.');
@@ -236,7 +481,46 @@ async function doneTask(options, request) {
236
481
  const dir = tasksDir(options);
237
482
  const taskPath = join(dir, `${id}.md`);
238
483
  const { fields, body } = await readTaskDocument(taskPath, 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
+ }
239
519
  const bodyWithEvidence = appendCompletionEvidence(body, request);
520
+ if (fields.control) {
521
+ fields.control.lastOutcome = "verified";
522
+ fields.control.blockedReason = undefined;
523
+ }
240
524
  await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "done" }, bodyWithEvidence));
241
525
  const { deleted, hasSchedule } = await cleanupTaskEvents(options, id);
242
526
  // Periodic task → sleeps in place until its schedule fires next; one-shot → archive.
@@ -261,6 +545,63 @@ async function doneTask(options, request) {
261
545
  notice: `任务 \`${id}\` 已完成(${disposition}${cleanup})。`,
262
546
  };
263
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
+ }
264
605
  async function listTasks(options) {
265
606
  const entries = await readActiveTasks(tasksDir(options));
266
607
  return {
@@ -271,6 +612,7 @@ async function listTasks(options) {
271
612
  status: entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "unreadable",
272
613
  wake: entry.frontmatter.wake,
273
614
  actionable: entry.actionable,
615
+ control: entry.frontmatter.control,
274
616
  })),
275
617
  notice: `台账共有 ${entries.length} 个 active 任务。`,
276
618
  };
@@ -279,10 +621,20 @@ export async function manageTask(options, request) {
279
621
  switch (request.action) {
280
622
  case "create":
281
623
  return createTask(options, request);
624
+ case "progress":
625
+ return progressTask(options, request);
626
+ case "candidate":
627
+ return candidateTask(options, request);
282
628
  case "set":
283
629
  return setTask(options, request);
630
+ case "verify":
631
+ return verifyTask(options, request);
284
632
  case "done":
285
633
  return doneTask(options, request);
634
+ case "cancel":
635
+ return cancelTask(options, request);
636
+ case "start-cycle":
637
+ return startCycleTask(options, request);
286
638
  case "list":
287
639
  return listTasks(options);
288
640
  }
@@ -291,10 +643,9 @@ export function createTaskManageTool(options) {
291
643
  return {
292
644
  name: "task_manage",
293
645
  label: "task_manage",
294
- description: "Manage this channel's task ledger frontmatter and lifecycle: set status/wake/recurrence, close a task out " +
295
- "(requiring summary/evidence, archiving one-shot tasks, and cleaning up residual events), or list active " +
296
- "tasks. Write the task body (goal, DoD, manual, cycle log) with write/edit; this tool owns only the " +
297
- "frontmatter and close-out evidence.",
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.",
298
649
  parameters: taskManageSchema,
299
650
  execute: async (_toolCallId, args) => {
300
651
  const result = await manageTask(options, {
@@ -304,12 +655,18 @@ export function createTaskManageTool(options) {
304
655
  goal: args.goal,
305
656
  dod: args.dod,
306
657
  manual: args.manual,
658
+ verificationPlan: args.verificationPlan,
659
+ control: args.control,
307
660
  status: args.status,
308
661
  wake: args.wake,
309
662
  recurrence: args.recurrence,
663
+ note: args.note,
664
+ verifierRunId: args.verifierRunId,
310
665
  summary: args.summary,
311
666
  evidence: args.evidence,
312
667
  residualRisk: args.residualRisk,
668
+ reason: args.reason,
669
+ cycleId: args.cycleId,
313
670
  });
314
671
  return {
315
672
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],