@linxiraos/pi-messenger 1.1.0 → 1.3.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 (66) hide show
  1. package/CHANGELOG.md +741 -676
  2. package/LICENSE +45 -0
  3. package/README.md +424 -424
  4. package/THIRD-PARTY-NOTICES.txt +22951 -0
  5. package/config-overlay.ts +175 -171
  6. package/config.ts +221 -209
  7. package/crew/agents/crew-plan-sync.md +66 -64
  8. package/crew/agents/crew-planner.md +173 -172
  9. package/crew/agents/crew-reviewer.md +58 -58
  10. package/crew/agents/crew-worker.md +130 -129
  11. package/crew/agents.ts +507 -434
  12. package/crew/handlers/coordination.ts +350 -332
  13. package/crew/handlers/plan.ts +988 -906
  14. package/crew/handlers/review.ts +354 -333
  15. package/crew/handlers/revise.ts +400 -376
  16. package/crew/handlers/status.ts +303 -295
  17. package/crew/handlers/sync.ts +237 -233
  18. package/crew/handlers/task.ts +820 -792
  19. package/crew/handlers/team.ts +294 -235
  20. package/crew/handlers/work.ts +467 -425
  21. package/crew/id-allocator.ts +30 -30
  22. package/crew/index.ts +297 -257
  23. package/crew/live-progress.ts +58 -58
  24. package/crew/lobby.ts +504 -473
  25. package/crew/prompt.ts +262 -252
  26. package/crew/registry.ts +114 -114
  27. package/crew/spawn.ts +135 -111
  28. package/crew/state-autonomous.ts +163 -164
  29. package/crew/state-planning.ts +264 -263
  30. package/crew/state.ts +20 -20
  31. package/crew/store.ts +646 -642
  32. package/crew/task-actions.ts +162 -131
  33. package/crew/team/store.ts +572 -479
  34. package/crew/team/subagent-roles.ts +105 -87
  35. package/crew/team/types.ts +50 -50
  36. package/crew/types.ts +194 -194
  37. package/crew/utils/artifacts.ts +57 -62
  38. package/crew/utils/config.ts +158 -156
  39. package/crew/utils/discover.ts +221 -219
  40. package/crew/utils/install.ts +94 -85
  41. package/crew/utils/migrations.ts +126 -0
  42. package/crew/utils/progress.ts +191 -187
  43. package/crew/utils/result.ts +16 -16
  44. package/crew/utils/risk-labels.ts +5 -7
  45. package/crew/utils/task-format.ts +14 -14
  46. package/crew/utils/team-roles.ts +44 -28
  47. package/crew/utils/truncate.ts +76 -79
  48. package/crew/utils/verdict.ts +55 -55
  49. package/editor-binary.ts +150 -0
  50. package/editor-command.ts +107 -0
  51. package/editor-target.ts +40 -0
  52. package/feed.ts +321 -268
  53. package/handlers.ts +1041 -1107
  54. package/index.ts +1314 -1206
  55. package/install.mjs +187 -189
  56. package/lib.ts +587 -467
  57. package/overlay-actions.ts +519 -511
  58. package/overlay-coordinator.ts +150 -150
  59. package/overlay-render.ts +770 -676
  60. package/overlay.ts +872 -830
  61. package/package.json +64 -60
  62. package/paths.ts +60 -0
  63. package/skills/pi-messenger-crew/SKILL.md +375 -347
  64. package/store.ts +1147 -1139
  65. package/teamagent-command.ts +321 -0
  66. package/vitest.config.ts +10 -10
@@ -1,425 +1,467 @@
1
- /**
2
- * Crew - Work Handler
3
- *
4
- * Spawns workers for ready tasks with concurrency control.
5
- * Simplified: works on current plan's tasks
6
- */
7
-
8
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
9
- import type { Dirs } from "../../lib.ts";
10
- import type { CrewParams, AppendEntryFn } from "../types.ts";
11
- import { result } from "../utils/result.ts";
12
- import { resolveModel, spawnAgents } from "../agents.ts";
13
- import { loadCrewConfig } from "../utils/config.ts";
14
- import { discoverCrewAgents, discoverCrewSkills } from "../utils/discover.ts";
15
- import { buildWorkerPrompt } from "../prompt.ts";
16
- import * as teamStore from "../team/store.ts";
17
- import { reviewImplementation } from "./review.ts";
18
- import * as store from "../store.ts";
19
- import { getCrewDir } from "../store.ts";
20
- import { autonomousState, isAutonomousForCwd, startAutonomous, stopAutonomous, addWaveResult, clampConcurrency } from "../state.ts";
21
- import { getAvailableLobbyWorkers, assignTaskToLobbyWorker, cleanupUnassignedAliveFiles } from "../lobby.ts";
22
- import { logFeedEvent } from "../../feed.ts";
23
- import { approvalTaskSummaries } from "../utils/task-format.ts";
24
-
25
- function revisionHint(taskId: string): string {
26
- return `pi_messenger({ action: "task.revise", id: "${taskId}", prompt: "Address approval feedback" })`;
27
- }
28
-
29
- function rejectedTasksText(tasks: { id: string; title: string; approval?: { feedback?: string } }[]): string {
30
- if (tasks.length === 0) return "";
31
- 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.id)}\``).join("\n")}`;
32
- }
33
-
34
- export async function execute(
35
- params: CrewParams,
36
- dirs: Dirs,
37
- ctx: ExtensionContext,
38
- appendEntry: AppendEntryFn,
39
- signal?: AbortSignal,
40
- sessionModel?: string,
41
- ) {
42
- const cwd = ctx.cwd;
43
- const config = loadCrewConfig(getCrewDir(cwd));
44
- const { autonomous, concurrency: concurrencyOverride } = params;
45
-
46
- // Verify plan exists
47
- const plan = store.getPlan(cwd);
48
- if (!plan) {
49
- return result("No plan found. Create one first:\n\n pi_messenger({ action: \"plan\" })\n pi_messenger({ action: \"plan\", prd: \"path/to/PRD.md\" })", {
50
- mode: "work",
51
- error: "no_plan"
52
- });
53
- }
54
-
55
- // Check for worker agent
56
- const availableAgents = discoverCrewAgents(cwd);
57
- const hasWorker = availableAgents.some(a => a.name === "crew-worker");
58
- if (!hasWorker) {
59
- return result("Error: crew-worker agent not found. Required for task execution.", {
60
- mode: "work",
61
- error: "no_worker"
62
- });
63
- }
64
-
65
- store.autoCompleteMilestones(cwd);
66
- syncCompletedCount(cwd);
67
-
68
- // Get ready tasks — auto-block any that exceeded max attempts
69
- const allReady = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
70
- const readyTasks: typeof allReady = [];
71
- const needsApproval: typeof allReady = [];
72
- const rejected: typeof allReady = [];
73
- for (const task of allReady) {
74
- if (teamStore.taskNeedsRevision(task)) {
75
- rejected.push(task);
76
- } else if (teamStore.taskPendingApproval(task)) {
77
- needsApproval.push(task);
78
- } else if (task.attempt_count >= config.work.maxAttemptsPerTask) {
79
- store.updateTask(cwd, task.id, {
80
- status: "blocked",
81
- blocked_reason: `Max attempts (${config.work.maxAttemptsPerTask}) reached`,
82
- });
83
- store.appendTaskProgress(cwd, task.id, "system",
84
- `Auto-blocked after ${task.attempt_count} attempts (max: ${config.work.maxAttemptsPerTask})`);
85
- logFeedEvent(cwd, "crew", "task.block", task.id, `Max attempts (${config.work.maxAttemptsPerTask}) reached`);
86
- } else {
87
- readyTasks.push(task);
88
- }
89
- }
90
-
91
- if (readyTasks.length === 0) {
92
- const tasks = store.getTasks(cwd);
93
- const inProgress = tasks.filter(t => t.status === "in_progress");
94
- const blocked = tasks.filter(t => t.status === "blocked");
95
- const done = tasks.filter(t => t.status === "done");
96
-
97
- let reason = "";
98
- if (done.length === tasks.length) {
99
- reason = "🎉 All tasks are done! Plan is complete.";
100
- } else if (inProgress.length > 0) {
101
- reason = `${inProgress.length} task(s) in progress: ${inProgress.map(t => t.id).join(", ")}`;
102
- } else if (rejected.length > 0) {
103
- reason = "No startable tasks; rejected tasks need revision.";
104
- } else if (needsApproval.length > 0) {
105
- reason = "No startable tasks; ready tasks need lead approval.";
106
- } else if (blocked.length > 0) {
107
- reason = `${blocked.length} task(s) blocked: ${blocked.map(t => `${t.id} (${t.blocked_reason})`).join(", ")}`;
108
- } else {
109
- reason = "All remaining tasks have unmet dependencies.";
110
- }
111
-
112
- const approvalText = needsApproval.length > 0
113
- ? `\n\nNeeds approval:\n${needsApproval.map(t => ` - ${t.id}: ${t.title}`).join("\n")}`
114
- : "";
115
-
116
- const revisionText = rejectedTasksText(rejected);
117
-
118
- return result(`No ready tasks.\n\n${reason}${approvalText}${revisionText}`, {
119
- mode: "work",
120
- prd: plan.prd,
121
- ready: [],
122
- reason,
123
- needsApproval: approvalTaskSummaries(needsApproval),
124
- rejected: approvalTaskSummaries(rejected),
125
- inProgress: inProgress.map(t => t.id),
126
- blocked: blocked.map(t => t.id)
127
- });
128
- }
129
-
130
- // Determine concurrency
131
- const requestedConcurrency = concurrencyOverride
132
- ?? (autonomous && isAutonomousForCwd(cwd)
133
- ? autonomousState.concurrency
134
- : config.concurrency.workers);
135
- autonomousState.concurrency = clampConcurrency(requestedConcurrency, config.concurrency.max);
136
-
137
- // If autonomous mode, set up state and persist (only on first wave or cwd change)
138
- if (autonomous && !isAutonomousForCwd(cwd)) {
139
- startAutonomous(cwd, autonomousState.concurrency);
140
- appendEntry("crew-state", autonomousState);
141
- }
142
-
143
- const skills = discoverCrewSkills(cwd);
144
-
145
- // Assign tasks to lobby workers first (they're already running and warmed up)
146
- const prdLabel = store.getPlanLabel(plan);
147
- const lobbyAssigned = new Set<string>();
148
- const lobbyWorkers = getAvailableLobbyWorkers(cwd);
149
- for (const lobbyWorker of lobbyWorkers) {
150
- const task = readyTasks.find(t => !lobbyAssigned.has(t.id));
151
- if (!task) break;
152
-
153
- const others = readyTasks.filter(t => t.id !== task.id);
154
- const prompt = buildWorkerPrompt(task, prdLabel, cwd, config, others, skills, teamStore.buildTeamPromptContext(cwd, task));
155
- store.updateTask(cwd, task.id, {
156
- status: "in_progress",
157
- started_at: new Date().toISOString(),
158
- base_commit: store.getBaseCommit(cwd),
159
- assigned_to: lobbyWorker.name,
160
- attempt_count: task.attempt_count + 1,
161
- });
162
- if (!assignTaskToLobbyWorker(lobbyWorker, task.id, prompt, dirs.inbox)) {
163
- store.updateTask(cwd, task.id, { status: "todo", assigned_to: undefined });
164
- continue;
165
- }
166
- store.appendTaskProgress(cwd, task.id, "system", `Assigned to lobby worker ${lobbyWorker.name} (attempt ${task.attempt_count + 1})`);
167
- logFeedEvent(cwd, lobbyWorker.name, "task.start", task.id, task.title);
168
- lobbyAssigned.add(task.id);
169
- }
170
- cleanupUnassignedAliveFiles(cwd);
171
-
172
- // Build prompts for remaining tasks — spawnAgents throttles via autonomousState.concurrency
173
- const remainingTasks = readyTasks.filter(t => !lobbyAssigned.has(t.id));
174
- const teamRoles = teamStore.resolveRoles(cwd);
175
- const workerTasks = remainingTasks.map(task => {
176
- const roleName = teamStore.resolveRoleName(cwd, task.role);
177
- const roleModel = roleName ? teamRoles[roleName]?.model : undefined;
178
- const taskModel = resolveModel(
179
- task.model,
180
- params.model,
181
- roleModel,
182
- config.models?.worker,
183
- sessionModel,
184
- );
185
- const others = readyTasks.filter(t => t.id !== task.id);
186
- const prompt = buildWorkerPrompt(task, prdLabel, cwd, config, others, skills, teamStore.buildTeamPromptContext(cwd, task));
187
- store.appendTaskProgress(cwd, task.id, "system", `Assigned to crew-worker (attempt ${task.attempt_count + 1})`);
188
-
189
- return {
190
- agent: "crew-worker",
191
- task: prompt,
192
- taskId: task.id,
193
- modelOverride: taskModel,
194
- };
195
- });
196
-
197
- const workerResults = await spawnAgents(
198
- workerTasks,
199
- cwd,
200
- {
201
- signal,
202
- messengerDirs: { registry: dirs.registry, inbox: dirs.inbox },
203
- }
204
- );
205
-
206
- // Process results
207
- const succeeded: string[] = [];
208
- const failed: string[] = [];
209
- const blocked: string[] = [];
210
-
211
- for (let i = 0; i < workerResults.length; i++) {
212
- const r = workerResults[i];
213
- const taskId = r.taskId;
214
- if (!taskId) {
215
- failed.push(`unknown-result-${i}`);
216
- continue;
217
- }
218
- const task = store.getTask(cwd, taskId);
219
-
220
- if (r.exitCode === 0) {
221
- if (task?.status === "done") {
222
- succeeded.push(taskId);
223
- } else if (task?.status === "blocked") {
224
- blocked.push(taskId);
225
- } else if (task?.status === "in_progress") {
226
- store.appendTaskProgress(cwd, taskId, "system",
227
- r.wasGracefullyShutdown ? "Task interrupted (shutdown), reset to todo" : "Worker exited without completing task, reset to todo");
228
- store.updateTask(cwd, taskId, { status: "todo", assigned_to: undefined });
229
- failed.push(taskId);
230
- } else {
231
- failed.push(taskId);
232
- }
233
- } else {
234
- if (r.wasGracefullyShutdown) {
235
- if (task?.status === "done") {
236
- succeeded.push(taskId);
237
- } else if (task?.status === "blocked") {
238
- blocked.push(taskId);
239
- } else if (task?.status === "in_progress") {
240
- store.appendTaskProgress(cwd, taskId, "system", "Task interrupted (shutdown), reset to todo");
241
- store.updateTask(cwd, taskId, { status: "todo", assigned_to: undefined });
242
- failed.push(taskId);
243
- } else {
244
- failed.push(taskId);
245
- }
246
- } else if (autonomous && task?.status === "in_progress") {
247
- store.appendTaskProgress(cwd, taskId, "system", `Worker crashed: ${r.error ?? "Unknown error"}`);
248
- store.blockTask(cwd, taskId, `Worker failed: ${r.error ?? "Unknown error"}`);
249
- blocked.push(taskId);
250
- } else {
251
- if (task?.status === "in_progress") {
252
- store.appendTaskProgress(cwd, taskId, "system", `Worker failed: ${r.error ?? "Unknown error"}`);
253
- }
254
- failed.push(taskId);
255
- }
256
- }
257
- }
258
-
259
- // Auto-review succeeded tasks
260
- if (config.review.enabled && succeeded.length > 0) {
261
- const hasReviewer = availableAgents.some(a => a.name === "crew-reviewer");
262
- if (hasReviewer) {
263
- for (const taskId of [...succeeded]) {
264
- if (signal?.aborted) break;
265
- const task = store.getTask(cwd, taskId);
266
- if (!task || !task.base_commit) continue;
267
- if ((task.review_count ?? 0) >= config.review.maxIterations) continue;
268
-
269
- if (task.status === "blocked" || /duplicate/i.test(task.blocked_reason ?? "")) {
270
- if (task.status !== "blocked") {
271
- store.blockTask(cwd, taskId, task.blocked_reason ?? "Duplicate task");
272
- }
273
- succeeded.splice(succeeded.indexOf(taskId), 1);
274
- blocked.push(taskId);
275
- logFeedEvent(cwd, "crew", "task.review", taskId,
276
- `skipped — blocked: ${task.blocked_reason ?? task.status}`);
277
- continue;
278
- }
279
-
280
- const rr = await reviewImplementation(cwd, taskId, config.models?.reviewer ?? sessionModel);
281
- const verdict = rr.details?.verdict as string | undefined;
282
- if (!verdict) {
283
- store.appendTaskProgress(cwd, taskId, "system",
284
- `Auto-review skipped: ${rr.details?.error ?? "unknown"}`);
285
- continue;
286
- }
287
-
288
- const reviewCount = (task.review_count ?? 0) + 1;
289
- store.updateTask(cwd, taskId, { review_count: reviewCount });
290
-
291
- if (verdict === "SHIP") {
292
- logFeedEvent(cwd, "crew", "task.review", taskId, "SHIP");
293
- } else if (verdict === "NEEDS_WORK") {
294
- store.resetTask(cwd, taskId);
295
- logFeedEvent(cwd, "crew", "task.review", taskId, "NEEDS_WORK — reset for retry");
296
- succeeded.splice(succeeded.indexOf(taskId), 1);
297
- failed.push(taskId);
298
- } else {
299
- const lastReview = store.getTask(cwd, taskId)?.last_review;
300
- const summary = lastReview?.summary
301
- ? lastReview.summary.split("\n")[0].slice(0, 120)
302
- : "Major issues found";
303
- store.blockTask(cwd, taskId, `Reviewer: ${summary}`);
304
- logFeedEvent(cwd, "crew", "task.review", taskId, "MAJOR_RETHINK — blocked");
305
- succeeded.splice(succeeded.indexOf(taskId), 1);
306
- blocked.push(taskId);
307
- }
308
- }
309
- }
310
- }
311
-
312
- syncCompletedCount(cwd);
313
-
314
- // Save current wave number BEFORE addWaveResult increments it
315
- const currentWave = autonomous ? autonomousState.waveNumber : 1;
316
-
317
- if (autonomous) {
318
- addWaveResult({
319
- waveNumber: currentWave,
320
- tasksAttempted: remainingTasks.map(t => t.id),
321
- succeeded,
322
- failed,
323
- blocked,
324
- timestamp: new Date().toISOString()
325
- });
326
-
327
- if (signal?.aborted) {
328
- stopAutonomous("manual");
329
- appendEntry("crew-state", autonomousState);
330
- } else {
331
- const nextReady = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" }).filter(t => !teamStore.taskNeedsApproval(t));
332
- const allTasks = store.getTasks(cwd);
333
- const allDone = allTasks.every(t => t.status === "done");
334
- const allBlockedOrDone = allTasks.every(t => t.status === "done" || t.status === "blocked");
335
-
336
- if (allDone) {
337
- stopAutonomous("completed");
338
- appendEntry("crew-state", autonomousState);
339
- appendEntry("crew_wave_complete", {
340
- prd: plan.prd,
341
- status: "completed",
342
- totalWaves: currentWave,
343
- totalTasks: allTasks.length
344
- });
345
- } else if (allBlockedOrDone || nextReady.length === 0) {
346
- stopAutonomous("blocked");
347
- appendEntry("crew-state", autonomousState);
348
- appendEntry("crew_wave_blocked", {
349
- prd: plan.prd,
350
- status: "blocked",
351
- blockedTasks: allTasks.filter(t => t.status === "blocked").map(t => t.id)
352
- });
353
- } else {
354
- appendEntry("crew-state", autonomousState);
355
- appendEntry("crew_wave_continue", {
356
- prd: plan.prd,
357
- nextWave: autonomousState.waveNumber,
358
- readyTasks: nextReady.map(t => t.id)
359
- });
360
- }
361
- }
362
- }
363
-
364
- // Build result
365
- const updatedPlan = store.getPlan(cwd);
366
- const progress = updatedPlan
367
- ? `${updatedPlan.completed_count}/${updatedPlan.task_count}`
368
- : "unknown";
369
-
370
- const nextReady = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
371
- const actionableNextReady = nextReady.filter(t => !teamStore.taskNeedsApproval(t));
372
- const finalNeedsApproval = nextReady.filter(teamStore.taskPendingApproval);
373
- const finalRejected = nextReady.filter(teamStore.taskNeedsRevision);
374
-
375
- let statusText = "";
376
- if (succeeded.length > 0) statusText += `\n✅ Completed: ${succeeded.join(", ")}`;
377
- if (failed.length > 0) statusText += `\n❌ Failed: ${failed.join(", ")}`;
378
- if (blocked.length > 0) statusText += `\n🚫 Blocked: ${blocked.join(", ")}`;
379
- if (finalNeedsApproval.length > 0) statusText += `\n🛑 Needs approval: ${finalNeedsApproval.map(t => t.id).join(", ")}`;
380
- if (finalRejected.length > 0) statusText += `\n↩️ Rejected: ${finalRejected.map(t => t.id).join(", ")}`;
381
- const nextText = actionableNextReady.length > 0
382
- ? `\n\n**Ready for next wave:** ${actionableNextReady.map(t => t.id).join(", ")}`
383
- : "";
384
- const continueText = autonomous && !signal?.aborted && actionableNextReady.length > 0
385
- ? "Autonomous mode: Continuing to next wave..."
386
- : signal?.aborted && autonomous
387
- ? "Autonomous mode stopped (cancelled)."
388
- : "";
389
-
390
- const lobbyText = lobbyAssigned.size > 0
391
- ? `\n🏢 Lobby workers assigned: ${Array.from(lobbyAssigned).join(", ")}`
392
- : "";
393
-
394
- const text = `# Work Wave ${currentWave}
395
-
396
- **PRD:** ${store.getPlanLabel(plan)}
397
- **Tasks attempted:** ${remainingTasks.length}${lobbyAssigned.size > 0 ? ` (+${lobbyAssigned.size} lobby)` : ""}
398
- **Progress:** ${progress}
399
- ${statusText}${lobbyText}${rejectedTasksText(finalRejected)}${nextText}
400
-
401
- ${continueText}`;
402
-
403
- return result(text, {
404
- mode: "work",
405
- prd: plan.prd,
406
- wave: currentWave,
407
- attempted: remainingTasks.map(t => t.id),
408
- succeeded,
409
- failed,
410
- blocked,
411
- needsApproval: approvalTaskSummaries(finalNeedsApproval),
412
- rejected: approvalTaskSummaries(finalRejected),
413
- nextReady: actionableNextReady.map(t => t.id),
414
- autonomous: !!autonomous
415
- });
416
- }
417
-
418
- function syncCompletedCount(cwd: string): void {
419
- const plan = store.getPlan(cwd);
420
- if (!plan) return;
421
- const doneCount = store.getTasks(cwd).filter(t => t.status === "done").length;
422
- if (plan.completed_count !== doneCount) {
423
- store.updatePlan(cwd, { completed_count: doneCount });
424
- }
425
- }
1
+ /**
2
+ * Crew - Work Handler
3
+ *
4
+ * Spawns workers for ready tasks with concurrency control.
5
+ * Simplified: works on current plan's tasks
6
+ */
7
+
8
+ import type { ExtensionContext } from "@linxiraos/zeta";
9
+ import type { Dirs } from "../../lib.ts";
10
+ import type { CrewParams, AppendEntryFn } from "../types.ts";
11
+ import { result } from "../utils/result.ts";
12
+ import { resolveModel, spawnAgents } from "../agents.ts";
13
+ import { loadCrewConfig } from "../utils/config.ts";
14
+ import { discoverCrewAgents, discoverCrewSkills } from "../utils/discover.ts";
15
+ import { buildWorkerPrompt } from "../prompt.ts";
16
+ import * as teamStore from "../team/store.ts";
17
+ import { reviewImplementation } from "./review.ts";
18
+ import {
19
+ autonomousState,
20
+ isAutonomousForCwd,
21
+ startAutonomous,
22
+ stopAutonomous,
23
+ addWaveResult,
24
+ clampConcurrency,
25
+ } from "../state.ts";
26
+ import { getAvailableLobbyWorkers, assignTaskToLobbyWorker, cleanupUnassignedAliveFiles } from "../lobby.ts";
27
+ import { logFeedEvent } from "../../feed.ts";
28
+ import { approvalTaskSummaries } from "../utils/task-format.ts";
29
+ import * as store from "../store.ts";
30
+ import { getCrewDir } from "../store.ts";
31
+
32
+ function revisionHint(taskId: string): string {
33
+ return `pi_messenger({ action: "task.revise", id: "${taskId}", prompt: "Address approval feedback" })`;
34
+ }
35
+
36
+ function rejectedTasksText(tasks: { id: string; title: string; approval?: { feedback?: string } }[]): string {
37
+ if (tasks.length === 0) return "";
38
+ 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.id)}\``).join("\n")}`;
39
+ }
40
+
41
+ export async function execute(
42
+ params: CrewParams,
43
+ dirs: Dirs,
44
+ ctx: ExtensionContext,
45
+ appendEntry: AppendEntryFn,
46
+ signal?: AbortSignal,
47
+ sessionModel?: string,
48
+ ) {
49
+ const cwd = ctx.cwd;
50
+ const config = loadCrewConfig(getCrewDir(cwd));
51
+ const { autonomous, concurrency: concurrencyOverride } = params;
52
+
53
+ // Verify plan exists
54
+ const plan = store.getPlan(cwd);
55
+ if (!plan) {
56
+ return result(
57
+ 'No plan found. Create one first:\n\n pi_messenger({ action: "plan" })\n pi_messenger({ action: "plan", prd: "path/to/PRD.md" })',
58
+ {
59
+ mode: "work",
60
+ error: "no_plan",
61
+ },
62
+ );
63
+ }
64
+
65
+ // Check for worker agent
66
+ const availableAgents = discoverCrewAgents(cwd);
67
+ const hasWorker = availableAgents.some(a => a.name === "crew-worker");
68
+ if (!hasWorker) {
69
+ return result("Error: crew-worker agent not found. Required for task execution.", {
70
+ mode: "work",
71
+ error: "no_worker",
72
+ });
73
+ }
74
+
75
+ store.autoCompleteMilestones(cwd);
76
+ syncCompletedCount(cwd);
77
+
78
+ // Get ready tasks — auto-block any that exceeded max attempts
79
+ const allReady = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
80
+ const readyTasks: typeof allReady = [];
81
+ const needsApproval: typeof allReady = [];
82
+ const rejected: typeof allReady = [];
83
+ for (const task of allReady) {
84
+ if (teamStore.taskNeedsRevision(task)) {
85
+ rejected.push(task);
86
+ } else if (teamStore.taskPendingApproval(task)) {
87
+ needsApproval.push(task);
88
+ } else if (task.attempt_count >= config.work.maxAttemptsPerTask) {
89
+ store.updateTask(cwd, task.id, {
90
+ status: "blocked",
91
+ blocked_reason: `Max attempts (${config.work.maxAttemptsPerTask}) reached`,
92
+ });
93
+ store.appendTaskProgress(
94
+ cwd,
95
+ task.id,
96
+ "system",
97
+ `Auto-blocked after ${task.attempt_count} attempts (max: ${config.work.maxAttemptsPerTask})`,
98
+ );
99
+ logFeedEvent(cwd, "crew", "task.block", task.id, `Max attempts (${config.work.maxAttemptsPerTask}) reached`);
100
+ } else {
101
+ readyTasks.push(task);
102
+ }
103
+ }
104
+
105
+ if (readyTasks.length === 0) {
106
+ const tasks = store.getTasks(cwd);
107
+ const inProgress = tasks.filter(t => t.status === "in_progress");
108
+ const blocked = tasks.filter(t => t.status === "blocked");
109
+ const done = tasks.filter(t => t.status === "done");
110
+
111
+ let reason = "";
112
+ if (done.length === tasks.length) {
113
+ reason = "🎉 All tasks are done! Plan is complete.";
114
+ } else if (inProgress.length > 0) {
115
+ reason = `${inProgress.length} task(s) in progress: ${inProgress.map(t => t.id).join(", ")}`;
116
+ } else if (rejected.length > 0) {
117
+ reason = "No startable tasks; rejected tasks need revision.";
118
+ } else if (needsApproval.length > 0) {
119
+ reason = "No startable tasks; ready tasks need lead approval.";
120
+ } else if (blocked.length > 0) {
121
+ reason = `${blocked.length} task(s) blocked: ${blocked.map(t => `${t.id} (${t.blocked_reason})`).join(", ")}`;
122
+ } else {
123
+ reason = "All remaining tasks have unmet dependencies.";
124
+ }
125
+
126
+ const approvalText =
127
+ needsApproval.length > 0
128
+ ? `\n\nNeeds approval:\n${needsApproval.map(t => ` - ${t.id}: ${t.title}`).join("\n")}`
129
+ : "";
130
+
131
+ const revisionText = rejectedTasksText(rejected);
132
+
133
+ return result(`No ready tasks.\n\n${reason}${approvalText}${revisionText}`, {
134
+ mode: "work",
135
+ prd: plan.prd,
136
+ ready: [],
137
+ reason,
138
+ needsApproval: approvalTaskSummaries(needsApproval),
139
+ rejected: approvalTaskSummaries(rejected),
140
+ inProgress: inProgress.map(t => t.id),
141
+ blocked: blocked.map(t => t.id),
142
+ });
143
+ }
144
+
145
+ // Determine concurrency
146
+ const requestedConcurrency =
147
+ concurrencyOverride ??
148
+ (autonomous && isAutonomousForCwd(cwd) ? autonomousState.concurrency : config.concurrency.workers);
149
+ autonomousState.concurrency = clampConcurrency(requestedConcurrency, config.concurrency.max);
150
+
151
+ // If autonomous mode, set up state and persist (only on first wave or cwd change)
152
+ if (autonomous && !isAutonomousForCwd(cwd)) {
153
+ startAutonomous(cwd, autonomousState.concurrency);
154
+ appendEntry("crew-state", autonomousState);
155
+ }
156
+
157
+ const skills = discoverCrewSkills(cwd);
158
+
159
+ // Assign tasks to lobby workers first (they're already running and warmed up)
160
+ const prdLabel = store.getPlanLabel(plan);
161
+ const lobbyAssigned = new Set<string>();
162
+ const lobbyWorkers = getAvailableLobbyWorkers(cwd);
163
+ for (const lobbyWorker of lobbyWorkers) {
164
+ const task = readyTasks.find(t => !lobbyAssigned.has(t.id));
165
+ if (!task) break;
166
+
167
+ const others = readyTasks.filter(t => t.id !== task.id);
168
+ const prompt = buildWorkerPrompt(
169
+ task,
170
+ prdLabel,
171
+ cwd,
172
+ config,
173
+ others,
174
+ skills,
175
+ teamStore.buildTeamPromptContext(cwd, task),
176
+ );
177
+ store.updateTask(cwd, task.id, {
178
+ status: "in_progress",
179
+ started_at: new Date().toISOString(),
180
+ base_commit: store.getBaseCommit(cwd),
181
+ assigned_to: lobbyWorker.name,
182
+ attempt_count: task.attempt_count + 1,
183
+ });
184
+ if (!assignTaskToLobbyWorker(lobbyWorker, task.id, prompt, dirs.inbox)) {
185
+ store.updateTask(cwd, task.id, { status: "todo", assigned_to: undefined });
186
+ continue;
187
+ }
188
+ store.appendTaskProgress(
189
+ cwd,
190
+ task.id,
191
+ "system",
192
+ `Assigned to lobby worker ${lobbyWorker.name} (attempt ${task.attempt_count + 1})`,
193
+ );
194
+ logFeedEvent(cwd, lobbyWorker.name, "task.start", task.id, task.title);
195
+ lobbyAssigned.add(task.id);
196
+ }
197
+ cleanupUnassignedAliveFiles(cwd);
198
+
199
+ // Build prompts for remaining tasks — spawnAgents throttles via autonomousState.concurrency
200
+ const remainingTasks = readyTasks.filter(t => !lobbyAssigned.has(t.id));
201
+ const teamRoles = teamStore.resolveRoles(cwd);
202
+ const workerTasks = remainingTasks.map(task => {
203
+ const roleName = teamStore.resolveRoleName(cwd, task.role);
204
+ const roleModel = roleName ? teamRoles[roleName]?.model : undefined;
205
+ const taskModel = resolveModel(task.model, params.model, roleModel, config.models?.worker, sessionModel);
206
+ const others = readyTasks.filter(t => t.id !== task.id);
207
+ const prompt = buildWorkerPrompt(
208
+ task,
209
+ prdLabel,
210
+ cwd,
211
+ config,
212
+ others,
213
+ skills,
214
+ teamStore.buildTeamPromptContext(cwd, task),
215
+ );
216
+ store.appendTaskProgress(cwd, task.id, "system", `Assigned to crew-worker (attempt ${task.attempt_count + 1})`);
217
+
218
+ return {
219
+ agent: "crew-worker",
220
+ task: prompt,
221
+ taskId: task.id,
222
+ modelOverride: taskModel,
223
+ };
224
+ });
225
+
226
+ const workerResults = await spawnAgents(workerTasks, cwd, {
227
+ signal,
228
+ messengerDirs: { registry: dirs.registry, inbox: dirs.inbox },
229
+ });
230
+
231
+ // Process results
232
+ const succeeded: string[] = [];
233
+ const failed: string[] = [];
234
+ const blocked: string[] = [];
235
+
236
+ for (let i = 0; i < workerResults.length; i++) {
237
+ const r = workerResults[i];
238
+ const taskId = r.taskId;
239
+ if (!taskId) {
240
+ failed.push(`unknown-result-${i}`);
241
+ continue;
242
+ }
243
+ const task = store.getTask(cwd, taskId);
244
+
245
+ if (r.exitCode === 0) {
246
+ if (task?.status === "done") {
247
+ succeeded.push(taskId);
248
+ } else if (task?.status === "blocked") {
249
+ blocked.push(taskId);
250
+ } else if (task?.status === "in_progress") {
251
+ store.appendTaskProgress(
252
+ cwd,
253
+ taskId,
254
+ "system",
255
+ r.wasGracefullyShutdown
256
+ ? "Task interrupted (shutdown), reset to todo"
257
+ : "Worker exited without completing task, reset to todo",
258
+ );
259
+ store.updateTask(cwd, taskId, { status: "todo", assigned_to: undefined });
260
+ failed.push(taskId);
261
+ } else {
262
+ failed.push(taskId);
263
+ }
264
+ } else {
265
+ if (r.wasGracefullyShutdown) {
266
+ if (task?.status === "done") {
267
+ succeeded.push(taskId);
268
+ } else if (task?.status === "blocked") {
269
+ blocked.push(taskId);
270
+ } else if (task?.status === "in_progress") {
271
+ store.appendTaskProgress(cwd, taskId, "system", "Task interrupted (shutdown), reset to todo");
272
+ store.updateTask(cwd, taskId, { status: "todo", assigned_to: undefined });
273
+ failed.push(taskId);
274
+ } else {
275
+ failed.push(taskId);
276
+ }
277
+ } else if (autonomous && task?.status === "in_progress") {
278
+ store.appendTaskProgress(cwd, taskId, "system", `Worker crashed: ${r.error ?? "Unknown error"}`);
279
+ store.blockTask(cwd, taskId, `Worker failed: ${r.error ?? "Unknown error"}`);
280
+ blocked.push(taskId);
281
+ } else {
282
+ if (task?.status === "in_progress") {
283
+ store.appendTaskProgress(cwd, taskId, "system", `Worker failed: ${r.error ?? "Unknown error"}`);
284
+ }
285
+ failed.push(taskId);
286
+ }
287
+ }
288
+ }
289
+
290
+ // Auto-review succeeded tasks
291
+ if (config.review.enabled && succeeded.length > 0) {
292
+ const hasReviewer = availableAgents.some(a => a.name === "crew-reviewer");
293
+ if (hasReviewer) {
294
+ for (const taskId of [...succeeded]) {
295
+ if (signal?.aborted) break;
296
+ const task = store.getTask(cwd, taskId);
297
+ if (!task || !task.base_commit) continue;
298
+ if ((task.review_count ?? 0) >= config.review.maxIterations) continue;
299
+
300
+ if (task.status === "blocked" || /duplicate/i.test(task.blocked_reason ?? "")) {
301
+ if (task.status !== "blocked") {
302
+ store.blockTask(cwd, taskId, task.blocked_reason ?? "Duplicate task");
303
+ }
304
+ succeeded.splice(succeeded.indexOf(taskId), 1);
305
+ blocked.push(taskId);
306
+ logFeedEvent(
307
+ cwd,
308
+ "crew",
309
+ "task.review",
310
+ taskId,
311
+ `skipped — blocked: ${task.blocked_reason ?? task.status}`,
312
+ );
313
+ continue;
314
+ }
315
+
316
+ const rr = await reviewImplementation(cwd, taskId, config.models?.reviewer ?? sessionModel);
317
+ const verdict = rr.details?.verdict as string | undefined;
318
+ if (!verdict) {
319
+ store.appendTaskProgress(
320
+ cwd,
321
+ taskId,
322
+ "system",
323
+ `Auto-review skipped: ${rr.details?.error ?? "unknown"}`,
324
+ );
325
+ continue;
326
+ }
327
+
328
+ const reviewCount = (task.review_count ?? 0) + 1;
329
+ store.updateTask(cwd, taskId, { review_count: reviewCount });
330
+
331
+ if (verdict === "SHIP") {
332
+ logFeedEvent(cwd, "crew", "task.review", taskId, "SHIP");
333
+ } else if (verdict === "NEEDS_WORK") {
334
+ store.resetTask(cwd, taskId);
335
+ logFeedEvent(cwd, "crew", "task.review", taskId, "NEEDS_WORK — reset for retry");
336
+ succeeded.splice(succeeded.indexOf(taskId), 1);
337
+ failed.push(taskId);
338
+ } else {
339
+ const lastReview = store.getTask(cwd, taskId)?.last_review;
340
+ const summary = lastReview?.summary
341
+ ? lastReview.summary.split("\n")[0].slice(0, 120)
342
+ : "Major issues found";
343
+ store.blockTask(cwd, taskId, `Reviewer: ${summary}`);
344
+ logFeedEvent(cwd, "crew", "task.review", taskId, "MAJOR_RETHINK — blocked");
345
+ succeeded.splice(succeeded.indexOf(taskId), 1);
346
+ blocked.push(taskId);
347
+ }
348
+ }
349
+ }
350
+ }
351
+
352
+ syncCompletedCount(cwd);
353
+
354
+ // Save current wave number BEFORE addWaveResult increments it
355
+ const currentWave = autonomous ? autonomousState.waveNumber : 1;
356
+
357
+ if (autonomous) {
358
+ addWaveResult({
359
+ waveNumber: currentWave,
360
+ tasksAttempted: remainingTasks.map(t => t.id),
361
+ succeeded,
362
+ failed,
363
+ blocked,
364
+ timestamp: new Date().toISOString(),
365
+ });
366
+
367
+ if (signal?.aborted) {
368
+ stopAutonomous("manual");
369
+ appendEntry("crew-state", autonomousState);
370
+ } else {
371
+ const nextReady = store
372
+ .getReadyTasks(cwd, { advisory: config.dependencies === "advisory" })
373
+ .filter(t => !teamStore.taskNeedsApproval(t));
374
+ const allTasks = store.getTasks(cwd);
375
+ const allDone = allTasks.every(t => t.status === "done");
376
+ const allBlockedOrDone = allTasks.every(t => t.status === "done" || t.status === "blocked");
377
+
378
+ if (allDone) {
379
+ stopAutonomous("completed");
380
+ appendEntry("crew-state", autonomousState);
381
+ appendEntry("crew_wave_complete", {
382
+ prd: plan.prd,
383
+ status: "completed",
384
+ totalWaves: currentWave,
385
+ totalTasks: allTasks.length,
386
+ });
387
+ } else if (allBlockedOrDone || nextReady.length === 0) {
388
+ stopAutonomous("blocked");
389
+ appendEntry("crew-state", autonomousState);
390
+ appendEntry("crew_wave_blocked", {
391
+ prd: plan.prd,
392
+ status: "blocked",
393
+ blockedTasks: allTasks.filter(t => t.status === "blocked").map(t => t.id),
394
+ });
395
+ } else {
396
+ appendEntry("crew-state", autonomousState);
397
+ appendEntry("crew_wave_continue", {
398
+ prd: plan.prd,
399
+ nextWave: autonomousState.waveNumber,
400
+ readyTasks: nextReady.map(t => t.id),
401
+ });
402
+ }
403
+ }
404
+ }
405
+
406
+ // Build result
407
+ const updatedPlan = store.getPlan(cwd);
408
+ const progress = updatedPlan ? `${updatedPlan.completed_count}/${updatedPlan.task_count}` : "unknown";
409
+
410
+ const nextReady = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
411
+ const actionableNextReady = nextReady.filter(t => !teamStore.taskNeedsApproval(t));
412
+ const finalNeedsApproval = nextReady.filter(teamStore.taskPendingApproval);
413
+ const finalRejected = nextReady.filter(teamStore.taskNeedsRevision);
414
+
415
+ let statusText = "";
416
+ if (succeeded.length > 0) statusText += `\n✅ Completed: ${succeeded.join(", ")}`;
417
+ if (failed.length > 0) statusText += `\n❌ Failed: ${failed.join(", ")}`;
418
+ if (blocked.length > 0) statusText += `\n🚫 Blocked: ${blocked.join(", ")}`;
419
+ if (finalNeedsApproval.length > 0)
420
+ statusText += `\n🛑 Needs approval: ${finalNeedsApproval.map(t => t.id).join(", ")}`;
421
+ if (finalRejected.length > 0) statusText += `\n↩️ Rejected: ${finalRejected.map(t => t.id).join(", ")}`;
422
+ const nextText =
423
+ actionableNextReady.length > 0
424
+ ? `\n\n**Ready for next wave:** ${actionableNextReady.map(t => t.id).join(", ")}`
425
+ : "";
426
+ const continueText =
427
+ autonomous && !signal?.aborted && actionableNextReady.length > 0
428
+ ? "Autonomous mode: Continuing to next wave..."
429
+ : signal?.aborted && autonomous
430
+ ? "Autonomous mode stopped (cancelled)."
431
+ : "";
432
+
433
+ const lobbyText =
434
+ lobbyAssigned.size > 0 ? `\n🏢 Lobby workers assigned: ${Array.from(lobbyAssigned).join(", ")}` : "";
435
+
436
+ const text = `# Work Wave ${currentWave}
437
+
438
+ **PRD:** ${store.getPlanLabel(plan)}
439
+ **Tasks attempted:** ${remainingTasks.length}${lobbyAssigned.size > 0 ? ` (+${lobbyAssigned.size} lobby)` : ""}
440
+ **Progress:** ${progress}
441
+ ${statusText}${lobbyText}${rejectedTasksText(finalRejected)}${nextText}
442
+
443
+ ${continueText}`;
444
+
445
+ return result(text, {
446
+ mode: "work",
447
+ prd: plan.prd,
448
+ wave: currentWave,
449
+ attempted: remainingTasks.map(t => t.id),
450
+ succeeded,
451
+ failed,
452
+ blocked,
453
+ needsApproval: approvalTaskSummaries(finalNeedsApproval),
454
+ rejected: approvalTaskSummaries(finalRejected),
455
+ nextReady: actionableNextReady.map(t => t.id),
456
+ autonomous: !!autonomous,
457
+ });
458
+ }
459
+
460
+ function syncCompletedCount(cwd: string): void {
461
+ const plan = store.getPlan(cwd);
462
+ if (!plan) return;
463
+ const doneCount = store.getTasks(cwd).filter(t => t.status === "done").length;
464
+ if (plan.completed_count !== doneCount) {
465
+ store.updatePlan(cwd, { completed_count: doneCount });
466
+ }
467
+ }