@linxiraos/pi-messenger 1.1.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 (58) hide show
  1. package/CHANGELOG.md +676 -0
  2. package/README.md +424 -0
  3. package/config-overlay.ts +171 -0
  4. package/config.ts +209 -0
  5. package/crew/agents/crew-plan-sync.md +64 -0
  6. package/crew/agents/crew-planner.md +172 -0
  7. package/crew/agents/crew-reviewer.md +58 -0
  8. package/crew/agents/crew-worker.md +129 -0
  9. package/crew/agents.ts +434 -0
  10. package/crew/handlers/coordination.ts +332 -0
  11. package/crew/handlers/plan.ts +906 -0
  12. package/crew/handlers/review.ts +333 -0
  13. package/crew/handlers/revise.ts +376 -0
  14. package/crew/handlers/status.ts +295 -0
  15. package/crew/handlers/sync.ts +233 -0
  16. package/crew/handlers/task.ts +792 -0
  17. package/crew/handlers/team.ts +235 -0
  18. package/crew/handlers/work.ts +425 -0
  19. package/crew/id-allocator.ts +30 -0
  20. package/crew/index.ts +257 -0
  21. package/crew/live-progress.ts +58 -0
  22. package/crew/lobby.ts +473 -0
  23. package/crew/prompt.ts +252 -0
  24. package/crew/registry.ts +114 -0
  25. package/crew/spawn.ts +111 -0
  26. package/crew/state-autonomous.ts +164 -0
  27. package/crew/state-planning.ts +263 -0
  28. package/crew/state.ts +20 -0
  29. package/crew/store.ts +642 -0
  30. package/crew/task-actions.ts +131 -0
  31. package/crew/team/store.ts +479 -0
  32. package/crew/team/subagent-roles.ts +87 -0
  33. package/crew/team/types.ts +50 -0
  34. package/crew/types.ts +194 -0
  35. package/crew/utils/artifacts.ts +62 -0
  36. package/crew/utils/config.ts +156 -0
  37. package/crew/utils/discover.ts +219 -0
  38. package/crew/utils/install.ts +85 -0
  39. package/crew/utils/progress.ts +187 -0
  40. package/crew/utils/result.ts +16 -0
  41. package/crew/utils/risk-labels.ts +7 -0
  42. package/crew/utils/task-format.ts +14 -0
  43. package/crew/utils/team-roles.ts +28 -0
  44. package/crew/utils/truncate.ts +79 -0
  45. package/crew/utils/verdict.ts +55 -0
  46. package/feed.ts +268 -0
  47. package/handlers.ts +1107 -0
  48. package/index.ts +1206 -0
  49. package/install.mjs +189 -0
  50. package/lib.ts +467 -0
  51. package/overlay-actions.ts +511 -0
  52. package/overlay-coordinator.ts +150 -0
  53. package/overlay-render.ts +676 -0
  54. package/overlay.ts +830 -0
  55. package/package.json +62 -0
  56. package/skills/pi-messenger-crew/SKILL.md +347 -0
  57. package/store.ts +1139 -0
  58. package/vitest.config.ts +10 -0
@@ -0,0 +1,792 @@
1
+ /**
2
+ * Crew - Task Handlers
3
+ *
4
+ * Operations: create, split, show, list, start, done, block, unblock, ready, reset, progress, approve, reject
5
+ * Simplified: tasks belong to the plan, not an epic
6
+ */
7
+
8
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
9
+ import type { MessengerState } from "../../lib.ts";
10
+ import type { CrewParams, Task, TaskEvidence } from "../types.ts";
11
+ import { result } from "../utils/result.ts";
12
+ import { loadCrewConfig } from "../utils/config.ts";
13
+ import * as store from "../store.ts";
14
+ import * as teamStore from "../team/store.ts";
15
+ import { logFeedEvent } from "../../feed.ts";
16
+ import { executeTaskAction } from "../task-actions.ts";
17
+ import { taskRevise, taskReviseTree } from "./revise.ts";
18
+ import { approvalTaskSummaries, taskMetadataMarkers } from "../utils/task-format.ts";
19
+ export { executeRevise, executeReviseTree, type ReviseResult } from "./revise.ts";
20
+
21
+ function revisionHint(task: Task): string {
22
+ return `pi_messenger({ action: "task.revise", id: "${task.id}", prompt: "Address approval feedback" })`;
23
+ }
24
+
25
+ function rejectedTasksText(tasks: Task[]): string {
26
+ if (tasks.length === 0) return "";
27
+ return `\n\nRejected tasks need revision:\n${tasks.map(t => ` - ${t.id}: ${t.title}${t.approval?.feedback ? ` — ${t.approval.feedback}` : ""}\n Revise with: \`${revisionHint(t)}\`\n Or revise dependents too: \`pi_messenger({ action: "task.revise-tree", id: "${t.id}", prompt: "Address approval feedback" })\``).join("\n")}`;
28
+ }
29
+
30
+ export async function execute(
31
+ op: string,
32
+ params: CrewParams,
33
+ state: MessengerState,
34
+ ctx: ExtensionContext
35
+ ) {
36
+ const cwd = ctx.cwd;
37
+
38
+ switch (op) {
39
+ case "create":
40
+ return taskCreate(cwd, params);
41
+ case "split":
42
+ return taskSplit(cwd, params, state);
43
+ case "show":
44
+ return taskShow(cwd, params);
45
+ case "list":
46
+ return taskList(cwd);
47
+ case "start":
48
+ return taskStart(cwd, params, state);
49
+ case "done":
50
+ return taskDone(cwd, params, state);
51
+ case "block":
52
+ return taskBlock(cwd, params, state);
53
+ case "unblock":
54
+ return taskUnblock(cwd, params, state);
55
+ case "ready":
56
+ return taskReady(cwd);
57
+ case "reset":
58
+ return taskReset(cwd, params, state);
59
+ case "progress":
60
+ return taskProgress(cwd, params, state);
61
+ case "approve":
62
+ return taskApproval(cwd, params, state, "approved");
63
+ case "reject":
64
+ return taskApproval(cwd, params, state, "rejected");
65
+ case "revise":
66
+ return taskRevise(cwd, params, state);
67
+ case "revise-tree":
68
+ return taskReviseTree(cwd, params, state);
69
+ default:
70
+ return result(`Unknown task operation: ${op}`, { mode: "task", error: "unknown_operation", operation: op });
71
+ }
72
+ }
73
+
74
+ // =============================================================================
75
+ // task.create
76
+ // =============================================================================
77
+
78
+ function taskActionHint(task: Task): string {
79
+ if (teamStore.taskNeedsRevision(task)) return `Revise first: \`${revisionHint(task)}\``;
80
+ return teamStore.taskNeedsApproval(task)
81
+ ? `Approve first: \`pi_messenger({ action: "task.approve", id: "${task.id}" })\``
82
+ : `Start with: \`pi_messenger({ action: "task.start", id: "${task.id}" })\``;
83
+ }
84
+
85
+ function taskCreate(cwd: string, params: CrewParams) {
86
+ if (!params.title) {
87
+ return result("Error: title required for task.create", { mode: "task.create", error: "missing_title" });
88
+ }
89
+
90
+ // Verify plan exists
91
+ const plan = store.getPlan(cwd);
92
+ if (!plan) {
93
+ return result("Error: No plan exists. Create one first with pi_messenger({ action: \"plan\" })", {
94
+ mode: "task.create", error: "no_plan"
95
+ });
96
+ }
97
+
98
+ // Validate dependencies exist
99
+ if (params.dependsOn && params.dependsOn.length > 0) {
100
+ for (const depId of params.dependsOn) {
101
+ const dep = store.getTask(cwd, depId);
102
+ if (!dep) {
103
+ return result(`Error: Dependency ${depId} not found`, { mode: "task.create", error: "dependency_not_found", dependency: depId });
104
+ }
105
+ }
106
+ }
107
+
108
+ const role = teamStore.canonicalRoleForTask(cwd, params.role);
109
+ if (params.role?.trim() && teamStore.getActiveTeam(cwd) && !role) {
110
+ return result(`Error: unknown Team role: ${params.role.trim()}`, { mode: "task.create", error: "invalid_role", role: params.role.trim() });
111
+ }
112
+
113
+ const riskLabels = teamStore.normalizeRiskLabels(params.riskLabels);
114
+ const approval = params.approval ?? teamStore.approvalForTask(cwd, role, riskLabels);
115
+ const task = store.createTask(cwd, params.title, params.content, params.dependsOn, {
116
+ ...(role ? { role } : {}),
117
+ ...(riskLabels && riskLabels.length > 0 ? { risk_labels: riskLabels } : {}),
118
+ ...(approval ? { approval } : {}),
119
+ });
120
+
121
+ const depsText = task.depends_on.length > 0
122
+ ? `\n**Depends on:** ${task.depends_on.join(", ")}`
123
+ : "";
124
+ const teamText = `${task.role ? `\n**Role:** ${task.role}` : ""}${task.risk_labels?.length ? `\n**Risk labels:** ${task.risk_labels.join(", ")}` : ""}${task.approval?.required ? `\n**Approval:** ${task.approval.status}` : ""}`;
125
+
126
+ const text = `✅ Created task **${task.id}**
127
+
128
+ **Title:** ${task.title}
129
+ **Status:** ${task.status}${depsText}${teamText}
130
+
131
+ ${taskActionHint(task)}`;
132
+
133
+ return result(text, {
134
+ mode: "task.create",
135
+ task: {
136
+ id: task.id,
137
+ title: task.title,
138
+ status: task.status,
139
+ depends_on: task.depends_on,
140
+ role: task.role,
141
+ risk_labels: task.risk_labels,
142
+ approval: task.approval,
143
+ }
144
+ });
145
+ }
146
+
147
+ function taskSplit(cwd: string, params: CrewParams, state: MessengerState) {
148
+ const { id, count, subtasks } = params;
149
+ if (!id) {
150
+ return result("Error: id required for task.split", { mode: "task.split", error: "missing_id" });
151
+ }
152
+
153
+ const task = store.getTask(cwd, id);
154
+ if (!task) {
155
+ return result(`Error: Task ${id} not found`, { mode: "task.split", error: "not_found", id });
156
+ }
157
+
158
+ if (task.status === "done") {
159
+ return result(`Error: Cannot split completed task ${id}`, { mode: "task.split", error: "already_done", id });
160
+ }
161
+
162
+ if (task.milestone) {
163
+ return result(`Error: Cannot split milestone task ${id}`, { mode: "task.split", error: "already_milestone", id });
164
+ }
165
+
166
+ if (!subtasks) {
167
+ const spec = store.getTaskSpec(cwd, id);
168
+ const progress = store.getTaskProgress(cwd, id);
169
+ const suggestedCount = count ?? 2;
170
+ const allTasks = store.getTasks(cwd);
171
+ const dependents = allTasks.filter(t => t.depends_on.includes(id));
172
+ const depsText = task.depends_on.length > 0 ? task.depends_on.join(", ") : "(none)";
173
+ const dependentsText = dependents.length > 0
174
+ ? `${dependents.map(t => t.id).join(", ")} (will be rewired to depend on all subtasks)`
175
+ : "(none)";
176
+ const specText = spec && spec.trim().length > 0 ? spec : "(no spec content)";
177
+ const progressText = progress && progress.trim().length > 0 ? progress : "(no progress entries)";
178
+
179
+ const text = `# Split Task ${task.id}: ${task.title}
180
+
181
+ **Status:** ${task.status}
182
+ **Dependencies:** ${depsText}
183
+ **Dependents:** ${dependentsText}
184
+ **Suggested count:** ${suggestedCount}
185
+
186
+ ## Current Spec
187
+ ${specText}
188
+
189
+ ## Progress
190
+ ${progressText}
191
+
192
+ ---
193
+
194
+ To execute the split, call task.split again with subtask definitions:
195
+
196
+ pi_messenger({
197
+ action: "task.split",
198
+ id: "${task.id}",
199
+ subtasks: [
200
+ { title: "...", content: "..." },
201
+ { title: "...", content: "..." },
202
+ { title: "...", content: "..." }
203
+ ]
204
+ })
205
+
206
+ Each subtask inherits this task's dependencies (${depsText}).
207
+ The parent becomes a milestone that auto-completes when all subtasks are done.`;
208
+
209
+ return result(text, {
210
+ mode: "task.split",
211
+ phase: "inspect",
212
+ task: { id: task.id, title: task.title, status: task.status, depends_on: task.depends_on },
213
+ spec,
214
+ progress,
215
+ suggestedCount,
216
+ dependents: dependents.map(t => t.id),
217
+ });
218
+ }
219
+
220
+ if (subtasks.length < 2) {
221
+ return result("Error: task.split requires at least 2 subtasks", { mode: "task.split", error: "insufficient_subtasks", id });
222
+ }
223
+
224
+ for (const sub of subtasks) {
225
+ if (!sub.title || !sub.title.trim()) {
226
+ return result("Error: each subtask requires a non-empty title", { mode: "task.split", error: "invalid_subtask_title", id });
227
+ }
228
+ }
229
+
230
+ const created: Task[] = [];
231
+ for (const sub of subtasks) {
232
+ const approval: Task["approval"] = task.approval?.required
233
+ ? { required: true, status: task.approval.status === "approved" ? "approved" : "pending" }
234
+ : teamStore.approvalForTask(cwd, task.role, task.risk_labels);
235
+ const newTask = store.createTask(cwd, sub.title, sub.content, [...task.depends_on], {
236
+ ...(task.role ? { role: task.role } : {}),
237
+ ...(task.risk_labels?.length ? { risk_labels: task.risk_labels } : {}),
238
+ ...(approval ? { approval } : {}),
239
+ });
240
+ created.push(newTask);
241
+ }
242
+
243
+ const allTasks = store.getTasks(cwd);
244
+ const subtaskIds = created.map(t => t.id);
245
+ for (const t of allTasks) {
246
+ if (t.id !== id && t.depends_on.includes(id) && !subtaskIds.includes(t.id)) {
247
+ store.updateTask(cwd, t.id, {
248
+ depends_on: [...t.depends_on.filter(d => d !== id), ...subtaskIds],
249
+ });
250
+ }
251
+ }
252
+
253
+ if (task.status === "blocked") {
254
+ store.cleanupBlockFiles(cwd, id);
255
+ }
256
+
257
+ store.updateTask(cwd, id, {
258
+ depends_on: subtaskIds,
259
+ milestone: true,
260
+ status: "todo",
261
+ started_at: undefined,
262
+ completed_at: undefined,
263
+ base_commit: undefined,
264
+ assigned_to: undefined,
265
+ summary: undefined,
266
+ evidence: undefined,
267
+ blocked_reason: undefined,
268
+ role: undefined,
269
+ risk_labels: undefined,
270
+ approval: undefined,
271
+ });
272
+
273
+ store.setTaskSpec(cwd, id, `# ${task.title}\n\nMilestone: completes when ${subtaskIds.join(", ")} are done.\n`);
274
+
275
+ logFeedEvent(cwd, state.agentName || "unknown", "task.split", id,
276
+ `Split into ${created.length} subtasks: ${subtaskIds.join(", ")}`);
277
+
278
+ return result(`Split ${id} into ${created.length} subtasks`, {
279
+ mode: "task.split",
280
+ phase: "execute",
281
+ parent: id,
282
+ subtasks: created.map(t => ({ id: t.id, title: t.title })),
283
+ });
284
+ }
285
+
286
+ // =============================================================================
287
+ // task.show
288
+ // =============================================================================
289
+
290
+ function taskShow(cwd: string, params: CrewParams) {
291
+ const id = params.id;
292
+ if (!id) {
293
+ return result("Error: id required for task.show", { mode: "task.show", error: "missing_id" });
294
+ }
295
+
296
+ const task = store.getTask(cwd, id);
297
+ if (!task) {
298
+ return result(`Error: Task ${id} not found`, { mode: "task.show", error: "not_found", id });
299
+ }
300
+
301
+ const spec = store.getTaskSpec(cwd, id);
302
+
303
+ // Build status details
304
+ let statusDetails = "";
305
+ switch (task.status) {
306
+ case "in_progress":
307
+ statusDetails = `\n**Assigned to:** ${task.assigned_to ?? "unknown"}\n**Started:** ${task.started_at}`;
308
+ if (task.base_commit) statusDetails += `\n**Base commit:** ${task.base_commit.slice(0, 8)}`;
309
+ break;
310
+ case "done":
311
+ statusDetails = `\n**Completed:** ${task.completed_at}`;
312
+ if (task.summary) statusDetails += `\n**Summary:** ${task.summary}`;
313
+ break;
314
+ case "blocked":
315
+ statusDetails = `\n**Blocked reason:** ${task.blocked_reason ?? "unknown"}`;
316
+ break;
317
+ }
318
+
319
+ const depsText = task.depends_on.length > 0
320
+ ? `\n**Depends on:** ${task.depends_on.join(", ")}`
321
+ : "";
322
+
323
+ // Spec preview
324
+ let specPreview = "";
325
+ if (spec && !spec.includes("*Spec pending*")) {
326
+ const truncated = spec.length > 800 ? spec.slice(0, 800) + "..." : spec;
327
+ specPreview = `\n\n## Spec\n\`\`\`\n${truncated}\n\`\`\``;
328
+ }
329
+ const progress = store.getTaskProgress(cwd, id);
330
+ let progressSection = "";
331
+ if (progress) {
332
+ const lines = progress.trimEnd().split("\n");
333
+ const recent = lines.length > 20 ? lines.slice(-20) : lines;
334
+ const omitted = lines.length > 20 ? `(${lines.length - 20} earlier entries omitted)\n` : "";
335
+ const preview = omitted + recent.join("\n");
336
+ progressSection = `\n\n## Progress\n\`\`\`\n${preview}\n\`\`\``;
337
+ }
338
+
339
+ const statusIcon = {
340
+ todo: "⬜",
341
+ in_progress: "🔄",
342
+ done: "✅",
343
+ blocked: "🚫",
344
+ }[task.status];
345
+
346
+ const text = `# Task ${task.id}: ${task.title}
347
+
348
+ ${statusIcon} **Status:** ${task.status}${statusDetails}
349
+ **Attempts:** ${task.attempt_count}${taskMetadataMarkers(task)}${depsText}${progressSection}${specPreview}`;
350
+
351
+ return result(text, {
352
+ mode: "task.show",
353
+ task,
354
+ hasSpec: spec && !spec.includes("*Spec pending*"),
355
+ });
356
+ }
357
+
358
+ function taskProgress(cwd: string, params: CrewParams, state: MessengerState) {
359
+ const { id, message } = params;
360
+ if (!id) return result("Error: id required for task.progress", { mode: "task.progress", error: "missing_id" });
361
+ if (!message) return result("Error: message required for task.progress", { mode: "task.progress", error: "missing_message" });
362
+
363
+ const task = store.getTask(cwd, id);
364
+ if (!task) return result(`Error: Task ${id} not found`, { mode: "task.progress", error: "not_found", id });
365
+
366
+ store.appendTaskProgress(cwd, id, state.agentName || "unknown", message);
367
+ return result(`Progress logged for ${id}`, { mode: "task.progress", id });
368
+ }
369
+
370
+ // =============================================================================
371
+ // task.list
372
+ // =============================================================================
373
+
374
+ function taskList(cwd: string) {
375
+ const plan = store.getPlan(cwd);
376
+ if (!plan) {
377
+ return result("No plan found. Create one with: pi_messenger({ action: \"plan\" })", {
378
+ mode: "task.list", tasks: [], hasPlan: false
379
+ });
380
+ }
381
+
382
+ const tasks = store.getTasks(cwd);
383
+ if (tasks.length === 0) {
384
+ return result(`No tasks in plan. Create with: \`pi_messenger({ action: "task.create", title: "..." })\``, {
385
+ mode: "task.list",
386
+ tasks: [],
387
+ prd: plan.prd,
388
+ });
389
+ }
390
+
391
+ const lines: string[] = [`# Tasks for ${store.getPlanLabel(plan)}\n`];
392
+
393
+ for (const task of tasks) {
394
+ const icon = { todo: "⬜", in_progress: "🔄", done: "✅", blocked: "🚫" }[task.status];
395
+ const deps = task.depends_on.length > 0 ? ` → deps: ${task.depends_on.join(", ")}` : "";
396
+ const assignee = task.assigned_to ? ` [${task.assigned_to}]` : "";
397
+ lines.push(`${icon} **${task.id}**: ${task.title}${taskMetadataMarkers(task)}${assignee}${deps}`);
398
+ }
399
+
400
+ const done = tasks.filter(t => t.status === "done").length;
401
+ lines.push(`\n**Progress:** ${done}/${tasks.length}`);
402
+
403
+ return result(lines.join("\n"), {
404
+ mode: "task.list",
405
+ prd: plan.prd,
406
+ tasks: tasks.map(t => ({
407
+ id: t.id,
408
+ title: t.title,
409
+ status: t.status,
410
+ depends_on: t.depends_on,
411
+ role: t.role,
412
+ risk_labels: t.risk_labels,
413
+ approval: t.approval,
414
+ })),
415
+ });
416
+ }
417
+
418
+ // =============================================================================
419
+ // task.start
420
+ // =============================================================================
421
+
422
+ function taskStart(cwd: string, params: CrewParams, state: MessengerState) {
423
+ const id = params.id;
424
+ if (!id) {
425
+ return result("Error: id required for task.start", { mode: "task.start", error: "missing_id" });
426
+ }
427
+
428
+ const task = store.getTask(cwd, id);
429
+ if (task && teamStore.taskNeedsApproval(task)) {
430
+ const message = teamStore.taskNeedsRevision(task)
431
+ ? `Error: Task ${id} was rejected and needs revision before it can be started.`
432
+ : `Error: Task ${id} needs lead approval before it can be started.`;
433
+ return result(message, {
434
+ mode: "task.start",
435
+ error: teamStore.taskNeedsRevision(task) ? "needs_revision" : "needs_approval",
436
+ id,
437
+ approval: task.approval,
438
+ });
439
+ }
440
+
441
+ const agentName = state.agentName || "unknown";
442
+ const actionResult = executeTaskAction(cwd, "start", id, agentName);
443
+ if (!actionResult.success || !actionResult.task) {
444
+ return result(`Error: ${actionResult.message}`, {
445
+ mode: "task.start",
446
+ error: actionResult.error ?? "start_failed",
447
+ id,
448
+ unmetDependencies: actionResult.unmetDependencies,
449
+ });
450
+ }
451
+
452
+ const started = actionResult.task;
453
+ const spec = store.getTaskSpec(cwd, id);
454
+ const specPreview = spec && !spec.includes("*Spec pending*")
455
+ ? `\n\n**Spec:**\n\`\`\`\n${spec.length > 1000 ? spec.slice(0, 1000) + "..." : spec}\n\`\`\``
456
+ : "";
457
+
458
+ const text = `🔄 Started task **${id}**
459
+
460
+ **Title:** ${started.title}
461
+ **Assigned to:** ${agentName}
462
+ **Attempt:** ${started.attempt_count}
463
+ ${started.base_commit ? `**Base commit:** ${started.base_commit.slice(0, 8)}` : ""}${specPreview}
464
+
465
+ When done: \`pi_messenger({ action: "task.done", id: "${id}", summary: "..." })\`
466
+ If blocked: \`pi_messenger({ action: "task.block", id: "${id}", reason: "..." })\``;
467
+
468
+ return result(text, {
469
+ mode: "task.start",
470
+ task: {
471
+ id: started.id,
472
+ title: started.title,
473
+ status: started.status,
474
+ assigned_to: started.assigned_to,
475
+ attempt_count: started.attempt_count,
476
+ base_commit: started.base_commit,
477
+ }
478
+ });
479
+ }
480
+
481
+ // =============================================================================
482
+ // task.done
483
+ // =============================================================================
484
+
485
+ function taskDone(cwd: string, params: CrewParams, state: MessengerState) {
486
+ const id = params.id;
487
+ if (!id) {
488
+ return result("Error: id required for task.done", { mode: "task.done", error: "missing_id" });
489
+ }
490
+
491
+ const task = store.getTask(cwd, id);
492
+ if (!task) {
493
+ return result(`Error: Task ${id} not found`, { mode: "task.done", error: "not_found", id });
494
+ }
495
+
496
+ if (task.status !== "in_progress") {
497
+ return result(`Error: Task ${id} is ${task.status}, not in_progress`, {
498
+ mode: "task.done", error: "invalid_status", id, status: task.status
499
+ });
500
+ }
501
+
502
+ const summary = params.summary ?? "Task completed";
503
+ const evidence: TaskEvidence | undefined = params.evidence;
504
+
505
+ const completed = store.completeTask(cwd, id, summary, evidence);
506
+ if (!completed) {
507
+ return result(`Error: Failed to complete task ${id}`, { mode: "task.done", error: "complete_failed", id });
508
+ }
509
+
510
+ logFeedEvent(cwd, state.agentName || "unknown", "task.done", id, summary);
511
+
512
+ const plan = store.getPlan(cwd);
513
+ const tasks = store.getTasks(cwd);
514
+ const remaining = tasks.filter(t => t.status !== "done");
515
+
516
+ let nextSteps = "";
517
+ if (remaining.length === 0) {
518
+ nextSteps = `\n\n🎉 **All tasks complete!** Plan is finished.`;
519
+ } else {
520
+ const config = loadCrewConfig(store.getCrewDir(cwd));
521
+ const ready = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
522
+ const actionable = ready.filter(t => !teamStore.taskNeedsApproval(t));
523
+ const rejected = ready.filter(teamStore.taskNeedsRevision);
524
+ const needsApproval = ready.filter(t => teamStore.taskPendingApproval(t));
525
+ if (actionable.length > 0) {
526
+ nextSteps = `\n\n**Ready tasks:** ${actionable.map(t => t.id).join(", ")}`;
527
+ }
528
+ if (needsApproval.length > 0) {
529
+ nextSteps += `\n\n**Needs approval:** ${needsApproval.map(t => t.id).join(", ")}`;
530
+ }
531
+ nextSteps += rejectedTasksText(rejected);
532
+ }
533
+
534
+ const text = `✅ Completed task **${id}**
535
+
536
+ **Summary:** ${summary}
537
+ **Progress:** ${plan?.completed_count}/${plan?.task_count}${nextSteps}`;
538
+
539
+ return result(text, {
540
+ mode: "task.done",
541
+ task: {
542
+ id: completed.id,
543
+ title: completed.title,
544
+ status: completed.status,
545
+ summary: completed.summary,
546
+ },
547
+ progress: {
548
+ completed: plan?.completed_count ?? 0,
549
+ total: plan?.task_count ?? 0,
550
+ }
551
+ });
552
+ }
553
+
554
+ // =============================================================================
555
+ // task.block
556
+ // =============================================================================
557
+
558
+ function taskBlock(cwd: string, params: CrewParams, state: MessengerState) {
559
+ const id = params.id;
560
+ if (!id) {
561
+ return result("Error: id required for task.block", { mode: "task.block", error: "missing_id" });
562
+ }
563
+
564
+ if (!params.reason) {
565
+ return result("Error: reason required for task.block", { mode: "task.block", error: "missing_reason" });
566
+ }
567
+
568
+ const actionResult = executeTaskAction(cwd, "block", id, state.agentName || "unknown", params.reason);
569
+ if (!actionResult.success || !actionResult.task) {
570
+ return result(`Error: ${actionResult.message}`, {
571
+ mode: "task.block",
572
+ error: actionResult.error ?? "block_failed",
573
+ id,
574
+ });
575
+ }
576
+
577
+ const blocked = actionResult.task;
578
+ const text = `🚫 Blocked task **${id}**
579
+
580
+ **Reason:** ${params.reason}
581
+
582
+ Unblock with: \`pi_messenger({ action: "task.unblock", id: "${id}" })\``;
583
+
584
+ return result(text, {
585
+ mode: "task.block",
586
+ task: {
587
+ id: blocked.id,
588
+ title: blocked.title,
589
+ status: blocked.status,
590
+ blocked_reason: blocked.blocked_reason,
591
+ }
592
+ });
593
+ }
594
+
595
+ // =============================================================================
596
+ // task.unblock
597
+ // =============================================================================
598
+
599
+ function taskUnblock(cwd: string, params: CrewParams, state: MessengerState) {
600
+ const id = params.id;
601
+ if (!id) {
602
+ return result("Error: id required for task.unblock", { mode: "task.unblock", error: "missing_id" });
603
+ }
604
+
605
+ const actionResult = executeTaskAction(cwd, "unblock", id, state.agentName || "unknown");
606
+ if (!actionResult.success || !actionResult.task) {
607
+ return result(`Error: ${actionResult.message}`, {
608
+ mode: "task.unblock",
609
+ error: actionResult.error ?? "unblock_failed",
610
+ id,
611
+ });
612
+ }
613
+
614
+ const unblocked = actionResult.task;
615
+ const text = `⬜ Unblocked task **${id}**\n\n${taskActionHint(unblocked)}`;
616
+
617
+ return result(text, {
618
+ mode: "task.unblock",
619
+ task: {
620
+ id: unblocked.id,
621
+ title: unblocked.title,
622
+ status: unblocked.status,
623
+ }
624
+ });
625
+ }
626
+
627
+ // =============================================================================
628
+ // task.ready
629
+ // =============================================================================
630
+
631
+ function taskReady(cwd: string) {
632
+ const plan = store.getPlan(cwd);
633
+ if (!plan) {
634
+ return result("No plan found. Create one with: pi_messenger({ action: \"plan\" })", {
635
+ mode: "task.ready", ready: [], hasPlan: false
636
+ });
637
+ }
638
+
639
+ const config = loadCrewConfig(store.getCrewDir(cwd));
640
+ const allReady = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
641
+ const ready: typeof allReady = [];
642
+ const needsApproval: typeof allReady = [];
643
+ const rejected: typeof allReady = [];
644
+ for (const task of allReady) {
645
+ if (teamStore.taskNeedsRevision(task)) rejected.push(task);
646
+ else if (teamStore.taskPendingApproval(task)) needsApproval.push(task);
647
+ else ready.push(task);
648
+ }
649
+
650
+ if (ready.length === 0) {
651
+ const tasks = store.getTasks(cwd);
652
+ const inProgress = tasks.filter(t => t.status === "in_progress");
653
+ const blocked = tasks.filter(t => t.status === "blocked");
654
+ const done = tasks.filter(t => t.status === "done");
655
+
656
+ let reason = "";
657
+ if (done.length === tasks.length) {
658
+ reason = "All tasks are done!";
659
+ } else if (inProgress.length > 0) {
660
+ reason = `${inProgress.length} task(s) in progress: ${inProgress.map(t => t.id).join(", ")}`;
661
+ } else if (rejected.length > 0) {
662
+ reason = "No startable tasks; rejected tasks need revision.";
663
+ } else if (needsApproval.length > 0) {
664
+ reason = "No startable tasks; ready tasks need lead approval.";
665
+ } else if (blocked.length > 0) {
666
+ reason = `${blocked.length} task(s) blocked: ${blocked.map(t => t.id).join(", ")}`;
667
+ } else {
668
+ reason = "All remaining tasks have unmet dependencies.";
669
+ }
670
+
671
+ const approvalText = needsApproval.length > 0
672
+ ? `\n\nNeeds approval:\n${needsApproval.map(t => ` - ${t.id}: ${t.title}`).join("\n")}`
673
+ : "";
674
+ const revisionText = rejectedTasksText(rejected);
675
+ return result(`No ready tasks.\n\n${reason}${approvalText}${revisionText}`, {
676
+ mode: "task.ready",
677
+ ready: [],
678
+ needsApproval: approvalTaskSummaries(needsApproval),
679
+ rejected: approvalTaskSummaries(rejected),
680
+ reason,
681
+ });
682
+ }
683
+
684
+ const lines: string[] = [`# Ready Tasks\n`];
685
+ for (const task of ready) {
686
+ lines.push(`⬜ **${task.id}**: ${task.title}`);
687
+ }
688
+ lines.push(`\nStart one: \`pi_messenger({ action: "task.start", id: "${ready[0].id}" })\``);
689
+ lines.push(`Or run all: \`pi_messenger({ action: "work" })\``);
690
+
691
+ if (needsApproval.length > 0) {
692
+ lines.push(`\nNeeds approval:\n${needsApproval.map(t => ` - ${t.id}: ${t.title}`).join("\n")}`);
693
+ }
694
+ const revisionText = rejectedTasksText(rejected);
695
+ if (revisionText) lines.push(revisionText);
696
+
697
+ return result(lines.join("\n"), {
698
+ mode: "task.ready",
699
+ ready: ready.map(t => ({
700
+ id: t.id,
701
+ title: t.title,
702
+ })),
703
+ needsApproval: approvalTaskSummaries(needsApproval),
704
+ rejected: approvalTaskSummaries(rejected),
705
+ });
706
+ }
707
+
708
+ // =============================================================================
709
+ // task.approve / task.reject
710
+ // =============================================================================
711
+
712
+ function taskApproval(cwd: string, params: CrewParams, state: MessengerState, status: "approved" | "rejected") {
713
+ const id = params.id;
714
+ const action = status === "approved" ? "approve" : "reject";
715
+ const mode = `task.${action}`;
716
+ const actor = state.agentName || "unknown";
717
+
718
+ if (!id) {
719
+ return result(`Error: id required for ${mode}`, { mode, error: "missing_id" });
720
+ }
721
+
722
+ const task = store.getTask(cwd, id);
723
+ if (!task) {
724
+ return result(`Error: Task ${id} not found`, { mode, error: "not_found", id });
725
+ }
726
+ if (!task.approval?.required) {
727
+ return result(`Task ${id} does not require approval.`, { mode, error: "approval_not_required", id });
728
+ }
729
+ if (task.status === "in_progress" || task.status === "done") {
730
+ return result(`Error: Task ${id} is ${task.status}; approval can only change before work starts.`, {
731
+ mode,
732
+ error: "invalid_status",
733
+ id,
734
+ status: task.status,
735
+ });
736
+ }
737
+
738
+ const approval = {
739
+ ...task.approval,
740
+ status,
741
+ feedback: params.reason,
742
+ decided_by: actor,
743
+ decided_at: new Date().toISOString(),
744
+ };
745
+ const updated = store.updateTask(cwd, id, { approval });
746
+ logFeedEvent(cwd, actor, status === "approved" ? "task.approve" : "task.reject", id, params.reason);
747
+
748
+ const nextStep = status === "rejected"
749
+ ? `\n\nNext: revise with \`${revisionHint(task)}\`, or use \`pi_messenger({ action: "task.revise-tree", id: "${id}", prompt: "Address approval feedback" })\` if dependents need updates too.`
750
+ : "";
751
+
752
+ return result(`${status === "approved" ? "Approved" : "Rejected"} task **${id}**.${nextStep}`, {
753
+ mode,
754
+ task: updated ? { id: updated.id, title: updated.title, approval: updated.approval } : undefined,
755
+ });
756
+ }
757
+
758
+ // =============================================================================
759
+ // task.reset
760
+ // =============================================================================
761
+
762
+ function taskReset(cwd: string, params: CrewParams, state: MessengerState) {
763
+ const id = params.id;
764
+ if (!id) {
765
+ return result("Error: id required for task.reset", { mode: "task.reset", error: "missing_id" });
766
+ }
767
+
768
+ const cascade = params.cascade ?? false;
769
+ const action = cascade ? "cascade-reset" : "reset";
770
+ const actionResult = executeTaskAction(cwd, action, id, state.agentName || "unknown");
771
+ if (!actionResult.success) {
772
+ return result(`Error: ${actionResult.message}`, {
773
+ mode: "task.reset",
774
+ error: actionResult.error ?? "reset_failed",
775
+ id,
776
+ });
777
+ }
778
+
779
+ const resetTasks = actionResult.resetTasks ?? [];
780
+ const text = cascade && resetTasks.length > 1
781
+ ? `🔄 Reset ${resetTasks.length} tasks:\n${resetTasks.map(t => ` - ${t.id}`).join("\n")}`
782
+ : `🔄 Reset task **${id}**`;
783
+
784
+ const resetTask = store.getTask(cwd, id);
785
+ const hint = resetTask ? taskActionHint(resetTask) : `Start with: \`pi_messenger({ action: "task.start", id: "${id}" })\``;
786
+
787
+ return result(`${text}\n\n${hint}`, {
788
+ mode: "task.reset",
789
+ reset: resetTasks.map(t => t.id),
790
+ cascade,
791
+ });
792
+ }