@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
|
@@ -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[]>;
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readdir, readFile, unlink } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { parseScheduledEventContent } from "../../runtime/events.js";
|
|
5
|
+
import { taskEventPrefix } from "../../shared/task-events.js";
|
|
6
|
+
import { parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, renderTaskDocument, taskBody, } from "../../shared/task-ledger.js";
|
|
7
|
+
import { nextTaskWake, validateTaskSchedule } from "../../shared/task-schedule.js";
|
|
8
|
+
import { applyTaskControlPatch, createDefaultTaskControl } from "../../tasks/control.js";
|
|
9
|
+
import { readStoredTask } from "../../tasks/store.js";
|
|
10
|
+
import { isSettableTaskStatus } from "../../tasks/transitions.js";
|
|
11
|
+
import { SETTABLE_STATUSES } from "./schema.js";
|
|
12
|
+
export function tasksDir(options) {
|
|
13
|
+
return join(options.channelDir, "tasks");
|
|
14
|
+
}
|
|
15
|
+
export function eventsDir(options) {
|
|
16
|
+
return join(options.workspaceDir, "events");
|
|
17
|
+
}
|
|
18
|
+
export function renderTaskFile(fields, body) {
|
|
19
|
+
return renderTaskDocument(fields, body);
|
|
20
|
+
}
|
|
21
|
+
export function requiredField(value, field, action) {
|
|
22
|
+
const trimmed = value?.trim();
|
|
23
|
+
if (!trimmed) {
|
|
24
|
+
throw new Error(`action "${action}" requires ${field}.`);
|
|
25
|
+
}
|
|
26
|
+
return trimmed;
|
|
27
|
+
}
|
|
28
|
+
export function requireNonEmpty(value, field) {
|
|
29
|
+
return requiredField(value, field, "done");
|
|
30
|
+
}
|
|
31
|
+
export function markdownValue(value) {
|
|
32
|
+
const lines = value.trim().split(/\r?\n/);
|
|
33
|
+
if (lines.length === 1)
|
|
34
|
+
return lines[0];
|
|
35
|
+
return lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join("\n");
|
|
36
|
+
}
|
|
37
|
+
export function appendCompletionEvidence(body, request) {
|
|
38
|
+
const summary = requireNonEmpty(request.summary, "summary");
|
|
39
|
+
const evidence = requireNonEmpty(request.evidence, "evidence");
|
|
40
|
+
const lines = [
|
|
41
|
+
"## Completion Evidence",
|
|
42
|
+
"",
|
|
43
|
+
`- Summary: ${markdownValue(summary)}`,
|
|
44
|
+
`- Evidence: ${markdownValue(evidence)}`,
|
|
45
|
+
];
|
|
46
|
+
const residualRisk = request.residualRisk?.trim();
|
|
47
|
+
if (residualRisk) {
|
|
48
|
+
lines.push(`- Residual risk: ${markdownValue(residualRisk)}`);
|
|
49
|
+
}
|
|
50
|
+
const normalizedBody = body.endsWith("\n") ? body.replace(/\n+$/, "\n") : `${body}\n`;
|
|
51
|
+
return `${normalizedBody}\n${lines.join("\n")}\n`;
|
|
52
|
+
}
|
|
53
|
+
function normalizeCreateStatus(status) {
|
|
54
|
+
if (status === undefined)
|
|
55
|
+
return "active";
|
|
56
|
+
if (isSettableTaskStatus(status))
|
|
57
|
+
return status;
|
|
58
|
+
throw new Error(`Invalid status "${status}". Use one of ${SETTABLE_STATUSES.join(", ")}.`);
|
|
59
|
+
}
|
|
60
|
+
export function renderTaskSkeleton(request) {
|
|
61
|
+
const title = requiredField(request.title, "title", "create");
|
|
62
|
+
const goal = requiredField(request.goal, "goal", "create");
|
|
63
|
+
const dod = requiredField(request.dod, "dod", "create");
|
|
64
|
+
// Independent verification is a real tax (an extra dispatch round plus a verifier
|
|
65
|
+
// sub-agent run) that only pays off when there is something a read-only verifier can
|
|
66
|
+
// actually check. Default to evidence (maker self-checks the DoD); the tool schema asks
|
|
67
|
+
// the model to opt into independent explicitly for tasks with a checkable artifact.
|
|
68
|
+
const mode = request.control?.verificationMode ?? "evidence";
|
|
69
|
+
const control = applyTaskControlPatch(createDefaultTaskControl(mode), request.control ?? {});
|
|
70
|
+
const fields = applySet({ status: normalizeCreateStatus(request.status), control }, request);
|
|
71
|
+
// First-cycle scheduling. A recurring task created without an explicit wake follows cron
|
|
72
|
+
// semantics: its first run is deferred to the next scheduled occurrence, not fired now.
|
|
73
|
+
// Without this the task is `active` + no `wake` → immediately actionable, so the driver
|
|
74
|
+
// resumes it the instant it is created (ignoring the schedule) and re-dispatches it every
|
|
75
|
+
// backoff interval; an agent expecting a scheduled wake then idles through those dispatches.
|
|
76
|
+
// Seeding the first wake here mirrors what `done` does for every subsequent cycle. Only a
|
|
77
|
+
// freshly opened task with no caller-supplied wake is seeded — an explicit wake (including a
|
|
78
|
+
// past one for "start now") or a non-active initial status is always honoured verbatim.
|
|
79
|
+
if (fields.schedule && fields.status === "active" && request.wake === undefined) {
|
|
80
|
+
fields.wake = nextTaskWake(fields.schedule)?.toISOString();
|
|
81
|
+
}
|
|
82
|
+
const body = renderStandardTaskBody({
|
|
83
|
+
title,
|
|
84
|
+
goal,
|
|
85
|
+
dod,
|
|
86
|
+
manual: request.manual,
|
|
87
|
+
verificationPlan: request.verificationPlan,
|
|
88
|
+
verificationMode: control.verification.mode,
|
|
89
|
+
});
|
|
90
|
+
return { fields, body };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Read a task file and split it into validated frontmatter and a verbatim body.
|
|
94
|
+
* Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
|
|
95
|
+
* rather than guessed at, so task_manage never silently mangles a body.
|
|
96
|
+
*/
|
|
97
|
+
export async function readTaskDocument(taskPath, id, allowControlRepair = false) {
|
|
98
|
+
if (!existsSync(taskPath)) {
|
|
99
|
+
throw new Error(`Task "${id}" does not exist; create it with task_manage action "create" first.`);
|
|
100
|
+
}
|
|
101
|
+
const content = await readFile(taskPath, "utf-8");
|
|
102
|
+
const frontmatter = parseTaskFrontmatter(content);
|
|
103
|
+
if (!frontmatter.readable) {
|
|
104
|
+
throw new Error(`Task "${id}" has no readable frontmatter; fix it with edit before using task_manage.`);
|
|
105
|
+
}
|
|
106
|
+
if (frontmatter.controlReadable === false && !allowControlRepair) {
|
|
107
|
+
throw new Error(`Task "${id}" has invalid control metadata; repair it with task_manage action "set" and an explicit control patch first.`);
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
fields: {
|
|
111
|
+
status: frontmatter.status ?? "active",
|
|
112
|
+
wake: frontmatter.wake,
|
|
113
|
+
schedule: frontmatter.schedule,
|
|
114
|
+
recurrence: frontmatter.recurrence,
|
|
115
|
+
control: frontmatter.control,
|
|
116
|
+
},
|
|
117
|
+
body: taskBody(content),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Apply a `set` request's optional fields onto the existing frontmatter. */
|
|
121
|
+
export function applySet(fields, request) {
|
|
122
|
+
const next = { ...fields };
|
|
123
|
+
if (request.control?.externalApproval === "granted") {
|
|
124
|
+
throw new Error('Only a user can grant external-action approval with "/tasks approve <id>".');
|
|
125
|
+
}
|
|
126
|
+
if (request.status !== undefined) {
|
|
127
|
+
if (!isSettableTaskStatus(request.status)) {
|
|
128
|
+
throw new Error(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or action "done".`);
|
|
129
|
+
}
|
|
130
|
+
next.status = request.status;
|
|
131
|
+
}
|
|
132
|
+
if (request.wake !== undefined) {
|
|
133
|
+
const trimmed = request.wake.trim();
|
|
134
|
+
if (trimmed === "") {
|
|
135
|
+
next.wake = undefined;
|
|
136
|
+
}
|
|
137
|
+
else if (!Number.isFinite(new Date(trimmed).getTime())) {
|
|
138
|
+
throw new Error(`wake "${request.wake}" is not a valid ISO8601 date.`);
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
next.wake = trimmed;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (request.schedule !== undefined) {
|
|
145
|
+
const trimmed = request.schedule.trim();
|
|
146
|
+
if (trimmed === "") {
|
|
147
|
+
next.schedule = undefined;
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
validateTaskSchedule(trimmed);
|
|
151
|
+
next.schedule = trimmed;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (request.recurrence !== undefined) {
|
|
155
|
+
const trimmed = request.recurrence.trim();
|
|
156
|
+
next.recurrence = trimmed === "" ? undefined : trimmed;
|
|
157
|
+
}
|
|
158
|
+
if (request.control !== undefined) {
|
|
159
|
+
next.control = applyTaskControlPatch(next.control ?? createDefaultTaskControl("evidence"), request.control);
|
|
160
|
+
}
|
|
161
|
+
// A done recurring task's wake is the single time rule's job: `normalizeTaskFields` fills the
|
|
162
|
+
// next occurrence on the write path, so no per-action recompute lives here anymore (D1).
|
|
163
|
+
return next;
|
|
164
|
+
}
|
|
165
|
+
export async function validateTaskRelations(options, id, fields) {
|
|
166
|
+
const control = fields.control;
|
|
167
|
+
if (!control)
|
|
168
|
+
return;
|
|
169
|
+
if (control.parent === id || control.dependsOn.includes(id)) {
|
|
170
|
+
throw new Error(`Task "${id}" cannot be its own parent or dependency.`);
|
|
171
|
+
}
|
|
172
|
+
for (const relatedId of [control.parent, ...control.dependsOn].filter((value) => Boolean(value))) {
|
|
173
|
+
const active = join(tasksDir(options), `${relatedId}.md`);
|
|
174
|
+
const archived = join(tasksDir(options), "archive", `${relatedId}.md`);
|
|
175
|
+
if (!existsSync(active) && !existsSync(archived)) {
|
|
176
|
+
throw new Error(`Related task "${relatedId}" does not exist; create it before linking task "${id}".`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (control.parent) {
|
|
180
|
+
const visited = new Set();
|
|
181
|
+
let current = control.parent;
|
|
182
|
+
while (current) {
|
|
183
|
+
if (visited.has(current)) {
|
|
184
|
+
throw new Error(`Existing parent chain for "${control.parent}" already contains a cycle.`);
|
|
185
|
+
}
|
|
186
|
+
if (current === id) {
|
|
187
|
+
throw new Error(`Task parent cycle detected while linking "${id}" to "${control.parent}".`);
|
|
188
|
+
}
|
|
189
|
+
visited.add(current);
|
|
190
|
+
const task = await readStoredTask(options.channelDir, current, true);
|
|
191
|
+
current = task?.fields.control?.parent;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
for (const dependencyId of control.dependsOn) {
|
|
195
|
+
const visited = new Set();
|
|
196
|
+
const stack = [dependencyId];
|
|
197
|
+
while (stack.length > 0) {
|
|
198
|
+
const current = stack.pop();
|
|
199
|
+
if (!current || visited.has(current))
|
|
200
|
+
continue;
|
|
201
|
+
if (current === id) {
|
|
202
|
+
throw new Error(`Task dependency cycle detected while linking "${id}" to "${dependencyId}".`);
|
|
203
|
+
}
|
|
204
|
+
visited.add(current);
|
|
205
|
+
const task = await readStoredTask(options.channelDir, current, true);
|
|
206
|
+
stack.push(...(task?.fields.control?.dependsOn ?? []));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* On close-out (done or cancel), delete every task-owned event.
|
|
212
|
+
*
|
|
213
|
+
* Recurrence cadence now lives solely in the task's `schedule` frontmatter (027/029), so a
|
|
214
|
+
* recurring task needs no surviving `.schedule` event — the driver reopens each cycle from
|
|
215
|
+
* frontmatter. Any remaining task-owned events are temporary sensors/check-ins that a closed
|
|
216
|
+
* task should not keep alive. A file that cannot be parsed is left for `/events` to handle.
|
|
217
|
+
*/
|
|
218
|
+
export async function cleanupTaskEvents(options, id) {
|
|
219
|
+
const dir = eventsDir(options);
|
|
220
|
+
if (!existsSync(dir))
|
|
221
|
+
return { deleted: [] };
|
|
222
|
+
const prefix = taskEventPrefix(options.channelId, id);
|
|
223
|
+
const deleted = [];
|
|
224
|
+
for (const filename of (await readdir(dir)).sort()) {
|
|
225
|
+
if (!filename.endsWith(".json") || !filename.startsWith(prefix))
|
|
226
|
+
continue;
|
|
227
|
+
const eventPath = join(dir, filename);
|
|
228
|
+
try {
|
|
229
|
+
parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename);
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
continue; // can't classify → leave it for /events to handle
|
|
233
|
+
}
|
|
234
|
+
await unlink(eventPath);
|
|
235
|
+
deleted.push(filename.slice(0, -".json".length));
|
|
236
|
+
}
|
|
237
|
+
return { deleted };
|
|
238
|
+
}
|
|
239
|
+
export async function unfinishedChildren(options, parentId) {
|
|
240
|
+
const entries = await readActiveTasks(tasksDir(options));
|
|
241
|
+
return entries
|
|
242
|
+
.filter((entry) => entry.frontmatter.control?.parent === parentId &&
|
|
243
|
+
entry.frontmatter.status !== "done" &&
|
|
244
|
+
entry.frontmatter.status !== "cancelled")
|
|
245
|
+
.map((entry) => entry.id);
|
|
246
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { TaskControl, TaskControlPatch } from "../../tasks/control.js";
|
|
2
|
+
export type TaskManageAction = "create" | "progress" | "candidate" | "set" | "verify" | "done" | "cancel" | "list";
|
|
3
|
+
export interface TaskManageResult {
|
|
4
|
+
action: TaskManageAction;
|
|
5
|
+
id?: string;
|
|
6
|
+
path?: string;
|
|
7
|
+
status?: string;
|
|
8
|
+
archived?: boolean;
|
|
9
|
+
deletedEvents?: string[];
|
|
10
|
+
tasks?: Array<{
|
|
11
|
+
id: string;
|
|
12
|
+
title: string;
|
|
13
|
+
status: string;
|
|
14
|
+
wake?: string;
|
|
15
|
+
actionable: boolean;
|
|
16
|
+
control?: TaskControl;
|
|
17
|
+
}>;
|
|
18
|
+
notice: string;
|
|
19
|
+
}
|
|
20
|
+
export interface TaskManageRequest {
|
|
21
|
+
action: TaskManageAction;
|
|
22
|
+
id?: string;
|
|
23
|
+
title?: string;
|
|
24
|
+
goal?: string;
|
|
25
|
+
dod?: string;
|
|
26
|
+
manual?: string;
|
|
27
|
+
status?: string;
|
|
28
|
+
wake?: string;
|
|
29
|
+
schedule?: string;
|
|
30
|
+
recurrence?: string;
|
|
31
|
+
note?: string;
|
|
32
|
+
verificationPlan?: string;
|
|
33
|
+
control?: TaskControlPatch;
|
|
34
|
+
verifierRunId?: string;
|
|
35
|
+
summary?: string;
|
|
36
|
+
evidence?: string;
|
|
37
|
+
residualRisk?: string;
|
|
38
|
+
reason?: string;
|
|
39
|
+
}
|
|
40
|
+
export interface TaskManageToolOptions {
|
|
41
|
+
workspaceDir: string;
|
|
42
|
+
channelDir: string;
|
|
43
|
+
channelId: string;
|
|
44
|
+
/** Project checkout whose artifact state an independent verifier binds to. */
|
|
45
|
+
workingDirectory?: string;
|
|
46
|
+
}
|
|
47
|
+
export interface TaskFields {
|
|
48
|
+
status: string;
|
|
49
|
+
wake?: string;
|
|
50
|
+
schedule?: string;
|
|
51
|
+
recurrence?: string;
|
|
52
|
+
control?: TaskControl;
|
|
53
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type TaskVerification } from "../../tasks/control.js";
|
|
2
|
+
import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Move a task into the verification lane. The runtime driver will explicitly
|
|
5
|
+
* wake a fresh verifier on the next attempt, keeping the maker from grading
|
|
6
|
+
* its own work in the same reasoning context.
|
|
7
|
+
*/
|
|
8
|
+
export declare function candidateTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
|
|
9
|
+
export declare function verifyTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
|
|
10
|
+
/**
|
|
11
|
+
* `verify` writes control.verification from a real attestation file, but the task Markdown
|
|
12
|
+
* itself is writable by the agent's own write/edit tools — nothing stops it from hand-crafting
|
|
13
|
+
* a "passed" verification block that was never backed by a real verifier run. Re-check the
|
|
14
|
+
* attestation file on the consuming side (done/doctor) too, not just at import time.
|
|
15
|
+
*/
|
|
16
|
+
export declare function assertVerificationAttestationMatches(channelDir: string, id: string, verification: TaskVerification): Promise<void>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { writeFileAtomically } from "../../shared/atomic-file.js";
|
|
3
|
+
import { appendCurrentCycleNote, normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../shared/task-ledger.js";
|
|
4
|
+
import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
|
|
5
|
+
import { createDefaultTaskControl } from "../../tasks/control.js";
|
|
6
|
+
import { readStoredTask, taskBodyHash } from "../../tasks/store.js";
|
|
7
|
+
import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
|
|
8
|
+
import { readVerificationAttestation } from "../../tasks/verification.js";
|
|
9
|
+
import { readTaskDocument, renderTaskFile, requiredField, tasksDir } from "./shared.js";
|
|
10
|
+
/**
|
|
11
|
+
* Move a task into the verification lane. The runtime driver will explicitly
|
|
12
|
+
* wake a fresh verifier on the next attempt, keeping the maker from grading
|
|
13
|
+
* its own work in the same reasoning context.
|
|
14
|
+
*/
|
|
15
|
+
export async function candidateTask(options, request) {
|
|
16
|
+
if (!request.id)
|
|
17
|
+
throw new Error('action "candidate" requires an id.');
|
|
18
|
+
const id = normalizeTaskId(request.id);
|
|
19
|
+
const note = requiredField(request.note, "note", "candidate");
|
|
20
|
+
const taskPath = join(tasksDir(options), `${id}.md`);
|
|
21
|
+
const { fields, body } = await readTaskDocument(taskPath, id);
|
|
22
|
+
resolveTaskTransition("candidate", id, normalizeStoredStatus(fields.status));
|
|
23
|
+
const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
|
|
24
|
+
if (uncheckedAcceptance.length > 0) {
|
|
25
|
+
throw new Error(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before requesting verification.`);
|
|
26
|
+
}
|
|
27
|
+
const control = fields.control ?? createDefaultTaskControl("independent");
|
|
28
|
+
control.verification = { mode: "independent", status: "pending" };
|
|
29
|
+
control.lastOutcome = "progress";
|
|
30
|
+
control.blockedReason = undefined;
|
|
31
|
+
control.nextAction = "Run a purpose=verify sub-agent and import its attestation.";
|
|
32
|
+
const nextBody = appendCurrentCycleNote(body, note);
|
|
33
|
+
await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "verifying", wake: undefined, control }, nextBody));
|
|
34
|
+
return {
|
|
35
|
+
action: "candidate",
|
|
36
|
+
id,
|
|
37
|
+
path: taskPath,
|
|
38
|
+
status: "verifying",
|
|
39
|
+
notice: `任务 \`${id}\` 已进入独立验收队列;driver 将安排 verifier。`,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export async function verifyTask(options, request) {
|
|
43
|
+
if (!request.id)
|
|
44
|
+
throw new Error('action "verify" requires an id.');
|
|
45
|
+
const id = normalizeTaskId(request.id);
|
|
46
|
+
const runId = requiredField(request.verifierRunId, "verifierRunId", "verify");
|
|
47
|
+
const task = await readStoredTask(options.channelDir, id);
|
|
48
|
+
if (!task)
|
|
49
|
+
throw new Error(`Task "${id}" does not exist; create it before verification.`);
|
|
50
|
+
const attestation = await readVerificationAttestation(options.channelDir, runId);
|
|
51
|
+
if (attestation.taskId !== id) {
|
|
52
|
+
throw new Error(`Verification run "${runId}" belongs to task "${attestation.taskId}", not "${id}".`);
|
|
53
|
+
}
|
|
54
|
+
if (attestation.workspaceChanged) {
|
|
55
|
+
throw new Error(`Verification run "${runId}" changed the workspace; rerun a read-only verifier.`);
|
|
56
|
+
}
|
|
57
|
+
if (attestation.bodyHash !== taskBodyHash(task.body)) {
|
|
58
|
+
throw new Error(`Task "${id}" changed after verification run "${runId}"; rerun the verifier on current content.`);
|
|
59
|
+
}
|
|
60
|
+
if (attestation.subjectHash) {
|
|
61
|
+
const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
|
|
62
|
+
if (!currentSubject) {
|
|
63
|
+
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.`);
|
|
64
|
+
}
|
|
65
|
+
if (currentSubject !== attestation.subjectHash) {
|
|
66
|
+
throw new Error(`Task "${id}" artifacts changed after verification run "${runId}"; rerun the verifier.`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const control = task.fields.control ?? createDefaultTaskControl("independent");
|
|
70
|
+
control.verification = {
|
|
71
|
+
mode: "independent",
|
|
72
|
+
status: attestation.verdict === "pass" ? "passed" : "failed",
|
|
73
|
+
runId,
|
|
74
|
+
evidence: attestation.evidence,
|
|
75
|
+
bodyHash: attestation.bodyHash,
|
|
76
|
+
subjectHash: attestation.subjectHash,
|
|
77
|
+
checkedAt: attestation.checkedAt,
|
|
78
|
+
};
|
|
79
|
+
control.lastOutcome = attestation.verdict === "pass" ? "verified" : "failed";
|
|
80
|
+
control.blockedReason = attestation.verdict === "fail" ? attestation.evidence : undefined;
|
|
81
|
+
task.fields.control = control;
|
|
82
|
+
await writeFileAtomically(task.path, renderTaskFile(task.fields, task.body));
|
|
83
|
+
return {
|
|
84
|
+
action: "verify",
|
|
85
|
+
id,
|
|
86
|
+
path: task.path,
|
|
87
|
+
status: task.fields.status,
|
|
88
|
+
notice: `任务 \`${id}\` 独立验收结果:${attestation.verdict.toUpperCase()}(run: ${runId})。`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* `verify` writes control.verification from a real attestation file, but the task Markdown
|
|
93
|
+
* itself is writable by the agent's own write/edit tools — nothing stops it from hand-crafting
|
|
94
|
+
* a "passed" verification block that was never backed by a real verifier run. Re-check the
|
|
95
|
+
* attestation file on the consuming side (done/doctor) too, not just at import time.
|
|
96
|
+
*/
|
|
97
|
+
export async function assertVerificationAttestationMatches(channelDir, id, verification) {
|
|
98
|
+
if (!verification.runId) {
|
|
99
|
+
throw new Error(`Task "${id}" has no verification run id; rerun task_manage verify before done.`);
|
|
100
|
+
}
|
|
101
|
+
const attestation = await readVerificationAttestation(channelDir, verification.runId);
|
|
102
|
+
if (attestation.taskId !== id) {
|
|
103
|
+
throw new Error(`Verification run "${verification.runId}" belongs to task "${attestation.taskId}", not "${id}"; rerun verification.`);
|
|
104
|
+
}
|
|
105
|
+
if (attestation.verdict !== "pass") {
|
|
106
|
+
throw new Error(`Verification run "${verification.runId}" recorded a FAIL, not a PASS; rerun verification.`);
|
|
107
|
+
}
|
|
108
|
+
if (attestation.bodyHash !== verification.bodyHash) {
|
|
109
|
+
throw new Error(`Task "${id}" control.verification.bodyHash does not match the attestation for run "${verification.runId}"; rerun task_manage verify.`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -1,92 +1,12 @@
|
|
|
1
1
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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<"blocked" | "paused" | "open" | "in-progress" | "awaiting-user">[]>>;
|
|
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
|
-
cycleId: Type.TOptional<Type.TString>;
|
|
43
|
-
}>;
|
|
44
|
-
export type TaskManageAction = "create" | "progress" | "candidate" | "set" | "verify" | "done" | "cancel" | "start-cycle" | "list";
|
|
45
|
-
export interface TaskManageResult {
|
|
46
|
-
action: TaskManageAction;
|
|
47
|
-
id?: string;
|
|
48
|
-
path?: string;
|
|
49
|
-
status?: string;
|
|
50
|
-
archived?: boolean;
|
|
51
|
-
deletedEvents?: string[];
|
|
52
|
-
tasks?: Array<{
|
|
53
|
-
id: string;
|
|
54
|
-
title: string;
|
|
55
|
-
status: string;
|
|
56
|
-
wake?: string;
|
|
57
|
-
actionable: boolean;
|
|
58
|
-
control?: TaskControl;
|
|
59
|
-
}>;
|
|
60
|
-
notice: string;
|
|
61
|
-
}
|
|
62
|
-
export interface TaskManageRequest {
|
|
63
|
-
action: TaskManageAction;
|
|
64
|
-
id?: string;
|
|
65
|
-
title?: string;
|
|
66
|
-
goal?: string;
|
|
67
|
-
dod?: string;
|
|
68
|
-
manual?: string;
|
|
69
|
-
status?: string;
|
|
70
|
-
wake?: string;
|
|
71
|
-
schedule?: string;
|
|
72
|
-
recurrence?: string;
|
|
73
|
-
note?: string;
|
|
74
|
-
verificationPlan?: string;
|
|
75
|
-
control?: TaskControlPatch;
|
|
76
|
-
verifierRunId?: string;
|
|
77
|
-
summary?: string;
|
|
78
|
-
evidence?: string;
|
|
79
|
-
residualRisk?: string;
|
|
80
|
-
reason?: string;
|
|
81
|
-
cycleId?: string;
|
|
82
|
-
}
|
|
83
|
-
export interface TaskManageToolOptions {
|
|
84
|
-
workspaceDir: string;
|
|
85
|
-
channelDir: string;
|
|
86
|
-
channelId: string;
|
|
87
|
-
/** Project checkout whose artifact state an independent verifier binds to. */
|
|
88
|
-
workingDirectory?: string;
|
|
89
|
-
}
|
|
2
|
+
import { taskManageSchema } from "./task-manage/schema.js";
|
|
3
|
+
import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./task-manage/types.js";
|
|
4
|
+
export type { TaskManageAction, TaskManageRequest, TaskManageResult, TaskManageToolOptions, } from "./task-manage/types.js";
|
|
5
|
+
/**
|
|
6
|
+
* The `task_manage` dispatcher. Each action lives in a focused module — `create`,
|
|
7
|
+
* `lifecycle` (progress/set/done/cancel/list) and `verification` (candidate/verify) — over a
|
|
8
|
+
* shared helper layer, with the status transition table in `src/tasks/transitions.ts` (spec
|
|
9
|
+
* 029, D7). This entry only routes and wraps the tool.
|
|
10
|
+
*/
|
|
90
11
|
export declare function manageTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
|
|
91
12
|
export declare function createTaskManageTool(options: TaskManageToolOptions): AgentTool<typeof taskManageSchema>;
|
|
92
|
-
export {};
|