@oyasmi/pipiclaw 0.8.8 → 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 (38) hide show
  1. package/dist/memory/task-digest.js +1 -1
  2. package/dist/playbooks/task-closeout.md +11 -10
  3. package/dist/playbooks/task-delegation.md +1 -1
  4. package/dist/playbooks/task-driving.md +6 -7
  5. package/dist/playbooks/task-planning.md +7 -5
  6. package/dist/playbooks/task-recurring.md +7 -4
  7. package/dist/playbooks/task-repair.md +7 -7
  8. package/dist/runtime/bootstrap.js +5 -1
  9. package/dist/runtime/task-commands.js +29 -51
  10. package/dist/runtime/task-driver.d.ts +0 -8
  11. package/dist/runtime/task-driver.js +83 -82
  12. package/dist/runtime/task-migration.d.ts +11 -0
  13. package/dist/runtime/task-migration.js +70 -0
  14. package/dist/shared/task-events.d.ts +0 -26
  15. package/dist/shared/task-events.js +0 -15
  16. package/dist/shared/task-ledger.d.ts +23 -1
  17. package/dist/shared/task-ledger.js +65 -16
  18. package/dist/tasks/control.d.ts +4 -0
  19. package/dist/tasks/control.js +3 -0
  20. package/dist/tasks/store.d.ts +28 -1
  21. package/dist/tasks/store.js +63 -6
  22. package/dist/tasks/transitions.d.ts +40 -0
  23. package/dist/tasks/transitions.js +81 -0
  24. package/dist/tools/task-manage/create.d.ts +2 -0
  25. package/dist/tools/task-manage/create.js +34 -0
  26. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  27. package/dist/tools/task-manage/lifecycle.js +196 -0
  28. package/dist/tools/task-manage/schema.d.ts +43 -0
  29. package/dist/tools/task-manage/schema.js +89 -0
  30. package/dist/tools/task-manage/shared.d.ts +36 -0
  31. package/dist/tools/task-manage/shared.js +246 -0
  32. package/dist/tools/task-manage/types.d.ts +53 -0
  33. package/dist/tools/task-manage/types.js +1 -0
  34. package/dist/tools/task-manage/verification.d.ts +16 -0
  35. package/dist/tools/task-manage/verification.js +111 -0
  36. package/dist/tools/task-manage.d.ts +9 -89
  37. package/dist/tools/task-manage.js +8 -696
  38. package/package.json +1 -1
@@ -3,9 +3,17 @@ import { existsSync } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
- import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, taskBody, } from "../shared/task-ledger.js";
6
+ import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, startTaskCycle, taskBody, taskContractSegment, } from "../shared/task-ledger.js";
7
+ import { resetTaskControlForCycle } from "./control.js";
8
+ /**
9
+ * Hash the task's *contract* segment (Goal/DoD/Manual/Verification), not the whole body, so
10
+ * verification PASS and external approval survive routine Current Cycle / History logging and
11
+ * only break when the contract itself changes (spec 029, D4). Old attestations that hashed the
12
+ * whole body naturally fail this check after upgrade and are re-verified — verification should
13
+ * always reflect current content, so there is no compatibility burden.
14
+ */
7
15
  export function taskBodyHash(body) {
8
- return createHash("sha256").update(body).digest("hex");
16
+ return createHash("sha256").update(taskContractSegment(body)).digest("hex");
9
17
  }
10
18
  export async function readStoredTask(channelDir, idInput, includeArchive = false, allowInvalidControl = false) {
11
19
  const id = normalizeTaskId(idInput);
@@ -29,7 +37,7 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
29
37
  id,
30
38
  path,
31
39
  fields: {
32
- status: frontmatter.status ?? "open",
40
+ status: frontmatter.status ?? "active",
33
41
  wake: frontmatter.wake,
34
42
  schedule: frontmatter.schedule,
35
43
  recurrence: frontmatter.recurrence,
@@ -108,17 +116,59 @@ export async function finishTaskAttempt(channelDir, id, result) {
108
116
  }
109
117
  }, true);
110
118
  }
119
+ /**
120
+ * A governor stop: the deterministic task governor pauses the task (spec 029, D3 — this is
121
+ * the former `escalated` status, now `paused` + `pausedBy: "governor"`), records the reason,
122
+ * and clears the wake so no automatic dispatch resumes it until a human intervenes.
123
+ */
111
124
  export async function escalateTask(channelDir, id, reason) {
112
125
  const document = await updateStoredTask(channelDir, id, (task) => {
113
- task.fields.status = "escalated";
126
+ task.fields.status = "paused";
114
127
  task.fields.wake = undefined;
115
128
  if (task.fields.control) {
129
+ task.fields.control.pausedBy = "governor";
116
130
  task.fields.control.lastOutcome = "blocked";
117
131
  task.fields.control.blockedReason = reason;
118
132
  }
119
133
  });
120
134
  return document !== undefined;
121
135
  }
136
+ /**
137
+ * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
138
+ * with a `-N` suffix when the same task is reopened more than once on the same local day.
139
+ */
140
+ export function nextCycleId(previousCycleId, now) {
141
+ const y = now.getFullYear();
142
+ const m = String(now.getMonth() + 1).padStart(2, "0");
143
+ const d = String(now.getDate()).padStart(2, "0");
144
+ const base = `cycle-${y}-${m}-${d}`;
145
+ if (!previousCycleId || (previousCycleId !== base && !previousCycleId.startsWith(`${base}-`)))
146
+ return base;
147
+ const suffix = previousCycleId.slice(base.length + 1);
148
+ const previousCount = suffix ? Number.parseInt(suffix, 10) : 1;
149
+ const nextCount = Number.isFinite(previousCount) && previousCount >= 1 ? previousCount + 1 : 2;
150
+ return `${base}-${nextCount}`;
151
+ }
152
+ /**
153
+ * Open the next cycle of a done recurring task entirely in the runtime (spec 029, D2):
154
+ * fold the previous cycle's log into History, reset per-cycle control, clear the wake, and
155
+ * mark it `active`. This is the deterministic replacement for the retired
156
+ * `task_manage start-cycle` action — no LLM turn is spent just to reopen a cycle.
157
+ */
158
+ export async function openRecurringTaskCycle(channelDir, id, now) {
159
+ let cycleId;
160
+ const document = await updateStoredTask(channelDir, id, (task) => {
161
+ cycleId = nextCycleId(task.fields.control?.cycleId, now);
162
+ task.body = startTaskCycle(task.body, cycleId);
163
+ task.fields.status = "active";
164
+ task.fields.wake = undefined;
165
+ if (task.fields.control)
166
+ task.fields.control = resetTaskControlForCycle(task.fields.control, cycleId);
167
+ });
168
+ if (!document || !cycleId)
169
+ return undefined;
170
+ return { document, cycleId };
171
+ }
122
172
  export async function dependencyState(channelDir, dependencyIds, ownerId) {
123
173
  const detectCycle = async (id, path, active) => {
124
174
  if (id === ownerId || active.has(id))
@@ -143,8 +193,15 @@ export async function dependencyState(channelDir, dependencyIds, ownerId) {
143
193
  const dependency = await readStoredTask(channelDir, dependencyId, true, true);
144
194
  if (!dependency)
145
195
  return { ready: false, reason: `dependency ${dependencyId} is missing` };
146
- if (dependency.fields.status === "cancelled" || dependency.fields.status === "escalated") {
147
- return { ready: false, reason: `dependency ${dependencyId} is ${dependency.fields.status}` };
196
+ if (dependency.fields.status === "cancelled") {
197
+ return { ready: false, reason: `dependency ${dependencyId} is cancelled` };
198
+ }
199
+ // A governor-paused dependency will not self-recover, so it blocks the dependent
200
+ // terminally (matches the retired `escalated` semantics); a user pause is a soft wait.
201
+ if (dependency.fields.status === "paused") {
202
+ return dependency.fields.control?.pausedBy === "governor"
203
+ ? { ready: false, reason: `dependency ${dependencyId} is paused by the governor` }
204
+ : { ready: false, reason: `waiting for dependency ${dependencyId} (paused)` };
148
205
  }
149
206
  if (dependency.fields.status !== "done")
150
207
  return { ready: false, reason: `waiting for dependency ${dependencyId}` };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The task status model and its single transition table (spec 029, D3).
3
+ *
4
+ * There are six canonical statuses. Every status maps to exactly one driver behaviour;
5
+ * statuses that used to differ only for human readers were merged (their nuance now lives
6
+ * in free-text `control.blockedReason`). A single `action × fromStatus → toStatus` table
7
+ * replaces the per-action status guards that used to be scattered across `task_manage` and
8
+ * the `/tasks` command handlers, so an illegal transition always fails the same way.
9
+ *
10
+ * active → dispatchable now (wake-gated: not yet due ⇒ sleep until wake)
11
+ * waiting → sleep until wake, then dispatch
12
+ * verifying → dispatch a checker-only turn
13
+ * paused → never dispatched (excluded at the driver scan layer, zero token)
14
+ * done → recurring: reopen next cycle at wake; otherwise archived
15
+ * cancelled → archived, never
16
+ */
17
+ export declare const TASK_STATUSES: readonly ["active", "waiting", "verifying", "done", "cancelled", "paused"];
18
+ export type TaskStatus = (typeof TASK_STATUSES)[number];
19
+ /** Statuses a user/agent may set directly via create/progress/set. */
20
+ export declare const SETTABLE_TASK_STATUSES: readonly ["active", "waiting", "paused"];
21
+ export type SettableTaskStatus = (typeof SETTABLE_TASK_STATUSES)[number];
22
+ /** Statuses the driver never dispatches. */
23
+ export declare const TERMINAL_TASK_STATUSES: Set<string>;
24
+ export type TaskLifecycleAction = "create" | "progress" | "candidate" | "verify" | "done" | "cancel" | "set" | "pause" | "resume" | "run";
25
+ /**
26
+ * Map a stored (possibly legacy) status string to a canonical status.
27
+ * Legacy files are read losslessly and written back canonical on the next write;
28
+ * there is no disk migration. `escalated` maps to `paused` — the caller is expected to
29
+ * stamp `control.pausedBy = "governor"` to preserve the "stopped by the governor" nuance.
30
+ */
31
+ export declare function normalizeStoredStatus(raw: string | undefined): TaskStatus;
32
+ /** True when the stored status was the legacy `escalated` (⇒ paused by the governor). */
33
+ export declare function wasLegacyEscalated(raw: string | undefined): boolean;
34
+ export declare function isSettableTaskStatus(value: string): value is SettableTaskStatus;
35
+ /**
36
+ * Assert an action is legal from the current status, throwing a uniform error otherwise.
37
+ * Returns the resolved target status: a fixed status, or — for `to: "caller"` actions —
38
+ * `requestedStatus` when supplied (validated as settable) else the unchanged `from`.
39
+ */
40
+ export declare function resolveTaskTransition(action: TaskLifecycleAction, id: string, from: TaskStatus, requestedStatus?: string): TaskStatus;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The task status model and its single transition table (spec 029, D3).
3
+ *
4
+ * There are six canonical statuses. Every status maps to exactly one driver behaviour;
5
+ * statuses that used to differ only for human readers were merged (their nuance now lives
6
+ * in free-text `control.blockedReason`). A single `action × fromStatus → toStatus` table
7
+ * replaces the per-action status guards that used to be scattered across `task_manage` and
8
+ * the `/tasks` command handlers, so an illegal transition always fails the same way.
9
+ *
10
+ * active → dispatchable now (wake-gated: not yet due ⇒ sleep until wake)
11
+ * waiting → sleep until wake, then dispatch
12
+ * verifying → dispatch a checker-only turn
13
+ * paused → never dispatched (excluded at the driver scan layer, zero token)
14
+ * done → recurring: reopen next cycle at wake; otherwise archived
15
+ * cancelled → archived, never
16
+ */
17
+ export const TASK_STATUSES = ["active", "waiting", "verifying", "done", "cancelled", "paused"];
18
+ /** Statuses a user/agent may set directly via create/progress/set. */
19
+ export const SETTABLE_TASK_STATUSES = ["active", "waiting", "paused"];
20
+ /** Statuses the driver never dispatches. */
21
+ export const TERMINAL_TASK_STATUSES = new Set(["done", "cancelled", "paused"]);
22
+ const TRANSITIONS = {
23
+ create: { from: [], to: "active" },
24
+ progress: { from: ["active", "waiting", "verifying"], to: "caller" },
25
+ candidate: { from: ["active", "waiting"], to: "verifying" },
26
+ verify: { from: ["verifying"], to: "verifying" },
27
+ done: { from: ["active", "waiting", "verifying"], to: "done" },
28
+ cancel: { from: ["active", "waiting", "verifying", "paused"], to: "cancelled" },
29
+ set: { from: ["active", "waiting", "verifying", "paused", "done"], to: "caller" },
30
+ pause: { from: ["active", "waiting", "verifying"], to: "paused" },
31
+ resume: { from: ["paused"], to: "active" },
32
+ run: { from: ["paused", "active", "waiting"], to: "active" },
33
+ };
34
+ /**
35
+ * Map a stored (possibly legacy) status string to a canonical status.
36
+ * Legacy files are read losslessly and written back canonical on the next write;
37
+ * there is no disk migration. `escalated` maps to `paused` — the caller is expected to
38
+ * stamp `control.pausedBy = "governor"` to preserve the "stopped by the governor" nuance.
39
+ */
40
+ export function normalizeStoredStatus(raw) {
41
+ switch (raw) {
42
+ case undefined:
43
+ case "":
44
+ case "open":
45
+ case "in-progress":
46
+ return "active";
47
+ case "awaiting-user":
48
+ case "blocked":
49
+ return "waiting";
50
+ case "escalated":
51
+ return "paused";
52
+ default:
53
+ return TASK_STATUSES.includes(raw) ? raw : "active";
54
+ }
55
+ }
56
+ /** True when the stored status was the legacy `escalated` (⇒ paused by the governor). */
57
+ export function wasLegacyEscalated(raw) {
58
+ return raw === "escalated";
59
+ }
60
+ export function isSettableTaskStatus(value) {
61
+ return SETTABLE_TASK_STATUSES.includes(value);
62
+ }
63
+ /**
64
+ * Assert an action is legal from the current status, throwing a uniform error otherwise.
65
+ * Returns the resolved target status: a fixed status, or — for `to: "caller"` actions —
66
+ * `requestedStatus` when supplied (validated as settable) else the unchanged `from`.
67
+ */
68
+ export function resolveTaskTransition(action, id, from, requestedStatus) {
69
+ const rule = TRANSITIONS[action];
70
+ if (!rule.from.includes(from)) {
71
+ throw new Error(`Task ${id} is ${from}; action ${action} allows only from: ${rule.from.join(", ") || "(none)"}.`);
72
+ }
73
+ if (rule.to !== "caller")
74
+ return rule.to;
75
+ if (requestedStatus === undefined)
76
+ return from;
77
+ if (!isSettableTaskStatus(requestedStatus)) {
78
+ throw new Error(`Invalid status "${requestedStatus}". Use one of ${SETTABLE_TASK_STATUSES.join(", ")}.`);
79
+ }
80
+ return requestedStatus;
81
+ }
@@ -0,0 +1,2 @@
1
+ import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./types.js";
2
+ export declare function createTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
@@ -0,0 +1,34 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeFileAtomically } from "../../shared/atomic-file.js";
5
+ import { normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../shared/task-ledger.js";
6
+ import { renderTaskFile, renderTaskSkeleton, tasksDir, validateTaskRelations } from "./shared.js";
7
+ export async function createTask(options, request) {
8
+ if (!request.id)
9
+ throw new Error('action "create" requires an id.');
10
+ const id = normalizeTaskId(request.id);
11
+ const dir = tasksDir(options);
12
+ const taskPath = join(dir, `${id}.md`);
13
+ const archivePath = join(dir, "archive", `${id}.md`);
14
+ if (existsSync(taskPath)) {
15
+ throw new Error(`Task "${id}" already exists; use action "set" or edit the body instead.`);
16
+ }
17
+ if (existsSync(archivePath)) {
18
+ throw new Error(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
19
+ }
20
+ const { fields, body } = renderTaskSkeleton(request);
21
+ const badDod = uncheckedTaskAcceptanceItems(body).find((item) => item.startsWith("DoD has no checklist items"));
22
+ if (badDod)
23
+ throw new Error(badDod);
24
+ await validateTaskRelations(options, id, fields);
25
+ await mkdir(dir, { recursive: true });
26
+ await writeFileAtomically(taskPath, renderTaskFile(fields, body));
27
+ return {
28
+ action: "create",
29
+ id,
30
+ path: taskPath,
31
+ status: fields.status,
32
+ notice: `已创建任务 \`${id}\`(status: ${fields.status}${fields.wake ? `, 首次唤醒: ${fields.wake}` : ""})。`,
33
+ };
34
+ }
@@ -0,0 +1,6 @@
1
+ import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./types.js";
2
+ export declare function setTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
3
+ export declare function progressTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
4
+ export declare function doneTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
5
+ export declare function cancelTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
6
+ export declare function listTasks(options: TaskManageToolOptions): Promise<TaskManageResult>;
@@ -0,0 +1,196 @@
1
+ import { mkdir, rename } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { writeFileAtomically } from "../../shared/atomic-file.js";
4
+ import { appendCurrentCycleNote, normalizeTaskId, readActiveTasks, uncheckedTaskAcceptanceItems, } from "../../shared/task-ledger.js";
5
+ import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
6
+ import { invalidateTaskVerification } from "../../tasks/control.js";
7
+ import { dependencyState, taskBodyHash } from "../../tasks/store.js";
8
+ import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
9
+ import { appendCompletionEvidence, applySet, cleanupTaskEvents, markdownValue, readTaskDocument, renderTaskFile, requiredField, tasksDir, unfinishedChildren, validateTaskRelations, } from "./shared.js";
10
+ import { assertVerificationAttestationMatches } from "./verification.js";
11
+ export async function setTask(options, request) {
12
+ if (!request.id)
13
+ throw new Error('action "set" requires an id.');
14
+ const id = normalizeTaskId(request.id);
15
+ const taskPath = join(tasksDir(options), `${id}.md`);
16
+ const { fields, body } = await readTaskDocument(taskPath, id, request.control !== undefined);
17
+ const fromStatus = normalizeStoredStatus(fields.status);
18
+ resolveTaskTransition("set", id, fromStatus, request.status);
19
+ const nextFields = applySet(fields, request);
20
+ // Leaving the verification lane by hand invalidates any recorded verdict — a passed/failed
21
+ // attestation only describes the task while it stayed in `verifying` (D3).
22
+ if (fromStatus === "verifying" && nextFields.status !== "verifying" && nextFields.control) {
23
+ nextFields.control = invalidateTaskVerification(nextFields.control);
24
+ }
25
+ await validateTaskRelations(options, id, nextFields);
26
+ await writeFileAtomically(taskPath, renderTaskFile(nextFields, body));
27
+ return {
28
+ action: "set",
29
+ id,
30
+ path: taskPath,
31
+ status: nextFields.status,
32
+ notice: `已更新任务 \`${id}\`(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
33
+ };
34
+ }
35
+ export async function progressTask(options, request) {
36
+ if (!request.id)
37
+ throw new Error('action "progress" requires an id.');
38
+ const id = normalizeTaskId(request.id);
39
+ const note = requiredField(request.note, "note", "progress");
40
+ const taskPath = join(tasksDir(options), `${id}.md`);
41
+ const { fields, body } = await readTaskDocument(taskPath, id);
42
+ resolveTaskTransition("progress", id, normalizeStoredStatus(fields.status), request.status);
43
+ const nextFields = applySet(fields, request);
44
+ await validateTaskRelations(options, id, nextFields);
45
+ // D4: a progress note only appends to Current Cycle — it never touches the contract segment
46
+ // that PASS/approval bind to, so it no longer invalidates verification or approval. A real
47
+ // contract change (Goal/DoD/Manual/Verification) goes through write/edit and is caught by the
48
+ // contract-hash checks in verify/done/approve.
49
+ if (nextFields.control) {
50
+ if (request.status === "waiting") {
51
+ nextFields.control.lastOutcome = "blocked";
52
+ }
53
+ else if (request.control?.lastOutcome === undefined) {
54
+ nextFields.control.lastOutcome = "progress";
55
+ if (request.control?.blockedReason === undefined)
56
+ nextFields.control.blockedReason = undefined;
57
+ }
58
+ }
59
+ const nextBody = appendCurrentCycleNote(body, note);
60
+ await writeFileAtomically(taskPath, renderTaskFile(nextFields, nextBody));
61
+ return {
62
+ action: "progress",
63
+ id,
64
+ path: taskPath,
65
+ status: nextFields.status,
66
+ notice: `已记录任务 \`${id}\` 的进展(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
67
+ };
68
+ }
69
+ export async function doneTask(options, request) {
70
+ if (!request.id)
71
+ throw new Error('action "done" requires an id.');
72
+ const id = normalizeTaskId(request.id);
73
+ const dir = tasksDir(options);
74
+ const taskPath = join(dir, `${id}.md`);
75
+ const { fields, body } = await readTaskDocument(taskPath, id);
76
+ resolveTaskTransition("done", id, normalizeStoredStatus(fields.status));
77
+ const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
78
+ if (uncheckedAcceptance.length > 0) {
79
+ throw new Error(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before done.`);
80
+ }
81
+ const dependencies = await dependencyState(options.channelDir, fields.control?.dependsOn ?? [], id);
82
+ if (!dependencies.ready) {
83
+ throw new Error(`Task "${id}" cannot be completed: ${dependencies.reason}. Complete its dependencies first.`);
84
+ }
85
+ const children = await unfinishedChildren(options, id);
86
+ if (children.length > 0) {
87
+ throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Finish or cancel them first.`);
88
+ }
89
+ if (fields.control?.sideEffects === "external") {
90
+ if (fields.control.externalApproval === "required") {
91
+ throw new Error(`Task "${id}" requires explicit external-action approval before it can be completed.`);
92
+ }
93
+ if (fields.control.externalApproval === "granted" && fields.control.approvalBodyHash !== taskBodyHash(body)) {
94
+ throw new Error(`Task "${id}" changed after external-action approval; ask the user to run /tasks approve ${id} again.`);
95
+ }
96
+ }
97
+ if (fields.control?.verification.mode === "independent") {
98
+ const verification = fields.control.verification;
99
+ if (verification.status !== "passed" || !verification.bodyHash || !verification.runId) {
100
+ throw new Error(`Task "${id}" requires an independent PASS. Run a purpose=verify sub-agent, then task_manage verify with its run id.`);
101
+ }
102
+ if (verification.bodyHash !== taskBodyHash(body)) {
103
+ throw new Error(`Task "${id}" changed after its independent PASS; rerun verification before done.`);
104
+ }
105
+ if (verification.subjectHash) {
106
+ const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
107
+ if (currentSubject !== verification.subjectHash) {
108
+ throw new Error(`Task "${id}" artifacts changed after its independent PASS; rerun verification before done.`);
109
+ }
110
+ }
111
+ await assertVerificationAttestationMatches(options.channelDir, id, verification);
112
+ }
113
+ const bodyWithEvidence = appendCompletionEvidence(body, request);
114
+ if (fields.control) {
115
+ fields.control.lastOutcome = "verified";
116
+ fields.control.blockedReason = undefined;
117
+ }
118
+ // A recurring task (schedule frontmatter) sleeps in place until its next occurrence. The
119
+ // wake is cleared here and refilled to the next cron occurrence by the single time rule
120
+ // (`normalizeTaskFields`) on the write path, so "done + wake" always describes "asleep
121
+ // until next cycle" without a per-action recompute (D1).
122
+ const doneFields = { ...fields, status: "done", wake: undefined };
123
+ await writeFileAtomically(taskPath, renderTaskFile(doneFields, bodyWithEvidence));
124
+ const { deleted } = await cleanupTaskEvents(options, id);
125
+ // Recurring (schedule frontmatter) sleeps in place; one-shot → archive.
126
+ const recurring = Boolean(fields.schedule);
127
+ let archived = false;
128
+ let finalPath = taskPath;
129
+ if (!recurring) {
130
+ const archiveDir = join(dir, "archive");
131
+ await mkdir(archiveDir, { recursive: true });
132
+ finalPath = join(archiveDir, `${id}.md`);
133
+ await rename(taskPath, finalPath);
134
+ archived = true;
135
+ }
136
+ const cleanup = deleted.length > 0 ? `,清理事件 ${deleted.join(", ")}` : "";
137
+ const disposition = archived ? "已归档" : "周期任务留原地待下次唤醒";
138
+ return {
139
+ action: "done",
140
+ id,
141
+ path: finalPath,
142
+ status: "done",
143
+ archived,
144
+ deletedEvents: deleted,
145
+ notice: `任务 \`${id}\` 已完成(${disposition}${cleanup})。`,
146
+ };
147
+ }
148
+ export async function cancelTask(options, request) {
149
+ if (!request.id)
150
+ throw new Error('action "cancel" requires an id.');
151
+ const id = normalizeTaskId(request.id);
152
+ const reason = requiredField(request.reason, "reason", "cancel");
153
+ const dir = tasksDir(options);
154
+ const taskPath = join(dir, `${id}.md`);
155
+ const { fields, body } = await readTaskDocument(taskPath, id);
156
+ resolveTaskTransition("cancel", id, normalizeStoredStatus(fields.status));
157
+ const children = await unfinishedChildren(options, id);
158
+ if (children.length > 0) {
159
+ throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Cancel or re-parent them first.`);
160
+ }
161
+ if (fields.control) {
162
+ fields.control.lastOutcome = "blocked";
163
+ fields.control.blockedReason = `Cancelled: ${reason}`;
164
+ }
165
+ const cancelledBody = `${body.replace(/\n+$/, "\n")}\n## Cancellation\n\n- Reason: ${markdownValue(reason)}\n`;
166
+ await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "cancelled", wake: undefined }, cancelledBody));
167
+ const { deleted } = await cleanupTaskEvents(options, id);
168
+ const archiveDir = join(dir, "archive");
169
+ await mkdir(archiveDir, { recursive: true });
170
+ const finalPath = join(archiveDir, `${id}.md`);
171
+ await rename(taskPath, finalPath);
172
+ return {
173
+ action: "cancel",
174
+ id,
175
+ path: finalPath,
176
+ status: "cancelled",
177
+ archived: true,
178
+ deletedEvents: deleted,
179
+ notice: `任务 \`${id}\` 已取消并归档${deleted.length ? `,清理事件 ${deleted.join(", ")}` : ""}。`,
180
+ };
181
+ }
182
+ export async function listTasks(options) {
183
+ const entries = await readActiveTasks(tasksDir(options));
184
+ return {
185
+ action: "list",
186
+ tasks: entries.map((entry) => ({
187
+ id: entry.id,
188
+ title: entry.title,
189
+ status: entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "unreadable",
190
+ wake: entry.frontmatter.wake,
191
+ actionable: entry.actionable,
192
+ control: entry.frontmatter.control,
193
+ })),
194
+ notice: `台账共有 ${entries.length} 个 active 任务。`,
195
+ };
196
+ }
@@ -0,0 +1,43 @@
1
+ import { Type } from "typebox";
2
+ import type { TaskManageAction } from "./types.js";
3
+ export declare const SETTABLE_STATUSES: readonly ["active", "waiting", "paused"];
4
+ export declare const taskManageSchema: Type.TObject<{
5
+ label: Type.TString;
6
+ action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"progress">, Type.TLiteral<"set">, Type.TLiteral<"verify">, Type.TLiteral<"done">, Type.TLiteral<"cancel">, Type.TLiteral<"candidate">, Type.TLiteral<"list">]>;
7
+ id: Type.TOptional<Type.TString>;
8
+ title: Type.TOptional<Type.TString>;
9
+ goal: Type.TOptional<Type.TString>;
10
+ dod: Type.TOptional<Type.TString>;
11
+ manual: Type.TOptional<Type.TString>;
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<"active" | "waiting" | "paused">[]>>;
33
+ wake: Type.TOptional<Type.TString>;
34
+ schedule: Type.TOptional<Type.TString>;
35
+ recurrence: Type.TOptional<Type.TString>;
36
+ note: Type.TOptional<Type.TString>;
37
+ verifierRunId: Type.TOptional<Type.TString>;
38
+ summary: Type.TOptional<Type.TString>;
39
+ evidence: Type.TOptional<Type.TString>;
40
+ residualRisk: Type.TOptional<Type.TString>;
41
+ reason: Type.TOptional<Type.TString>;
42
+ }>;
43
+ export declare function parseAction(action: string): TaskManageAction;
@@ -0,0 +1,89 @@
1
+ import { Type } from "typebox";
2
+ import { SETTABLE_TASK_STATUSES } from "../../tasks/transitions.js";
3
+ export const SETTABLE_STATUSES = SETTABLE_TASK_STATUSES;
4
+ const taskControlSchema = Type.Object({
5
+ priority: Type.Optional(Type.Union([Type.Literal("low"), Type.Literal("normal"), Type.Literal("high"), Type.Literal("critical")])),
6
+ deadline: Type.Optional(Type.String({ description: "ISO8601 deadline; empty string clears it." })),
7
+ nextAction: Type.Optional(Type.String({ description: "Concrete next executable step; empty string clears it." })),
8
+ lastOutcome: Type.Optional(Type.Union([
9
+ Type.Literal("pending"),
10
+ Type.Literal("running"),
11
+ Type.Literal("progress"),
12
+ Type.Literal("blocked"),
13
+ Type.Literal("failed"),
14
+ Type.Literal("verified"),
15
+ ])),
16
+ blockedReason: Type.Optional(Type.String({ description: "Why work cannot currently proceed; empty clears it." })),
17
+ parent: Type.Optional(Type.String({ description: "Parent task id; empty clears it." })),
18
+ dependsOn: Type.Optional(Type.Array(Type.String(), { description: "Task ids that must be done first." })),
19
+ isolation: Type.Optional(Type.Union([Type.Literal("shared"), Type.Literal("worktree")])),
20
+ sideEffects: Type.Optional(Type.Union([Type.Literal("read-only"), Type.Literal("workspace"), Type.Literal("external")])),
21
+ externalApproval: Type.Optional(Type.Union([Type.Literal("not-required"), Type.Literal("required")], {
22
+ description: 'External approval can only be granted by a user with "/tasks approve <id>".',
23
+ })),
24
+ maxAttempts: Type.Optional(Type.Integer({ minimum: 1 })),
25
+ maxTokens: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
26
+ maxCostUsd: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
27
+ maxWallTimeMinutes: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
28
+ verificationMode: Type.Optional(Type.Union([Type.Literal("evidence"), Type.Literal("independent")], {
29
+ 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.',
30
+ })),
31
+ worktreePath: Type.Optional(Type.String({ description: "Owned worktree path; empty clears it." })),
32
+ worktreeBranch: Type.Optional(Type.String()),
33
+ });
34
+ export const taskManageSchema = Type.Object({
35
+ label: Type.String({ description: "Brief description of the ledger change (shown to the user)" }),
36
+ action: Type.Union([
37
+ Type.Literal("create"),
38
+ Type.Literal("progress"),
39
+ Type.Literal("set"),
40
+ Type.Literal("verify"),
41
+ Type.Literal("done"),
42
+ Type.Literal("cancel"),
43
+ Type.Literal("candidate"),
44
+ Type.Literal("list"),
45
+ ], {
46
+ 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; "list" returns tasks. Recurring cycles are reopened automatically by the runtime.',
47
+ }),
48
+ id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/progress/set/done." })),
49
+ title: Type.Optional(Type.String({ description: "Required for create: task title used as the H1 heading." })),
50
+ goal: Type.Optional(Type.String({ description: "Required for create: concise task goal." })),
51
+ dod: Type.Optional(Type.String({
52
+ 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.',
53
+ })),
54
+ manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
55
+ verificationPlan: Type.Optional(Type.String({ description: "Optional for create: deterministic checks the verifier must perform." })),
56
+ control: Type.Optional(taskControlSchema),
57
+ 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." })),
58
+ wake: Type.Optional(Type.String({
59
+ description: "ISO8601 earliest-recheck time for create/progress/set; empty string clears it. The native task driver resumes it; no .checkin event is needed.",
60
+ })),
61
+ schedule: Type.Optional(Type.String({
62
+ description: "Five-field cron cadence (host timezone) that makes this a recurring task; empty string clears it. " +
63
+ "On done, the driver sleeps the task until the next occurrence and reopens the next cycle automatically. Min every 30 minutes.",
64
+ })),
65
+ recurrence: Type.Optional(Type.String({ description: "Human annotation only (e.g. 每周一); empty string clears it." })),
66
+ note: Type.Optional(Type.String({
67
+ description: "Required for progress: concise Current Cycle entry covering what changed, evidence observed, and the next step.",
68
+ })),
69
+ verifierRunId: Type.Optional(Type.String({ description: "Required for verify: run id returned by a purpose=verify sub-agent." })),
70
+ summary: Type.Optional(Type.String({ description: "Required for done: concise completion summary." })),
71
+ evidence: Type.Optional(Type.String({
72
+ description: "Required for done: verification evidence (tests, commands, review result, external confirmation, or a clear not-run reason).",
73
+ })),
74
+ residualRisk: Type.Optional(Type.String({ description: "Optional for done: remaining risk or follow-up note." })),
75
+ reason: Type.Optional(Type.String({ description: "Required for cancel: why the task was abandoned." })),
76
+ });
77
+ export function parseAction(action) {
78
+ if (action === "create" ||
79
+ action === "progress" ||
80
+ action === "candidate" ||
81
+ action === "set" ||
82
+ action === "verify" ||
83
+ action === "done" ||
84
+ action === "cancel" ||
85
+ action === "list") {
86
+ return action;
87
+ }
88
+ throw new Error("Unsupported task action. Use create, progress, candidate, set, verify, done, cancel, or list.");
89
+ }
@@ -0,0 +1,36 @@
1
+ import type { TaskFields, TaskManageRequest, TaskManageToolOptions } from "./types.js";
2
+ export declare function tasksDir(options: TaskManageToolOptions): string;
3
+ export declare function eventsDir(options: TaskManageToolOptions): string;
4
+ export declare function renderTaskFile(fields: TaskFields, body: string): string;
5
+ export declare function requiredField(value: string | undefined, field: string, action: string): string;
6
+ export declare function requireNonEmpty(value: string | undefined, field: string): string;
7
+ export declare function markdownValue(value: string): string;
8
+ export declare function appendCompletionEvidence(body: string, request: TaskManageRequest): string;
9
+ export declare function renderTaskSkeleton(request: TaskManageRequest): {
10
+ fields: TaskFields;
11
+ body: string;
12
+ };
13
+ /**
14
+ * Read a task file and split it into validated frontmatter and a verbatim body.
15
+ * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
16
+ * rather than guessed at, so task_manage never silently mangles a body.
17
+ */
18
+ export declare function readTaskDocument(taskPath: string, id: string, allowControlRepair?: boolean): Promise<{
19
+ fields: TaskFields;
20
+ body: string;
21
+ }>;
22
+ /** Apply a `set` request's optional fields onto the existing frontmatter. */
23
+ export declare function applySet(fields: TaskFields, request: TaskManageRequest): TaskFields;
24
+ export declare function validateTaskRelations(options: TaskManageToolOptions, id: string, fields: TaskFields): Promise<void>;
25
+ /**
26
+ * On close-out (done or cancel), delete every task-owned event.
27
+ *
28
+ * Recurrence cadence now lives solely in the task's `schedule` frontmatter (027/029), so a
29
+ * recurring task needs no surviving `.schedule` event — the driver reopens each cycle from
30
+ * frontmatter. Any remaining task-owned events are temporary sensors/check-ins that a closed
31
+ * task should not keep alive. A file that cannot be parsed is left for `/events` to handle.
32
+ */
33
+ export declare function cleanupTaskEvents(options: TaskManageToolOptions, id: string): Promise<{
34
+ deleted: string[];
35
+ }>;
36
+ export declare function unfinishedChildren(options: TaskManageToolOptions, parentId: string): Promise<string[]>;