@oyasmi/pipiclaw 0.7.6 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +13 -0
  2. package/dist/agent/channel-runner.d.ts +3 -0
  3. package/dist/agent/channel-runner.js +14 -4
  4. package/dist/agent/commands.js +8 -2
  5. package/dist/agent/prompt-builder.js +46 -0
  6. package/dist/agent/session-events.js +5 -0
  7. package/dist/agent/types.d.ts +2 -0
  8. package/dist/memory/recall.js +6 -0
  9. package/dist/memory/task-digest.js +17 -0
  10. package/dist/models/api-keys.d.ts +5 -1
  11. package/dist/models/api-keys.js +10 -4
  12. package/dist/runtime/bootstrap.d.ts +5 -0
  13. package/dist/runtime/bootstrap.js +59 -2
  14. package/dist/runtime/dingtalk.d.ts +2 -0
  15. package/dist/runtime/dingtalk.js +13 -1
  16. package/dist/runtime/durable-dispatch.d.ts +28 -0
  17. package/dist/runtime/durable-dispatch.js +144 -0
  18. package/dist/runtime/events.d.ts +4 -2
  19. package/dist/runtime/events.js +12 -8
  20. package/dist/runtime/task-commands.d.ts +9 -0
  21. package/dist/runtime/task-commands.js +429 -2
  22. package/dist/runtime/task-driver.d.ts +32 -0
  23. package/dist/runtime/task-driver.js +270 -0
  24. package/dist/settings.d.ts +12 -0
  25. package/dist/settings.js +30 -0
  26. package/dist/shared/atomic-file.js +23 -3
  27. package/dist/shared/task-events.d.ts +32 -0
  28. package/dist/shared/task-events.js +29 -0
  29. package/dist/shared/task-ledger.d.ts +53 -0
  30. package/dist/shared/task-ledger.js +246 -8
  31. package/dist/subagents/tool.d.ts +13 -0
  32. package/dist/subagents/tool.js +229 -15
  33. package/dist/tasks/artifact-subject.d.ts +6 -0
  34. package/dist/tasks/artifact-subject.js +29 -0
  35. package/dist/tasks/control.d.ts +83 -0
  36. package/dist/tasks/control.js +292 -0
  37. package/dist/tasks/store.d.ts +32 -0
  38. package/dist/tasks/store.js +142 -0
  39. package/dist/tasks/verification.d.ts +23 -0
  40. package/dist/tasks/verification.js +68 -0
  41. package/dist/tools/registry.d.ts +1 -1
  42. package/dist/tools/registry.js +6 -4
  43. package/dist/tools/task-manage.d.ts +51 -3
  44. package/dist/tools/task-manage.js +491 -37
  45. package/dist/tools/web-fetch.js +3 -0
  46. package/dist/tui/app.js +1 -1
  47. package/dist/tui/commands.js +1 -1
  48. package/package.json +1 -1
@@ -0,0 +1,292 @@
1
+ const PRIORITIES = ["low", "normal", "high", "critical"];
2
+ const ISOLATIONS = ["shared", "worktree"];
3
+ const SIDE_EFFECTS = ["read-only", "workspace", "external"];
4
+ const VERIFICATION_MODES = ["evidence", "independent"];
5
+ const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
6
+ const OUTCOMES = ["pending", "running", "progress", "blocked", "failed", "verified"];
7
+ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
8
+ function isRecord(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10
+ }
11
+ function optionalString(value) {
12
+ if (typeof value !== "string")
13
+ return undefined;
14
+ const trimmed = value.trim();
15
+ return trimmed || undefined;
16
+ }
17
+ function finiteNonNegative(value, fallback = 0) {
18
+ if (value === undefined)
19
+ return fallback;
20
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
21
+ throw new Error("control usage values must be finite non-negative numbers");
22
+ }
23
+ return value;
24
+ }
25
+ function optionalPositive(value) {
26
+ if (value === undefined)
27
+ return undefined;
28
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
29
+ throw new Error("control budget values must be finite positive numbers");
30
+ }
31
+ return value;
32
+ }
33
+ function enumValue(value, values, fallback) {
34
+ if (value === undefined)
35
+ return fallback;
36
+ if (typeof value !== "string" || !values.includes(value)) {
37
+ throw new Error(`control enum value must be one of: ${values.join(", ")}`);
38
+ }
39
+ return value;
40
+ }
41
+ function taskIds(value) {
42
+ if (value === undefined)
43
+ return [];
44
+ if (!Array.isArray(value))
45
+ throw new Error("control.dependsOn must be an array of task ids");
46
+ if (value.some((item) => typeof item !== "string" || !TASK_ID_PATTERN.test(item.trim()))) {
47
+ throw new Error("control.dependsOn contains an invalid task id");
48
+ }
49
+ return Array.from(new Set(value
50
+ .filter((item) => typeof item === "string")
51
+ .map((item) => item.trim())
52
+ .filter((item) => TASK_ID_PATTERN.test(item))));
53
+ }
54
+ function validateTaskId(value, field) {
55
+ if (value && !TASK_ID_PATTERN.test(value))
56
+ throw new Error(`${field} contains an invalid task id: ${value}`);
57
+ }
58
+ export function createDefaultTaskControl(mode = "independent") {
59
+ return {
60
+ version: 1,
61
+ priority: "normal",
62
+ lastOutcome: "pending",
63
+ dependsOn: [],
64
+ isolation: "shared",
65
+ sideEffects: "workspace",
66
+ externalApproval: "not-required",
67
+ budget: { maxAttempts: 12 },
68
+ usage: { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 },
69
+ verification: { mode, status: "pending" },
70
+ };
71
+ }
72
+ export function parseTaskControl(raw) {
73
+ let value;
74
+ try {
75
+ value = JSON.parse(raw);
76
+ }
77
+ catch (error) {
78
+ throw new Error(`control is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
79
+ }
80
+ if (!isRecord(value) || value.version !== 1) {
81
+ throw new Error("control must be a version 1 JSON object");
82
+ }
83
+ const budget = isRecord(value.budget) ? value.budget : {};
84
+ const usage = isRecord(value.usage) ? value.usage : {};
85
+ const verification = isRecord(value.verification) ? value.verification : {};
86
+ const worktree = isRecord(value.worktree) ? value.worktree : undefined;
87
+ const maxAttempts = optionalPositive(budget.maxAttempts);
88
+ if (!maxAttempts || !Number.isInteger(maxAttempts)) {
89
+ throw new Error("control.budget.maxAttempts must be a positive integer");
90
+ }
91
+ const deadline = optionalString(value.deadline);
92
+ if (deadline && !Number.isFinite(new Date(deadline).getTime())) {
93
+ throw new Error("control.deadline must be a valid ISO8601 date");
94
+ }
95
+ const parent = optionalString(value.parent);
96
+ validateTaskId(parent, "control.parent");
97
+ const sideEffects = enumValue(value.sideEffects, SIDE_EFFECTS, "workspace");
98
+ const externalApproval = enumValue(value.externalApproval, ["not-required", "required", "granted"], "not-required");
99
+ const approvalBy = optionalString(value.approvalBy);
100
+ const approvedAt = optionalString(value.approvedAt);
101
+ const approvalBodyHash = optionalString(value.approvalBodyHash);
102
+ if (externalApproval === "granted" &&
103
+ (sideEffects !== "external" ||
104
+ !approvalBy ||
105
+ !approvedAt ||
106
+ !Number.isFinite(new Date(approvedAt).getTime()) ||
107
+ !approvalBodyHash ||
108
+ !/^[a-f0-9]{64}$/i.test(approvalBodyHash))) {
109
+ throw new Error("granted external approval requires external side effects, approvalBy, approvedAt, and approvalBodyHash");
110
+ }
111
+ if (value.worktree !== undefined && (!worktree || !optionalString(worktree.path))) {
112
+ throw new Error("control.worktree must contain a non-empty path");
113
+ }
114
+ return {
115
+ version: 1,
116
+ priority: enumValue(value.priority, PRIORITIES, "normal"),
117
+ deadline,
118
+ nextAction: optionalString(value.nextAction),
119
+ lastOutcome: enumValue(value.lastOutcome, OUTCOMES, "pending"),
120
+ blockedReason: optionalString(value.blockedReason),
121
+ parent,
122
+ dependsOn: taskIds(value.dependsOn),
123
+ isolation: enumValue(value.isolation, ISOLATIONS, "shared"),
124
+ sideEffects,
125
+ externalApproval,
126
+ approvalBy,
127
+ approvedAt,
128
+ approvalBodyHash,
129
+ budget: {
130
+ maxAttempts: Math.max(1, Math.floor(maxAttempts)),
131
+ maxTokens: optionalPositive(budget.maxTokens),
132
+ maxCostUsd: optionalPositive(budget.maxCostUsd),
133
+ maxWallTimeMinutes: optionalPositive(budget.maxWallTimeMinutes),
134
+ },
135
+ usage: {
136
+ attempts: Math.floor(finiteNonNegative(usage.attempts)),
137
+ tokens: Math.floor(finiteNonNegative(usage.tokens)),
138
+ costUsd: finiteNonNegative(usage.costUsd),
139
+ wallTimeMinutes: finiteNonNegative(usage.wallTimeMinutes),
140
+ },
141
+ verification: {
142
+ mode: enumValue(verification.mode, VERIFICATION_MODES, "independent"),
143
+ status: enumValue(verification.status, VERIFICATION_STATUSES, "pending"),
144
+ runId: optionalString(verification.runId),
145
+ evidence: optionalString(verification.evidence),
146
+ bodyHash: optionalString(verification.bodyHash),
147
+ checkedAt: optionalString(verification.checkedAt),
148
+ subjectHash: optionalString(verification.subjectHash),
149
+ },
150
+ worktree: optionalString(worktree?.path)
151
+ ? { path: optionalString(worktree?.path), branch: optionalString(worktree?.branch) }
152
+ : undefined,
153
+ lastStartedAt: optionalString(value.lastStartedAt),
154
+ lastFinishedAt: optionalString(value.lastFinishedAt),
155
+ cycleId: optionalString(value.cycleId),
156
+ };
157
+ }
158
+ /** Reset state which is meaningful only within one recurring task cycle. */
159
+ export function resetTaskControlForCycle(control, cycleId) {
160
+ const normalizedCycleId = cycleId.trim();
161
+ if (!normalizedCycleId)
162
+ throw new Error("cycleId must not be empty.");
163
+ return {
164
+ ...structuredClone(control),
165
+ nextAction: undefined,
166
+ lastOutcome: "pending",
167
+ blockedReason: undefined,
168
+ externalApproval: control.sideEffects === "external" ? "required" : "not-required",
169
+ approvalBy: undefined,
170
+ approvedAt: undefined,
171
+ approvalBodyHash: undefined,
172
+ usage: { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 },
173
+ verification: { mode: control.verification.mode, status: "pending" },
174
+ worktree: undefined,
175
+ lastStartedAt: undefined,
176
+ lastFinishedAt: undefined,
177
+ cycleId: normalizedCycleId,
178
+ };
179
+ }
180
+ function patchOptionalString(current, value) {
181
+ if (value === undefined)
182
+ return current;
183
+ return value.trim() || undefined;
184
+ }
185
+ function patchPositive(current, value, field) {
186
+ if (value === undefined)
187
+ return current;
188
+ if (!Number.isFinite(value) || value < 0)
189
+ throw new Error(`${field} must be a non-negative number.`);
190
+ return value === 0 ? undefined : value;
191
+ }
192
+ export function applyTaskControlPatch(control, patch) {
193
+ const next = structuredClone(control);
194
+ const invalidatesApproval = control.externalApproval === "granted" && Object.keys(patch).length > 0;
195
+ if (patch.priority !== undefined)
196
+ next.priority = patch.priority;
197
+ if (patch.deadline?.trim() && !Number.isFinite(new Date(patch.deadline).getTime())) {
198
+ throw new Error(`deadline "${patch.deadline}" is not a valid ISO8601 date.`);
199
+ }
200
+ next.deadline = patchOptionalString(next.deadline, patch.deadline);
201
+ next.nextAction = patchOptionalString(next.nextAction, patch.nextAction);
202
+ if (patch.lastOutcome !== undefined)
203
+ next.lastOutcome = patch.lastOutcome;
204
+ next.blockedReason = patchOptionalString(next.blockedReason, patch.blockedReason);
205
+ next.parent = patchOptionalString(next.parent, patch.parent);
206
+ validateTaskId(next.parent, "parent");
207
+ if (patch.dependsOn !== undefined) {
208
+ for (const dependency of patch.dependsOn)
209
+ validateTaskId(dependency.trim(), "dependsOn");
210
+ next.dependsOn = taskIds(patch.dependsOn);
211
+ }
212
+ if (patch.isolation !== undefined)
213
+ next.isolation = patch.isolation;
214
+ if (patch.sideEffects !== undefined)
215
+ next.sideEffects = patch.sideEffects;
216
+ if (patch.externalApproval !== undefined)
217
+ next.externalApproval = patch.externalApproval;
218
+ if (patch.maxAttempts !== undefined) {
219
+ if (!Number.isInteger(patch.maxAttempts) || patch.maxAttempts < 1) {
220
+ throw new Error("maxAttempts must be a positive integer.");
221
+ }
222
+ next.budget.maxAttempts = patch.maxAttempts;
223
+ }
224
+ next.budget.maxTokens = patchPositive(next.budget.maxTokens, patch.maxTokens, "maxTokens");
225
+ next.budget.maxCostUsd = patchPositive(next.budget.maxCostUsd, patch.maxCostUsd, "maxCostUsd");
226
+ next.budget.maxWallTimeMinutes = patchPositive(next.budget.maxWallTimeMinutes, patch.maxWallTimeMinutes, "maxWallTimeMinutes");
227
+ if (patch.verificationMode !== undefined && patch.verificationMode !== next.verification.mode) {
228
+ next.verification = { mode: patch.verificationMode, status: "pending" };
229
+ }
230
+ if (patch.worktreePath !== undefined || patch.worktreeBranch !== undefined) {
231
+ const path = patchOptionalString(next.worktree?.path, patch.worktreePath);
232
+ const branch = patchOptionalString(next.worktree?.branch, patch.worktreeBranch);
233
+ next.worktree = path ? { path, branch } : undefined;
234
+ }
235
+ if (next.sideEffects !== "external") {
236
+ next.externalApproval = "not-required";
237
+ next.approvalBy = undefined;
238
+ next.approvedAt = undefined;
239
+ next.approvalBodyHash = undefined;
240
+ }
241
+ if (next.sideEffects === "external" && next.externalApproval === "not-required") {
242
+ next.externalApproval = "required";
243
+ }
244
+ if (invalidatesApproval && next.sideEffects === "external")
245
+ next.externalApproval = "required";
246
+ if (next.externalApproval !== "granted") {
247
+ next.approvalBy = undefined;
248
+ next.approvedAt = undefined;
249
+ next.approvalBodyHash = undefined;
250
+ }
251
+ return next;
252
+ }
253
+ export function taskPriorityRank(priority) {
254
+ return { critical: 0, high: 1, normal: 2, low: 3 }[priority];
255
+ }
256
+ export function taskBudgetViolation(control, nowMs) {
257
+ if (control.deadline) {
258
+ const deadlineMs = new Date(control.deadline).getTime();
259
+ if (Number.isFinite(deadlineMs) && deadlineMs < nowMs)
260
+ return `deadline exceeded (${control.deadline})`;
261
+ }
262
+ if (control.usage.attempts >= control.budget.maxAttempts) {
263
+ return `attempt budget exhausted (${control.usage.attempts}/${control.budget.maxAttempts})`;
264
+ }
265
+ if (control.budget.maxTokens !== undefined && control.usage.tokens >= control.budget.maxTokens) {
266
+ return `token budget exhausted (${control.usage.tokens}/${control.budget.maxTokens})`;
267
+ }
268
+ if (control.budget.maxCostUsd !== undefined && control.usage.costUsd >= control.budget.maxCostUsd) {
269
+ return `cost budget exhausted ($${control.usage.costUsd.toFixed(4)}/$${control.budget.maxCostUsd.toFixed(4)})`;
270
+ }
271
+ if (control.budget.maxWallTimeMinutes !== undefined &&
272
+ control.usage.wallTimeMinutes >= control.budget.maxWallTimeMinutes) {
273
+ return `wall-time budget exhausted (${control.usage.wallTimeMinutes.toFixed(1)}/${control.budget.maxWallTimeMinutes}m)`;
274
+ }
275
+ return undefined;
276
+ }
277
+ export function invalidateTaskVerification(control) {
278
+ if (control.verification.status === "pending")
279
+ return control;
280
+ return { ...control, verification: { mode: control.verification.mode, status: "pending" } };
281
+ }
282
+ export function invalidateTaskApproval(control) {
283
+ if (control.sideEffects !== "external" || control.externalApproval !== "granted")
284
+ return control;
285
+ return {
286
+ ...control,
287
+ externalApproval: "required",
288
+ approvalBy: undefined,
289
+ approvedAt: undefined,
290
+ approvalBodyHash: undefined,
291
+ };
292
+ }
@@ -0,0 +1,32 @@
1
+ import { type TaskDocumentFields } from "../shared/task-ledger.js";
2
+ import type { TaskControl, TaskOutcome } from "./control.js";
3
+ export interface StoredTaskDocument {
4
+ id: string;
5
+ path: string;
6
+ fields: TaskDocumentFields;
7
+ body: string;
8
+ }
9
+ export declare function taskBodyHash(body: string): string;
10
+ export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
11
+ export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
12
+ export declare function updateStoredTask(channelDir: string, id: string, update: (document: StoredTaskDocument) => void, includeArchive?: boolean): Promise<StoredTaskDocument | undefined>;
13
+ export interface TaskAttemptClaim {
14
+ control: TaskControl;
15
+ previousLastOutcome: TaskOutcome;
16
+ previousBlockedReason?: string;
17
+ previousLastStartedAt?: string;
18
+ }
19
+ export declare function claimTaskAttempt(channelDir: string, id: string, now: Date): Promise<TaskAttemptClaim | undefined>;
20
+ export declare function releaseTaskAttemptClaim(channelDir: string, id: string, claim: TaskAttemptClaim, startedAt: Date): Promise<void>;
21
+ export declare function finishTaskAttempt(channelDir: string, id: string, result: {
22
+ tokens: number;
23
+ costUsd: number;
24
+ wallTimeMinutes: number;
25
+ failed: boolean;
26
+ finishedAt: Date;
27
+ }): Promise<void>;
28
+ export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
29
+ export declare function dependencyState(channelDir: string, dependencyIds: readonly string[], ownerId?: string): Promise<{
30
+ ready: boolean;
31
+ reason?: string;
32
+ }>;
@@ -0,0 +1,142 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { writeFileAtomically } from "../shared/atomic-file.js";
6
+ import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, taskBody, } from "../shared/task-ledger.js";
7
+ export function taskBodyHash(body) {
8
+ return createHash("sha256").update(body).digest("hex");
9
+ }
10
+ export async function readStoredTask(channelDir, idInput, includeArchive = false, allowInvalidControl = false) {
11
+ const id = normalizeTaskId(idInput);
12
+ const activePath = join(channelDir, "tasks", `${id}.md`);
13
+ const archivePath = join(channelDir, "tasks", "archive", `${id}.md`);
14
+ const path = existsSync(activePath)
15
+ ? activePath
16
+ : includeArchive && existsSync(archivePath)
17
+ ? archivePath
18
+ : undefined;
19
+ if (!path)
20
+ return undefined;
21
+ const content = await readFile(path, "utf-8");
22
+ const frontmatter = parseTaskFrontmatter(content);
23
+ if (!frontmatter.readable)
24
+ throw new Error(`Task "${id}" has unreadable frontmatter.`);
25
+ if (frontmatter.controlReadable === false && !allowInvalidControl) {
26
+ throw new Error(`Task "${id}" has unreadable control metadata.`);
27
+ }
28
+ return {
29
+ id,
30
+ path,
31
+ fields: {
32
+ status: frontmatter.status ?? "open",
33
+ wake: frontmatter.wake,
34
+ recurrence: frontmatter.recurrence,
35
+ control: frontmatter.control,
36
+ },
37
+ body: taskBody(content),
38
+ };
39
+ }
40
+ export async function writeStoredTask(document) {
41
+ await writeFileAtomically(document.path, renderTaskDocument(document.fields, document.body));
42
+ }
43
+ export async function updateStoredTask(channelDir, id, update, includeArchive = false) {
44
+ const document = await readStoredTask(channelDir, id, includeArchive);
45
+ if (!document)
46
+ return undefined;
47
+ update(document);
48
+ await writeStoredTask(document);
49
+ return document;
50
+ }
51
+ export async function claimTaskAttempt(channelDir, id, now) {
52
+ let claim;
53
+ const document = await updateStoredTask(channelDir, id, (task) => {
54
+ if (!task.fields.control)
55
+ return;
56
+ claim = {
57
+ control: task.fields.control,
58
+ previousLastOutcome: task.fields.control.lastOutcome,
59
+ previousBlockedReason: task.fields.control.blockedReason,
60
+ previousLastStartedAt: task.fields.control.lastStartedAt,
61
+ };
62
+ task.fields.control.usage.attempts++;
63
+ task.fields.control.lastStartedAt = now.toISOString();
64
+ task.fields.control.lastOutcome = "running";
65
+ });
66
+ if (claim && document?.fields.control)
67
+ claim.control = document.fields.control;
68
+ return claim;
69
+ }
70
+ export async function releaseTaskAttemptClaim(channelDir, id, claim, startedAt) {
71
+ await updateStoredTask(channelDir, id, (task) => {
72
+ const control = task.fields.control;
73
+ if (!control || control.lastStartedAt !== startedAt.toISOString())
74
+ return;
75
+ control.usage.attempts = Math.max(0, control.usage.attempts - 1);
76
+ control.lastStartedAt = claim.previousLastStartedAt;
77
+ control.lastOutcome = claim.previousLastOutcome;
78
+ control.blockedReason = claim.previousBlockedReason;
79
+ });
80
+ }
81
+ export async function finishTaskAttempt(channelDir, id, result) {
82
+ await updateStoredTask(channelDir, id, (task) => {
83
+ const control = task.fields.control;
84
+ if (!control)
85
+ return;
86
+ control.usage.tokens += Math.max(0, Math.floor(result.tokens));
87
+ control.usage.costUsd += Math.max(0, result.costUsd);
88
+ control.usage.wallTimeMinutes += Math.max(0, result.wallTimeMinutes);
89
+ control.lastFinishedAt = result.finishedAt.toISOString();
90
+ if (result.failed) {
91
+ control.lastOutcome = "failed";
92
+ control.blockedReason = "The previous agent run failed; inspect the runtime error before retrying.";
93
+ }
94
+ else if (control.lastOutcome === "running") {
95
+ control.lastOutcome = "progress";
96
+ control.blockedReason = undefined;
97
+ }
98
+ }, true);
99
+ }
100
+ export async function escalateTask(channelDir, id, reason) {
101
+ const document = await updateStoredTask(channelDir, id, (task) => {
102
+ task.fields.status = "escalated";
103
+ task.fields.wake = undefined;
104
+ if (task.fields.control) {
105
+ task.fields.control.lastOutcome = "blocked";
106
+ task.fields.control.blockedReason = reason;
107
+ }
108
+ });
109
+ return document !== undefined;
110
+ }
111
+ export async function dependencyState(channelDir, dependencyIds, ownerId) {
112
+ const detectCycle = async (id, path, active) => {
113
+ if (id === ownerId || active.has(id))
114
+ return `dependency cycle detected (${[...path, id].join(" -> ")})`;
115
+ const dependency = await readStoredTask(channelDir, id, true, true);
116
+ if (!dependency || dependency.fields.status === "done")
117
+ return undefined;
118
+ const nextActive = new Set(active).add(id);
119
+ for (const nestedId of dependency.fields.control?.dependsOn ?? []) {
120
+ const cycle = await detectCycle(nestedId, [...path, id], nextActive);
121
+ if (cycle)
122
+ return cycle;
123
+ }
124
+ return undefined;
125
+ };
126
+ for (const dependencyId of dependencyIds) {
127
+ const cycle = await detectCycle(dependencyId, ownerId ? [ownerId] : [], new Set());
128
+ if (cycle)
129
+ return { ready: false, reason: cycle };
130
+ }
131
+ for (const dependencyId of dependencyIds) {
132
+ const dependency = await readStoredTask(channelDir, dependencyId, true, true);
133
+ if (!dependency)
134
+ return { ready: false, reason: `dependency ${dependencyId} is missing` };
135
+ if (dependency.fields.status === "cancelled" || dependency.fields.status === "escalated") {
136
+ return { ready: false, reason: `dependency ${dependencyId} is ${dependency.fields.status}` };
137
+ }
138
+ if (dependency.fields.status !== "done")
139
+ return { ready: false, reason: `waiting for dependency ${dependencyId}` };
140
+ }
141
+ return { ready: true };
142
+ }
@@ -0,0 +1,23 @@
1
+ export type VerificationVerdict = "pass" | "fail";
2
+ export interface VerificationAttestation {
3
+ version: 1;
4
+ runId: string;
5
+ taskId: string;
6
+ verdict: VerificationVerdict;
7
+ agent: string;
8
+ model: string;
9
+ checkedAt: string;
10
+ bodyHash: string;
11
+ evidence: string;
12
+ outputHash: string;
13
+ workspaceChanged: boolean;
14
+ /** Git HEAD + working-tree subject that the verifier actually inspected. */
15
+ subjectHash?: string;
16
+ }
17
+ export declare function verificationDir(channelDir: string): string;
18
+ export declare function verificationAttestationPath(channelDir: string, runId: string): string;
19
+ export declare function parseVerificationVerdict(output: string): VerificationVerdict | undefined;
20
+ export declare function writeVerificationAttestation(channelDir: string, input: Omit<VerificationAttestation, "version" | "bodyHash" | "outputHash"> & {
21
+ output: string;
22
+ }): Promise<VerificationAttestation>;
23
+ export declare function readVerificationAttestation(channelDir: string, runId: string): Promise<VerificationAttestation>;
@@ -0,0 +1,68 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { readStoredTask, taskBodyHash } from "./store.js";
6
+ function attestationFilename(runId) {
7
+ return `${createHash("sha256").update(runId).digest("hex")}.json`;
8
+ }
9
+ export function verificationDir(channelDir) {
10
+ return join(channelDir, "tasks", ".verifications");
11
+ }
12
+ export function verificationAttestationPath(channelDir, runId) {
13
+ return join(verificationDir(channelDir), attestationFilename(runId));
14
+ }
15
+ export function parseVerificationVerdict(output) {
16
+ const value = /(?:^|\n)VERDICT:\s*(PASS|FAIL)\s*$/i.exec(output.trim())?.[1]?.toLowerCase();
17
+ return value === "pass" || value === "fail" ? value : undefined;
18
+ }
19
+ export async function writeVerificationAttestation(channelDir, input) {
20
+ const task = await readStoredTask(channelDir, input.taskId);
21
+ if (!task)
22
+ throw new Error(`Cannot attest verification: task "${input.taskId}" does not exist.`);
23
+ const attestation = {
24
+ version: 1,
25
+ runId: input.runId,
26
+ taskId: input.taskId,
27
+ verdict: input.verdict,
28
+ agent: input.agent,
29
+ model: input.model,
30
+ checkedAt: input.checkedAt,
31
+ bodyHash: taskBodyHash(task.body),
32
+ evidence: input.evidence,
33
+ outputHash: createHash("sha256").update(input.output).digest("hex"),
34
+ workspaceChanged: input.workspaceChanged,
35
+ subjectHash: input.subjectHash,
36
+ };
37
+ await mkdir(verificationDir(channelDir), { recursive: true });
38
+ await writeFileAtomically(verificationAttestationPath(channelDir, input.runId), `${JSON.stringify(attestation, null, 2)}\n`);
39
+ return attestation;
40
+ }
41
+ export async function readVerificationAttestation(channelDir, runId) {
42
+ let value;
43
+ try {
44
+ value = JSON.parse(await readFile(verificationAttestationPath(channelDir, runId), "utf-8"));
45
+ }
46
+ catch (error) {
47
+ throw new Error(`Verification run "${runId}" was not found or is unreadable. Run a subagent with purpose=verify and taskId first. ${error instanceof Error ? error.message : String(error)}`);
48
+ }
49
+ if (typeof value !== "object" ||
50
+ value === null ||
51
+ value.version !== 1 ||
52
+ value.runId !== runId ||
53
+ typeof value.taskId !== "string" ||
54
+ (value.verdict !== "pass" && value.verdict !== "fail") ||
55
+ typeof value.agent !== "string" ||
56
+ typeof value.model !== "string" ||
57
+ typeof value.checkedAt !== "string" ||
58
+ !Number.isFinite(new Date(value.checkedAt).getTime()) ||
59
+ !/^[a-f0-9]{64}$/i.test(String(value.bodyHash)) ||
60
+ !/^[a-f0-9]{64}$/i.test(String(value.outputHash)) ||
61
+ typeof value.evidence !== "string" ||
62
+ typeof value.workspaceChanged !== "boolean" ||
63
+ (value.subjectHash !== undefined &&
64
+ !/^[a-f0-9]{64}$/i.test(String(value.subjectHash)))) {
65
+ throw new Error(`Verification run "${runId}" has an invalid attestation. Run the verifier again.`);
66
+ }
67
+ return value;
68
+ }
@@ -60,7 +60,7 @@ export interface ToolRegistration {
60
60
  */
61
61
  export declare const TOOL_REGISTRY: ToolRegistration[];
62
62
  /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
63
- export declare const SUBAGENT_TOOL_HINT = "Delegate a focused task to a sub-agent with its own isolated context";
63
+ export declare const SUBAGENT_TOOL_HINT = "Delegate focused work or independent verification; optionally isolate implementation in a task-owned git worktree";
64
64
  /** Single source of truth for prompt hints, keyed by tool name (leaf tools + subagent). */
65
65
  export declare const TOOL_PROMPT_HINTS: Record<string, string>;
66
66
  export interface BuildToolSetOptions {
@@ -136,7 +136,7 @@ export const TOOL_REGISTRY = [
136
136
  name: "event_manage",
137
137
  promptHint: "Schedule your own follow-ups: create/update/delete one-shot check-ins and periodic cadences for this channel. " +
138
138
  "Name task-owned events `task.<channelId>.<taskId>.<use>` (e.g. .checkin, .schedule) so they clean up together. " +
139
- "Keep a task's `wake` and its .checkin one-shot in sync — move both, clear both. " +
139
+ "Task wake/resume is handled natively; use task-owned events mainly for canonical recurring .schedule cadences. " +
140
140
  "No immediate events; periodic no more often than every 30 min (or 5 min when it carries a preAction gate).",
141
141
  availableToSubagents: false,
142
142
  enabledBy: (ctx) => ctx.toolsConfig?.tools.events.enabled !== false,
@@ -149,8 +149,9 @@ export const TOOL_REGISTRY = [
149
149
  },
150
150
  {
151
151
  name: "task_manage",
152
- promptHint: "Update the task ledger: set a task's status/wake/recurrence, close a task out (archives one-shot tasks and " +
153
- "cleans up its residual events), or list active tasks. Write the task body with write/edit; this owns the frontmatter.",
152
+ promptHint: "Manage governed tasks: structured control/budgets/dependencies, atomic progress, candidate verification, verifier attestations, " +
153
+ "verified completion, cancellation, and listing. The native driver resumes ready tasks and escalates hard limits; " +
154
+ "use write/edit only for substantial body changes.",
154
155
  availableToSubagents: false,
155
156
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
156
157
  create: (ctx) => createTaskManageTool({
@@ -158,6 +159,7 @@ export const TOOL_REGISTRY = [
158
159
  workspacePath: ctx.workspacePath,
159
160
  channelDir: ctx.channelDir,
160
161
  channelId: ctx.channelId,
162
+ workingDirectory: ctx.securityContext.cwd,
161
163
  }),
162
164
  },
163
165
  {
@@ -170,7 +172,7 @@ export const TOOL_REGISTRY = [
170
172
  },
171
173
  ];
172
174
  /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
173
- export const SUBAGENT_TOOL_HINT = "Delegate a focused task to a sub-agent with its own isolated context";
175
+ export const SUBAGENT_TOOL_HINT = "Delegate focused work or independent verification; optionally isolate implementation in a task-owned git worktree";
174
176
  /** Single source of truth for prompt hints, keyed by tool name (leaf tools + subagent). */
175
177
  export const TOOL_PROMPT_HINTS = {
176
178
  ...Object.fromEntries(TOOL_REGISTRY.map((registration) => [registration.name, registration.promptHint])),