@oyasmi/pipiclaw 0.8.8-beta.2 → 0.8.9-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +8 -0
- package/dist/agent/runner-factory.d.ts +2 -0
- package/dist/memory/task-digest.js +1 -1
- package/dist/playbooks/task-closeout.md +11 -10
- package/dist/playbooks/task-delegation.md +1 -1
- package/dist/playbooks/task-driving.md +6 -7
- package/dist/playbooks/task-planning.md +7 -5
- package/dist/playbooks/task-recurring.md +7 -4
- package/dist/playbooks/task-repair.md +7 -7
- package/dist/runtime/bootstrap.d.ts +12 -1
- package/dist/runtime/bootstrap.js +9 -1
- package/dist/runtime/task-commands.js +29 -51
- package/dist/runtime/task-driver.d.ts +3 -8
- package/dist/runtime/task-driver.js +97 -84
- package/dist/runtime/task-migration.d.ts +11 -0
- package/dist/runtime/task-migration.js +70 -0
- package/dist/security/path-guard.js +3 -1
- package/dist/shared/task-events.d.ts +0 -26
- package/dist/shared/task-events.js +0 -15
- package/dist/shared/task-ledger.d.ts +23 -1
- package/dist/shared/task-ledger.js +65 -16
- package/dist/tasks/control.d.ts +4 -0
- package/dist/tasks/control.js +3 -0
- package/dist/tasks/store.d.ts +28 -1
- package/dist/tasks/store.js +63 -6
- package/dist/tasks/transitions.d.ts +40 -0
- package/dist/tasks/transitions.js +81 -0
- package/dist/tools/task-manage/create.d.ts +2 -0
- package/dist/tools/task-manage/create.js +34 -0
- package/dist/tools/task-manage/lifecycle.d.ts +6 -0
- package/dist/tools/task-manage/lifecycle.js +196 -0
- package/dist/tools/task-manage/schema.d.ts +43 -0
- package/dist/tools/task-manage/schema.js +89 -0
- package/dist/tools/task-manage/shared.d.ts +36 -0
- package/dist/tools/task-manage/shared.js +246 -0
- package/dist/tools/task-manage/types.d.ts +53 -0
- package/dist/tools/task-manage/types.js +1 -0
- package/dist/tools/task-manage/verification.d.ts +16 -0
- package/dist/tools/task-manage/verification.js +111 -0
- package/dist/tools/task-manage.d.ts +9 -89
- package/dist/tools/task-manage.js +8 -696
- package/package.json +5 -1
package/dist/tasks/store.d.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { type TaskDocumentFields } from "../shared/task-ledger.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type TaskControl, type TaskOutcome } from "./control.js";
|
|
3
3
|
export interface StoredTaskDocument {
|
|
4
4
|
id: string;
|
|
5
5
|
path: string;
|
|
6
6
|
fields: TaskDocumentFields;
|
|
7
7
|
body: string;
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Hash the task's *contract* segment (Goal/DoD/Manual/Verification), not the whole body, so
|
|
11
|
+
* verification PASS and external approval survive routine Current Cycle / History logging and
|
|
12
|
+
* only break when the contract itself changes (spec 029, D4). Old attestations that hashed the
|
|
13
|
+
* whole body naturally fail this check after upgrade and are re-verified — verification should
|
|
14
|
+
* always reflect current content, so there is no compatibility burden.
|
|
15
|
+
*/
|
|
9
16
|
export declare function taskBodyHash(body: string): string;
|
|
10
17
|
export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
|
|
11
18
|
export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
|
|
@@ -26,7 +33,27 @@ export declare function finishTaskAttempt(channelDir: string, id: string, result
|
|
|
26
33
|
silent?: boolean;
|
|
27
34
|
finishedAt: Date;
|
|
28
35
|
}): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* A governor stop: the deterministic task governor pauses the task (spec 029, D3 — this is
|
|
38
|
+
* the former `escalated` status, now `paused` + `pausedBy: "governor"`), records the reason,
|
|
39
|
+
* and clears the wake so no automatic dispatch resumes it until a human intervenes.
|
|
40
|
+
*/
|
|
29
41
|
export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
|
|
42
|
+
/**
|
|
43
|
+
* A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
|
|
44
|
+
* with a `-N` suffix when the same task is reopened more than once on the same local day.
|
|
45
|
+
*/
|
|
46
|
+
export declare function nextCycleId(previousCycleId: string | undefined, now: Date): string;
|
|
47
|
+
/**
|
|
48
|
+
* Open the next cycle of a done recurring task entirely in the runtime (spec 029, D2):
|
|
49
|
+
* fold the previous cycle's log into History, reset per-cycle control, clear the wake, and
|
|
50
|
+
* mark it `active`. This is the deterministic replacement for the retired
|
|
51
|
+
* `task_manage start-cycle` action — no LLM turn is spent just to reopen a cycle.
|
|
52
|
+
*/
|
|
53
|
+
export declare function openRecurringTaskCycle(channelDir: string, id: string, now: Date): Promise<{
|
|
54
|
+
document: StoredTaskDocument;
|
|
55
|
+
cycleId: string;
|
|
56
|
+
} | undefined>;
|
|
30
57
|
export declare function dependencyState(channelDir: string, dependencyIds: readonly string[], ownerId?: string): Promise<{
|
|
31
58
|
ready: boolean;
|
|
32
59
|
reason?: string;
|
package/dist/tasks/store.js
CHANGED
|
@@ -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 ?? "
|
|
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 = "
|
|
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"
|
|
147
|
-
return { ready: false, reason: `dependency ${dependencyId} is
|
|
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,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;
|