@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,295 @@
1
+ /**
2
+ * Crew - Status Handler
3
+ *
4
+ * Shows plan progress and task status.
5
+ */
6
+
7
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
+ import { result } from "../utils/result.ts";
9
+ import { discoverCrewAgents } from "../utils/discover.ts";
10
+ import { uninstallAgents } from "../utils/install.ts";
11
+ import { loadCrewConfig } from "../utils/config.ts";
12
+ import { formatDuration } from "../../lib.ts";
13
+ import * as store from "../store.ts";
14
+ import { autonomousState, getPlanningUpdateAgeMs, isAutonomousForCwd, isPlanningForCwd, isPlanningStalled, planningState, PLANNING_STALE_TIMEOUT_MS } from "../state.ts";
15
+
16
+ /**
17
+ * Execute status action - shows plan progress.
18
+ */
19
+ export async function execute(ctx: ExtensionContext) {
20
+ const cwd = ctx.cwd;
21
+ const plan = store.getPlan(cwd);
22
+
23
+ if (!plan) {
24
+ return result(`# Crew Status
25
+
26
+ **No active plan.**
27
+
28
+ Create a plan:
29
+ pi_messenger({ action: "plan" }) # Auto-discovers PRD.md
30
+ pi_messenger({ action: "plan", prd: "docs/PRD.md" }) # Explicit PRD path
31
+ pi_messenger({ action: "plan", prompt: "Scan the codebase for bugs" }) # Inline prompt`, {
32
+ mode: "status",
33
+ hasPlan: false
34
+ });
35
+ }
36
+
37
+ const tasks = store.getTasks(cwd);
38
+ const config = loadCrewConfig(store.getCrewDir(cwd));
39
+ const done = tasks.filter(t => t.status === "done");
40
+ const inProgress = tasks.filter(t => t.status === "in_progress");
41
+ const blocked = tasks.filter(t => t.status === "blocked");
42
+ const ready = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
43
+ const waiting = tasks.filter(t =>
44
+ t.status === "todo" && !ready.some(r => r.id === t.id)
45
+ );
46
+
47
+ const pct = tasks.length > 0 ? Math.round((done.length / tasks.length) * 100) : 0;
48
+ const autonomousActive = isAutonomousForCwd(cwd);
49
+
50
+ let text = `# Crew Status
51
+
52
+ **Plan:** ${store.getPlanLabel(plan)}
53
+ **Progress:** ${done.length}/${tasks.length} tasks (${pct}%)
54
+ `;
55
+
56
+ if (tasks.length === 0 && isPlanningForCwd(cwd)) {
57
+ const stalled = isPlanningStalled(cwd);
58
+ const ageMs = getPlanningUpdateAgeMs(cwd);
59
+ text += `
60
+ **Planning:** pass ${planningState.pass}/${planningState.maxPasses} — ${planningState.phase}`;
61
+ if (planningState.updatedAt) {
62
+ text += `\n**Last update:** ${planningState.updatedAt}`;
63
+ }
64
+ if (stalled) {
65
+ const ageLabel = ageMs === null ? "unknown" : formatDuration(ageMs);
66
+ text += `\n**Planning health:** stalled (no updates for ${ageLabel}; timeout ${formatDuration(PLANNING_STALE_TIMEOUT_MS)})`;
67
+ } else {
68
+ text += `\n**Planning health:** active`;
69
+ }
70
+ text += `\n**Progress log:** .pi/messenger/crew/planning-progress.md`;
71
+ text += `\n**Outline:** .pi/messenger/crew/planning-outline.md`;
72
+ }
73
+
74
+ text += `\n\n## Tasks\n`;
75
+
76
+ if (done.length > 0) {
77
+ text += `\n✅ **Done**\n`;
78
+ for (const t of done) {
79
+ text += ` - ${t.id}: ${t.title}\n`;
80
+ }
81
+ }
82
+
83
+ if (inProgress.length > 0) {
84
+ text += `\n🔄 **In Progress**\n`;
85
+ for (const t of inProgress) {
86
+ const parts: string[] = [];
87
+ if (t.assigned_to) parts.push(t.assigned_to);
88
+ if (t.attempt_count > 1) parts.push(`attempt ${t.attempt_count}`);
89
+ const suffix = parts.length > 0 ? ` (${parts.join(", ")})` : "";
90
+ text += ` - ${t.id}: ${t.title}${suffix}\n`;
91
+ }
92
+ }
93
+
94
+ if (config.dependencies === "advisory") {
95
+ if (ready.length > 0) {
96
+ text += `\n⬜ **Available**\n`;
97
+ for (const t of ready) {
98
+ let depSuffix = "";
99
+ if (t.depends_on.length > 0) {
100
+ const depStatus = t.depends_on.map(depId => {
101
+ const dep = store.getTask(cwd, depId);
102
+ if (!dep) return `${depId} ○`;
103
+ if (dep.status === "done") return `${depId} ✓`;
104
+ if (dep.status === "in_progress") return `${depId} ⟳`;
105
+ return `${depId} ○`;
106
+ }).join(", ");
107
+ depSuffix = ` (needs: ${depStatus})`;
108
+ }
109
+ text += ` - ${t.id}: ${t.title}${depSuffix}\n`;
110
+ }
111
+ }
112
+ } else {
113
+ if (ready.length > 0) {
114
+ text += `\n⬜ **Ready**\n`;
115
+ for (const t of ready) {
116
+ text += ` - ${t.id}: ${t.title}\n`;
117
+ }
118
+ }
119
+
120
+ if (waiting.length > 0) {
121
+ text += `\n⏸️ **Waiting** (dependencies not met)\n`;
122
+ for (const t of waiting) {
123
+ const deps = t.depends_on.join(", ");
124
+ text += ` - ${t.id}: ${t.title} → needs: ${deps}\n`;
125
+ }
126
+ }
127
+ }
128
+
129
+ if (blocked.length > 0) {
130
+ text += `\n🚫 **Blocked**\n`;
131
+ for (const t of blocked) {
132
+ const reason = t.blocked_reason
133
+ ? ` (${t.blocked_reason.length > 40 ? t.blocked_reason.slice(0, 40) + "..." : t.blocked_reason})`
134
+ : "";
135
+ text += ` - ${t.id}: ${t.title}${reason}\n`;
136
+ }
137
+ }
138
+
139
+ // Add autonomous status if active for this project
140
+ if (autonomousActive) {
141
+ text += `\n## Autonomous Mode\n`;
142
+ text += `Wave ${autonomousState.waveNumber} running...\n`;
143
+ if (autonomousState.startedAt) {
144
+ const startTime = new Date(autonomousState.startedAt).getTime();
145
+ const elapsedMs = Date.now() - startTime;
146
+ const minutes = Math.floor(elapsedMs / 60000);
147
+ const seconds = Math.floor((elapsedMs % 60000) / 1000);
148
+ text += `Elapsed: ${minutes}:${seconds.toString().padStart(2, "0")}\n`;
149
+ }
150
+ }
151
+
152
+ text += `\n## Next`;
153
+ if (tasks.length === 0 && isPlanningForCwd(cwd)) {
154
+ text += `\nPlanning is in progress. Check .pi/messenger/crew/planning-progress.md for updates.`;
155
+ } else if (tasks.length === 0) {
156
+ text += `\nNo tasks yet. Run \`pi_messenger({ action: "plan" })\` to generate tasks from your PRD.`;
157
+ } else if (done.length === tasks.length) {
158
+ text += `\n🎉 All tasks complete!`;
159
+ } else if (ready.length > 0) {
160
+ text += `\nRun \`pi_messenger({ action: "work" })\` to execute ${ready.map(t => t.id).join(", ")}`;
161
+ } else if (blocked.length > 0) {
162
+ text += `\nUnblock tasks with \`pi_messenger({ action: "task.unblock", id: "..." })\``;
163
+ } else if (inProgress.length > 0) {
164
+ text += `\nWaiting for in-progress tasks to complete.`;
165
+ }
166
+
167
+ return result(text, {
168
+ mode: "status",
169
+ hasPlan: true,
170
+ prd: plan.prd,
171
+ progress: { done: done.length, total: tasks.length, pct },
172
+ tasks: {
173
+ done: done.map(t => t.id),
174
+ inProgress: inProgress.map(t => t.id),
175
+ ready: ready.map(t => t.id),
176
+ waiting: waiting.map(t => t.id),
177
+ blocked: blocked.map(t => t.id)
178
+ },
179
+ planning: {
180
+ active: isPlanningForCwd(cwd),
181
+ pass: planningState.pass,
182
+ maxPasses: planningState.maxPasses,
183
+ phase: planningState.phase,
184
+ updatedAt: planningState.updatedAt,
185
+ stale: isPlanningStalled(cwd),
186
+ ageMs: getPlanningUpdateAgeMs(cwd),
187
+ staleAfterMs: PLANNING_STALE_TIMEOUT_MS,
188
+ },
189
+ autonomous: autonomousActive
190
+ });
191
+ }
192
+
193
+ /**
194
+ * Execute crew.* actions (crew.status, crew.agents, crew.install, crew.uninstall)
195
+ */
196
+ export async function executeCrew(
197
+ op: string,
198
+ ctx: ExtensionContext
199
+ ) {
200
+ const cwd = ctx.cwd;
201
+
202
+ switch (op) {
203
+ case "status": {
204
+ return execute(ctx);
205
+ }
206
+
207
+ case "agents": {
208
+ const agents = discoverCrewAgents(cwd);
209
+ if (agents.length === 0) {
210
+ return result("No crew agents found. Check extension installation.", {
211
+ mode: "crew.agents",
212
+ agents: []
213
+ });
214
+ }
215
+
216
+ const byRole: Record<string, string[]> = {};
217
+ for (const a of agents) {
218
+ const role = a.crewRole ?? "other";
219
+ if (!byRole[role]) byRole[role] = [];
220
+ byRole[role].push(`${a.name} (${a.model ?? "default"})`);
221
+ }
222
+
223
+ let text = "# Crew Agents\n";
224
+ for (const [role, names] of Object.entries(byRole)) {
225
+ text += `\n**${role}s:** ${names.join(", ")}\n`;
226
+ }
227
+
228
+ return result(text, {
229
+ mode: "crew.agents",
230
+ agents: agents.map(a => ({ name: a.name, role: a.crewRole, model: a.model }))
231
+ });
232
+ }
233
+
234
+ case "install": {
235
+ const agents = discoverCrewAgents(cwd);
236
+ return result(`Crew agents (${agents.length}): ${agents.map(a => `${a.name} (${a.source})`).join(", ")}`, {
237
+ mode: "crew.install",
238
+ agents: agents.map(a => ({ name: a.name, source: a.source })),
239
+ });
240
+ }
241
+
242
+ case "uninstall": {
243
+ const agentResult = uninstallAgents();
244
+
245
+ if (agentResult.errors.length > 0) {
246
+ return result(`⚠️ Removed with ${agentResult.errors.length} error(s):\n${agentResult.errors.join("\n")}`, {
247
+ mode: "crew.uninstall",
248
+ removed: agentResult.removed,
249
+ errors: agentResult.errors
250
+ });
251
+ }
252
+ return result(`✅ Removed ${agentResult.removed.length} agent(s)`, {
253
+ mode: "crew.uninstall",
254
+ removed: agentResult.removed,
255
+ });
256
+ }
257
+
258
+ case "validate": {
259
+ const validation = store.validatePlan(cwd);
260
+
261
+ if (validation.valid && validation.warnings.length === 0) {
262
+ return result("✅ Plan is valid with no warnings.", {
263
+ mode: "crew.validate",
264
+ valid: true,
265
+ errors: [],
266
+ warnings: []
267
+ });
268
+ }
269
+
270
+ let text = validation.valid ? "✅ Plan is valid" : "❌ Plan has errors";
271
+
272
+ if (validation.errors.length > 0) {
273
+ text += "\n\n**Errors:**\n" + validation.errors.map(e => `- ${e}`).join("\n");
274
+ }
275
+
276
+ if (validation.warnings.length > 0) {
277
+ text += "\n\n**Warnings:**\n" + validation.warnings.map(w => `- ${w}`).join("\n");
278
+ }
279
+
280
+ return result(text, {
281
+ mode: "crew.validate",
282
+ valid: validation.valid,
283
+ errors: validation.errors,
284
+ warnings: validation.warnings
285
+ });
286
+ }
287
+
288
+ default:
289
+ return result(`Unknown crew operation: ${op}`, {
290
+ mode: "crew",
291
+ error: "unknown_operation",
292
+ operation: op
293
+ });
294
+ }
295
+ }
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Crew - Sync Handler
3
+ *
4
+ * Updates downstream specs after task completion.
5
+ * Works with current plan's tasks.
6
+ */
7
+
8
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
9
+ import type { CrewParams } from "../types.ts";
10
+ import { result } from "../utils/result.ts";
11
+ import { spawnAgents } from "../agents.ts";
12
+ import { discoverCrewAgents } from "../utils/discover.ts";
13
+ import { loadCrewConfig } from "../utils/config.ts";
14
+ import * as store from "../store.ts";
15
+
16
+ export async function execute(
17
+ params: CrewParams,
18
+ ctx: ExtensionContext,
19
+ sessionModel?: string,
20
+ ) {
21
+ const cwd = ctx.cwd;
22
+ const { target } = params;
23
+
24
+ if (!target) {
25
+ return result("Error: target (completed task ID) required for sync action.", {
26
+ mode: "sync",
27
+ error: "missing_target"
28
+ });
29
+ }
30
+
31
+ // Verify plan exists
32
+ const plan = store.getPlan(cwd);
33
+ if (!plan) {
34
+ return result("Error: No plan found.", {
35
+ mode: "sync",
36
+ error: "no_plan"
37
+ });
38
+ }
39
+
40
+ // Verify task exists and is completed
41
+ const task = store.getTask(cwd, target);
42
+ if (!task) {
43
+ return result(`Error: Task ${target} not found.`, {
44
+ mode: "sync",
45
+ error: "task_not_found",
46
+ target
47
+ });
48
+ }
49
+
50
+ if (task.status !== "done") {
51
+ return result(`Error: Task ${target} is ${task.status}, not done. Sync is for completed tasks.`, {
52
+ mode: "sync",
53
+ error: "task_not_done",
54
+ status: task.status
55
+ });
56
+ }
57
+
58
+ // Check for plan-sync agent
59
+ const config = loadCrewConfig(store.getCrewDir(cwd));
60
+ const availableAgents = discoverCrewAgents(cwd);
61
+ const hasSyncAgent = availableAgents.some(a => a.name === "crew-plan-sync");
62
+ if (!hasSyncAgent) {
63
+ return result("Error: crew-plan-sync agent not found.", {
64
+ mode: "sync",
65
+ error: "no_sync_agent"
66
+ });
67
+ }
68
+
69
+ const allTasks = store.getTasks(cwd);
70
+
71
+ // Find dependent tasks (tasks that depend on the completed task)
72
+ const dependentTasks = allTasks.filter(t =>
73
+ t.depends_on.includes(target) && t.status === "todo"
74
+ );
75
+
76
+ if (dependentTasks.length === 0) {
77
+ return result(`No downstream tasks depend on ${target}. No sync needed.`, {
78
+ mode: "sync",
79
+ taskId: target,
80
+ dependentTasks: [],
81
+ synced: false
82
+ });
83
+ }
84
+
85
+ // Get completed task details for context
86
+ const taskSpec = store.getTaskSpec(cwd, target);
87
+ const taskSummary = task.summary ?? "No summary";
88
+
89
+ // Build task overview for dependent tasks
90
+ const dependentOverview = dependentTasks.map(t => {
91
+ const spec = store.getTaskSpec(cwd, t.id);
92
+ return `### ${t.id}: ${t.title}
93
+
94
+ ${spec || "*No spec*"}
95
+ `;
96
+ }).join("\n");
97
+
98
+ // Build sync prompt
99
+ const prompt = `# Spec Sync Request
100
+
101
+ ## Completed Task
102
+
103
+ **Task ID:** ${target}
104
+ **Title:** ${task.title}
105
+ **Summary:** ${taskSummary}
106
+
107
+ ### Implementation Details
108
+
109
+ ${taskSpec || "*No detailed spec*"}
110
+
111
+ ## Dependent Tasks to Update
112
+
113
+ These tasks depend on the completed task and may need spec updates:
114
+
115
+ ${dependentOverview}
116
+
117
+ ## Your Task
118
+
119
+ 1. Review what was implemented in the completed task
120
+ 2. Check if any dependent task specs need updating based on the implementation
121
+ 3. Update specs with relevant information (file locations, API details, etc.)
122
+ 4. Output which specs were updated and why
123
+
124
+ Follow the output format in your instructions.`;
125
+
126
+ // Spawn sync agent
127
+ const [syncResult] = await spawnAgents([{
128
+ agent: "crew-plan-sync",
129
+ task: prompt,
130
+ modelOverride: config.models?.analyst ?? sessionModel,
131
+ }], cwd);
132
+
133
+ if (syncResult.exitCode !== 0) {
134
+ return result(`Error: Sync agent failed: ${syncResult.error ?? "Unknown error"}`, {
135
+ mode: "sync",
136
+ error: "sync_failed"
137
+ });
138
+ }
139
+
140
+ // Parse sync results
141
+ const updates = parseSyncUpdates(syncResult.output);
142
+
143
+ // Apply updates to task specs
144
+ let updatedCount = 0;
145
+ for (const update of updates) {
146
+ const matchingTask = dependentTasks.find(t =>
147
+ t.id === update.taskId ||
148
+ t.title.toLowerCase().includes(update.taskId.toLowerCase())
149
+ );
150
+
151
+ if (matchingTask && update.newContent) {
152
+ const currentSpec = store.getTaskSpec(cwd, matchingTask.id) ?? "";
153
+
154
+ // Append update to spec (don't replace)
155
+ const updatedSpec = `${currentSpec}
156
+
157
+ ---
158
+ *Updated after ${target} completion:*
159
+
160
+ ${update.newContent}`;
161
+
162
+ store.setTaskSpec(cwd, matchingTask.id, updatedSpec);
163
+ updatedCount++;
164
+ }
165
+ }
166
+
167
+ const readyTasks = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
168
+ const text = `# Sync Complete: ${target}
169
+
170
+ **Dependent tasks checked:** ${dependentTasks.length}
171
+ **Specs updated:** ${updatedCount}
172
+
173
+ ${updates.length > 0 ? `## Updates\n${updates.map(u => `- **${u.taskId}**: ${u.reason}`).join("\n")}` : "## No Updates Needed\n\nDependent task specs are already up to date."}
174
+
175
+ ${updatedCount > 0 ? `\n**Ready tasks:** ${readyTasks.map(t => t.id).join(", ") || "none"}` : ""}`;
176
+
177
+ return result(text, {
178
+ mode: "sync",
179
+ taskId: target,
180
+ dependentTasks: dependentTasks.map(t => t.id),
181
+ updatedCount,
182
+ updates: updates.map(u => ({ taskId: u.taskId, reason: u.reason }))
183
+ });
184
+ }
185
+
186
+ // =============================================================================
187
+ // Sync Update Parsing
188
+ // =============================================================================
189
+
190
+ interface SyncUpdate {
191
+ taskId: string;
192
+ reason: string;
193
+ newContent?: string;
194
+ }
195
+
196
+ /**
197
+ * Parses sync updates from the sync agent output.
198
+ *
199
+ * Expected format:
200
+ * ### Updated: [task-id]
201
+ *
202
+ * Changes made:
203
+ * - Updated section X to reflect...
204
+ *
205
+ * New content:
206
+ * [content to add to spec]
207
+ */
208
+ function parseSyncUpdates(output: string): SyncUpdate[] {
209
+ const updates: SyncUpdate[] = [];
210
+
211
+ // Match update blocks
212
+ const updateRegex = /###\s*Updated:\s*(.+?)\n([\s\S]*?)(?=###|$)/gi;
213
+ let match;
214
+
215
+ while ((match = updateRegex.exec(output)) !== null) {
216
+ const taskId = match[1].trim();
217
+ const body = match[2].trim();
218
+
219
+ // Extract reason (Changes made section)
220
+ const reasonMatch = body.match(/Changes made:?\s*([\s\S]*?)(?=New content:|$)/i);
221
+ const reason = reasonMatch
222
+ ? reasonMatch[1].trim().replace(/^[-*]\s*/gm, "").split("\n")[0].trim()
223
+ : "Updated based on implementation";
224
+
225
+ // Extract new content
226
+ const contentMatch = body.match(/New content:?\s*([\s\S]*?)$/i);
227
+ const newContent = contentMatch ? contentMatch[1].trim() : undefined;
228
+
229
+ updates.push({ taskId, reason, newContent });
230
+ }
231
+
232
+ return updates;
233
+ }