@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,235 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { MessengerState } from "../../lib.ts";
3
+ import type { CrewParams } from "../types.ts";
4
+ import { result } from "../utils/result.ts";
5
+ import * as crewStore from "../store.ts";
6
+ import * as teamStore from "../team/store.ts";
7
+ import { TEAM_MEMORY_TYPES, type TeamMemoryType, type TeamProfile } from "../team/types.ts";
8
+
9
+ export async function execute(op: string, params: CrewParams, state: MessengerState, ctx: ExtensionContext) {
10
+ const cwd = ctx.cwd;
11
+
12
+ switch (op) {
13
+ case "setup":
14
+ return setup(cwd, params);
15
+ case "profile.list":
16
+ return profileList();
17
+ case "profile.use":
18
+ return profileUse(cwd, params);
19
+ case "profile.save":
20
+ return profileSave(cwd, params);
21
+ case "charter.show":
22
+ return charterShow(cwd);
23
+ case "charter.create":
24
+ return charterCreate(cwd, params);
25
+ case "charter.update":
26
+ return charterUpdate(cwd, params);
27
+ case "memory.note":
28
+ return memoryNote(cwd, params, state);
29
+ case "memory.list":
30
+ return memoryList(cwd, params);
31
+ case "roles":
32
+ return roles(cwd);
33
+ case "status":
34
+ return status(cwd);
35
+ default:
36
+ return result(`Unknown team operation: ${op}`, { mode: "team", error: "unknown_operation", operation: op });
37
+ }
38
+ }
39
+
40
+ function memoryType(value: unknown): TeamMemoryType | null {
41
+ return typeof value === "string" && TEAM_MEMORY_TYPES.includes(value as TeamMemoryType) ? value as TeamMemoryType : null;
42
+ }
43
+
44
+ function starterCharter(profile: TeamProfile): string {
45
+ const roles = Object.keys(profile.roles ?? {}).sort();
46
+ const approval = profile.approval?.mode === "off"
47
+ ? "No approval gates are configured for this profile."
48
+ : `High-risk editing tasks need lead approval for: ${(profile.approval?.labels ?? ["security", "database", "api-contract", "destructive", "migration", "auth", "payment"]).join(", ")}.`;
49
+ return [
50
+ `Use the ${profile.name} Team profile for this project.`,
51
+ profile.description ? `Profile intent: ${profile.description}.` : null,
52
+ roles.length > 0 ? `Planner may assign these roles: ${roles.join(", ")}.` : null,
53
+ approval,
54
+ "Keep Team memory current with decisions, interface notes, risks, and handoffs.",
55
+ ].filter(Boolean).join("\n\n");
56
+ }
57
+
58
+ function setup(cwd: string, params: CrewParams) {
59
+ const name = params.name ?? "migration-squad";
60
+ if (!teamStore.isValidProfileName(name)) {
61
+ return result("Error: invalid team profile name. Use letters, numbers, underscore, or hyphen.", { mode: "team.setup", error: "invalid_name" });
62
+ }
63
+
64
+ const { team, profile, created } = teamStore.useProfile(cwd, name);
65
+ const existingCharter = teamStore.readCharter(cwd);
66
+ const customCharter = typeof params.message === "string" && params.message.trim().length > 0 ? params.message : undefined;
67
+ const charter = customCharter || !existingCharter
68
+ ? teamStore.writeCharter(cwd, profile.name, customCharter ?? starterCharter(profile))
69
+ : existingCharter;
70
+ const charterStatus = customCharter ? "updated" : existingCharter ? "kept" : "created";
71
+
72
+ const text = `Set up Team profile **${profile.name}**.
73
+
74
+ Profile: ${created ? "created editable JSON" : "activated"}
75
+ Charter: ${charterStatus}
76
+
77
+ Next:
78
+ - Plan with this Team context: \`pi_messenger({ action: "plan", prompt: "..." })\`
79
+ - Check Team status: \`pi_messenger({ action: "team.status" })\`
80
+ - Approve gated work with \`task.approve\`; reject with \`task.reject\` and feedback.`;
81
+
82
+ return result(text, {
83
+ mode: "team.setup",
84
+ team,
85
+ profile,
86
+ created,
87
+ charter,
88
+ charterStatus,
89
+ });
90
+ }
91
+
92
+ function profileList() {
93
+ const profiles = teamStore.listProfiles();
94
+ const text = `# Team Profiles\n\n${profiles.map(p => `- ${p.name}${p.description ? ` — ${p.description}` : ""}`).join("\n")}`;
95
+ return result(text, { mode: "team.profile.list", profiles });
96
+ }
97
+
98
+ function profileUse(cwd: string, params: CrewParams) {
99
+ if (!params.name) return result("Error: name required for team.profile.use", { mode: "team.profile.use", error: "missing_name" });
100
+ if (!teamStore.isValidProfileName(params.name)) {
101
+ return result("Error: invalid team profile name. Use letters, numbers, underscore, or hyphen.", { mode: "team.profile.use", error: "invalid_name" });
102
+ }
103
+ const { team, profile, created } = teamStore.useProfile(cwd, params.name);
104
+ const action = created ? "Created and activated" : "Activated";
105
+ return result(`${action} team profile **${profile.name}**.`, {
106
+ mode: "team.profile.use",
107
+ team,
108
+ profile,
109
+ created,
110
+ });
111
+ }
112
+
113
+ function profileSave(cwd: string, params: CrewParams) {
114
+ if (!params.name) return result("Error: name required for team.profile.save", { mode: "team.profile.save", error: "missing_name" });
115
+ if (!teamStore.isValidProfileName(params.name)) {
116
+ return result("Error: invalid team profile name. Use letters, numbers, underscore, or hyphen.", { mode: "team.profile.save", error: "invalid_name" });
117
+ }
118
+ const active = teamStore.getActiveTeam(cwd);
119
+ const activeProfile = teamStore.loadActiveProfile(cwd);
120
+ const profile: TeamProfile = {
121
+ ...(activeProfile ?? teamStore.defaultTeamProfile(params.name)),
122
+ name: params.name,
123
+ };
124
+ teamStore.saveProfile(profile);
125
+ const team = teamStore.setActiveTeam(cwd, active?.name ?? params.name, profile.name);
126
+ return result(`Saved team profile **${profile.name}**.`, { mode: "team.profile.save", team, profile });
127
+ }
128
+
129
+ function charterShow(cwd: string) {
130
+ const charter = teamStore.readCharter(cwd);
131
+ if (!charter) {
132
+ return result("No team charter found. Create one with `team.charter.create`.", {
133
+ mode: "team.charter.show",
134
+ charter: null,
135
+ exists: false,
136
+ });
137
+ }
138
+ return result(charter, {
139
+ mode: "team.charter.show",
140
+ charter,
141
+ exists: true,
142
+ });
143
+ }
144
+
145
+ function charterCreate(cwd: string, params: CrewParams) {
146
+ if (!params.name) return result("Error: name required for team.charter.create", { mode: "team.charter.create", error: "missing_name" });
147
+ if (!params.message) return result("Error: message required for team.charter.create", { mode: "team.charter.create", error: "missing_message" });
148
+ const charter = teamStore.writeCharter(cwd, params.name, params.message);
149
+ return result(`Created charter for **${params.name}**.`, { mode: "team.charter.create", charter, team: teamStore.getActiveTeam(cwd) });
150
+ }
151
+
152
+ function charterUpdate(cwd: string, params: CrewParams) {
153
+ if (!params.message) return result("Error: message required for team.charter.update", { mode: "team.charter.update", error: "missing_message" });
154
+ const charter = teamStore.updateCharter(cwd, params.message);
155
+ return result("Updated team charter.", { mode: "team.charter.update", charter, team: teamStore.getActiveTeam(cwd) });
156
+ }
157
+
158
+ function memoryNote(cwd: string, params: CrewParams, state: MessengerState) {
159
+ const type = memoryType(params.type);
160
+ if (!type) return result("Error: type must be one of decision, interface, risk, or handoff", { mode: "team.memory.note", error: "invalid_type" });
161
+ if (!params.message) return result("Error: message required for team.memory.note", { mode: "team.memory.note", error: "missing_message" });
162
+ const entry = teamStore.noteMemory(cwd, type, params.message, state.agentName || "unknown", params.id);
163
+ return result(`Saved team ${type} note.`, { mode: "team.memory.note", entry });
164
+ }
165
+
166
+ function memoryList(cwd: string, params: CrewParams) {
167
+ const type = params.type ? memoryType(params.type) : null;
168
+ if (params.type && !type) return result("Error: type must be one of decision, interface, risk, or handoff", { mode: "team.memory.list", error: "invalid_type" });
169
+ const entries = teamStore.listMemory(cwd, type ?? undefined, params.limit);
170
+ const text = entries.length > 0
171
+ ? entries.map(entry => `- ${entry.ts} [${entry.type}] ${entry.message}${entry.taskId ? ` (${entry.taskId})` : ""}`).join("\n")
172
+ : "No team memory entries found.";
173
+ return result(text, { mode: "team.memory.list", type, entries });
174
+ }
175
+
176
+ function roles(cwd: string) {
177
+ const roles = teamStore.resolveRoles(cwd);
178
+ const profile = teamStore.loadActiveProfile(cwd);
179
+ const activeNames = Object.keys(profile?.roles ?? {}).sort();
180
+ const builtInNames = Object.keys(roles).filter(name => !activeNames.includes(name)).sort();
181
+ const formatRole = (name: string) => {
182
+ const role = roles[name];
183
+ return `- ${name}${role?.description ? ` — ${role.description}` : ""}`;
184
+ };
185
+ const activeText = activeNames.length > 0
186
+ ? `## Active profile roles\n${activeNames.map(formatRole).join("\n")}`
187
+ : "## Active profile roles\nNo Team profile is active.";
188
+ const availableText = builtInNames.length > 0
189
+ ? `\n\n## Other available roles\n${builtInNames.map(formatRole).join("\n")}`
190
+ : "";
191
+ const note = "Team roles are labels and prompt context. Crew still runs tasks through Crew agents and does not launch pi-subagents.";
192
+ return result(`# Team Roles\n\n${note}\n\n${activeText}${availableText}`, {
193
+ mode: "team.roles",
194
+ activeRoles: activeNames,
195
+ availableRoles: builtInNames,
196
+ roles,
197
+ });
198
+ }
199
+
200
+ function status(cwd: string) {
201
+ const team = teamStore.getActiveTeam(cwd);
202
+ const profile = teamStore.loadActiveProfile(cwd);
203
+ const charter = teamStore.readCharter(cwd);
204
+ const roles = teamStore.resolveRoles(cwd);
205
+ const roleNames = Object.keys(roles).sort();
206
+ const activeRoleNames = Object.keys(profile?.roles ?? {}).sort();
207
+ const counts = teamStore.memoryCounts(cwd);
208
+ const needsLead = teamStore.needsLeadTasks(cwd);
209
+ const rejected = teamStore.rejectedTasks(cwd);
210
+ const approvalText = needsLead.length > 0
211
+ ? `\nNeeds approval:\n${needsLead.map(t => `- ${t.id}: ${t.title} [${t.approval?.status ?? "pending"}]`).join("\n")}`
212
+ : "\nNeeds approval: none";
213
+ const rejectedText = rejected.length > 0
214
+ ? `\nRejected tasks:\n${rejected.map(t => `- ${t.id}: ${t.title}${t.approval?.feedback ? ` — ${t.approval.feedback}` : ""}`).join("\n")}`
215
+ : "\nRejected tasks: none";
216
+ const nextAction = rejected.length > 0
217
+ ? `Revise rejected work with: pi_messenger({ action: "task.revise", id: "${rejected[0].id}", prompt: "Address approval feedback" })`
218
+ : needsLead.length > 0
219
+ ? `Approve with: pi_messenger({ action: "task.approve", id: "${needsLead[0].id}" })`
220
+ : team ? "Next: plan or run Crew work with this Team context." : "Next: activate a sample profile, e.g. migration-squad, review-squad, or research-squad.";
221
+ const text = `Team: ${team?.name ?? "(none)"}\nProfile: ${profile?.name ?? team?.profile ?? "(none)"}\nCharter: ${charter ? "present" : "missing"}\nActive roles: ${activeRoleNames.length > 0 ? activeRoleNames.join(", ") : "none"}\nMemory: decisions ${counts.decision}, interfaces ${counts.interface}, risks ${counts.risk}, handoffs ${counts.handoff}${approvalText}${rejectedText}\n${nextAction}`;
222
+ return result(text, {
223
+ mode: "team.status",
224
+ team,
225
+ profile,
226
+ charterPresent: !!charter,
227
+ roles: roleNames,
228
+ activeRoles: activeRoleNames,
229
+ nextAction,
230
+ memoryCounts: counts,
231
+ needsLead: needsLead.map(t => ({ id: t.id, title: t.title, approval: t.approval })),
232
+ rejected: rejected.map(t => ({ id: t.id, title: t.title, approval: t.approval })),
233
+ taskCount: crewStore.getTasks(cwd).length,
234
+ });
235
+ }
@@ -0,0 +1,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 "@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
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Crew - ID Allocator
3
+ *
4
+ * Simple task ID allocation: task-1, task-2, ...
5
+ */
6
+
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+
10
+ /**
11
+ * Scans existing tasks to determine the next sequence number.
12
+ * Returns task ID in format: task-N
13
+ */
14
+ export function allocateTaskId(cwd: string): string {
15
+ const tasksDir = path.join(cwd, ".pi", "messenger", "crew", "tasks");
16
+
17
+ let maxN = 0;
18
+ if (fs.existsSync(tasksDir)) {
19
+ for (const file of fs.readdirSync(tasksDir)) {
20
+ const match = file.match(/^task-(\d+)\.json$/);
21
+ if (match) {
22
+ const n = parseInt(match[1], 10);
23
+ if (n > maxN) maxN = n;
24
+ }
25
+ }
26
+ }
27
+
28
+ return `task-${maxN + 1}`;
29
+ }
30
+