@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,332 +1,350 @@
1
- /**
2
- * Crew - Worker Coordination
3
- *
4
- * Builds dependency sections, coordination context (concurrent tasks,
5
- * recent activity, ready tasks), and coordination instructions for
6
- * worker prompts. All functions use static data available at prompt-build
7
- * time — no runtime worker state.
8
- */
9
-
10
- import type { Task } from "../types.ts";
11
- import type { CrewConfig } from "../utils/config.ts";
12
- import { readFeedEvents, type FeedEvent } from "../../feed.ts";
13
- import * as store from "../store.ts";
14
- import * as teamStore from "../team/store.ts";
15
-
16
- interface CoordinationPromptOptions {
17
- readOnly?: boolean;
18
- }
19
-
20
- // =============================================================================
21
- // Dependency Section
22
- // =============================================================================
23
-
24
- export function buildDependencySection(cwd: string, task: Task, config: CrewConfig, options: CoordinationPromptOptions = {}): string {
25
- if (config.dependencies === "advisory") {
26
- const lines: string[] = [
27
- "## Dependency Status\n",
28
- "Your task has dependencies on other tasks. Some may not be complete yet — this is expected. Use the coordination system to work through it.",
29
- "",
30
- ];
31
-
32
- for (const depId of task.depends_on) {
33
- const dep = store.getTask(cwd, depId);
34
- if (!dep) {
35
- lines.push(`- ○ ${depId} — not yet started`);
36
- continue;
37
- }
38
-
39
- if (dep.status === "done") {
40
- const summary = dep.summary ? ` ${dep.summary}` : "";
41
- lines.push(`- ✓ ${dep.id} (${dep.title}) — done${summary ? `.${summary}` : ""}`);
42
- } else if (dep.status === "in_progress") {
43
- const worker = dep.assigned_to ? `, worker: ${dep.assigned_to}` : "";
44
- lines.push(`- ⟳ ${dep.id} (${dep.title}) — in progress${worker}`);
45
- } else {
46
- lines.push(`- ○ ${dep.id} (${dep.title}) — not yet started`);
47
- }
48
- }
49
-
50
- lines.push(
51
- "",
52
- "**Working with pending dependencies:**",
53
- "- Check if the dependency's output files exist. If yes, import and use them.",
54
- "- If not, define what you need locally based on your task spec. Your spec describes the interfaces.",
55
- );
56
- if (config.coordination !== "none") {
57
- lines.push("- DM in-progress workers for API details they're building.");
58
- }
59
- if (!options.readOnly) lines.push("- Reserve your files before editing to prevent conflicts.");
60
- lines.push(
61
- "- Do NOT block yourself because a dependency isn't done. Work around it.",
62
- options.readOnly
63
- ? "- Log findings, assumptions, and handoff notes in your progress for later reconciliation."
64
- : "- Log any local definitions in your progress for later reconciliation.",
65
- );
66
-
67
- return lines.join("\n") + "\n\n";
68
- }
69
-
70
- const level = config.coordination;
71
- const lines: string[] = ["## Dependencies\n", "Your task depends on these completed tasks:"];
72
-
73
- for (const depId of task.depends_on) {
74
- const dep = store.getTask(cwd, depId);
75
- if (!dep) {
76
- lines.push(`- ${depId}`);
77
- continue;
78
- }
79
-
80
- if (level === "minimal") {
81
- lines.push(`- ${depId}: ${dep.title}`);
82
- } else {
83
- const summary = dep.summary || "(no summary)";
84
- lines.push(`- ${depId} (${dep.title}): ${summary}`);
85
- }
86
- }
87
-
88
- return lines.join("\n") + "\n\n";
89
- }
90
-
91
- // =============================================================================
92
- // Coordination Context (concurrent tasks, recent activity, ready tasks)
93
- // =============================================================================
94
-
95
- const ACTIVITY_EVENT_TYPES = new Set<string>([
96
- "task.start", "task.done", "task.block", "task.reset",
97
- "reserve", "release", "message",
98
- ]);
99
-
100
- function formatFeedTime(isoTs: string): string {
101
- const d = new Date(isoTs);
102
- return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
103
- }
104
-
105
- function formatFeedVerb(type: string): string {
106
- switch (type) {
107
- case "task.start": return "started";
108
- case "task.done": return "completed";
109
- case "task.block": return "blocked";
110
- case "task.reset": return "reset";
111
- case "reserve": return "reserved";
112
- case "release": return "released";
113
- default: return type;
114
- }
115
- }
116
-
117
- function formatActivityLine(event: FeedEvent): string {
118
- const time = formatFeedTime(event.ts);
119
- if (event.type === "message") {
120
- if (event.target) {
121
- return event.preview
122
- ? `${time} ${event.agent} → ${event.target}: ${event.preview}`
123
- : `${time} ${event.agent} → ${event.target}`;
124
- }
125
- return event.preview
126
- ? `${time} ${event.agent} ✦ ${event.preview}`
127
- : `${time} ${event.agent} ✦`;
128
- }
129
- const verb = formatFeedVerb(event.type);
130
- const target = event.target ? ` ${event.target}` : "";
131
- const preview = event.preview ? ` — ${event.preview}` : "";
132
- return `${time} ${event.agent} ${verb}${target}${preview}`;
133
- }
134
-
135
- export function buildCoordinationContext(
136
- cwd: string,
137
- task: Task,
138
- config: CrewConfig,
139
- concurrentTasks: Task[],
140
- options: CoordinationPromptOptions = {},
141
- ): string {
142
- if (config.coordination === "none") return "";
143
-
144
- const level = config.coordination;
145
- let out = "";
146
-
147
- if (concurrentTasks.length > 0) {
148
- out += `## Concurrent Tasks
149
-
150
- These tasks are being worked on by other workers in this wave. Discover their agent names after joining the mesh via \`pi_messenger({ action: "list" })\`.
151
-
152
- `;
153
- for (const t of concurrentTasks) {
154
- out += `- ${t.id}: ${t.title}\n`;
155
- }
156
- out += "\n";
157
- }
158
-
159
- if (level === "moderate" || level === "chatty") {
160
- const events = readFeedEvents(cwd, 20);
161
- const signal = events.filter(e => ACTIVITY_EVENT_TYPES.has(e.type)).slice(-8);
162
- if (signal.length > 0) {
163
- out += "## Recent Activity\n\n";
164
- for (const e of signal) {
165
- out += formatActivityLine(e) + "\n";
166
- }
167
- out += "\n";
168
- }
169
- }
170
-
171
- if (level === "chatty") {
172
- const concurrentIds = new Set(concurrentTasks.map(t => t.id));
173
- const ready = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" })
174
- .filter(t => t.id !== task.id && !concurrentIds.has(t.id));
175
- const claimable = ready.filter(t => !teamStore.taskNeedsApproval(t));
176
- const needsApproval = ready.filter(teamStore.taskPendingApproval);
177
- const rejected = ready.filter(teamStore.taskNeedsRevision);
178
- if (claimable.length > 0) {
179
- out += `## Ready Tasks
180
-
181
- ${options.readOnly ? "After completing your current task, only claim one of these if it fits your read-only assignment:" : "After completing your current task, you can claim one of these:"}
182
- `;
183
- for (const t of claimable) {
184
- const deps = t.depends_on.length > 0 ? ` (deps: ${t.depends_on.join(", ")})` : "";
185
- out += `- ${t.id}: ${t.title}${deps}\n`;
186
- }
187
- out += "\n";
188
- }
189
- if (needsApproval.length > 0) {
190
- out += `## Ready Tasks Needing Approval
191
-
192
- These tasks are ready but require lead approval before anyone can claim them:
193
- `;
194
- for (const t of needsApproval) out += `- ${t.id}: ${t.title} — approve with \`pi_messenger({ action: "task.approve", id: "${t.id}" })\`\n`;
195
- out += "\n";
196
- }
197
- if (rejected.length > 0) {
198
- out += `## Rejected Tasks Needing Revision
199
-
200
- These tasks need revision before they can be approved or claimed:
201
- `;
202
- for (const t of rejected) out += `- ${t.id}: ${t.title}${t.approval?.feedback ? ` — ${t.approval.feedback}` : ""} — revise with \`pi_messenger({ action: "task.revise", id: "${t.id}", prompt: "Address approval feedback" })\`\n`;
203
- out += "\n";
204
- }
205
- }
206
-
207
- return out;
208
- }
209
-
210
- // =============================================================================
211
- // Coordination Instructions
212
- // =============================================================================
213
-
214
- export function buildCoordinationInstructions(config: CrewConfig, options: CoordinationPromptOptions = {}): string {
215
- const level = config.coordination;
216
- if (level === "none") return "";
217
-
218
- const budget = config.messageBudgets?.[level] ?? (level === "chatty" ? 10 : 5);
219
-
220
- if (level === "minimal") {
221
- if (options.readOnly) {
222
- return `## Coordination
223
-
224
- **Message budget: ${budget} messages this session.** The system enforces this.
225
-
226
- Use \`pi_messenger({ action: "list" })\` to see active workers if your investigation overlaps with their work. Message a worker only when you need concrete context or a handoff detail.
227
-
228
- `;
229
- }
230
-
231
- return `## Coordination
232
-
233
- **Message budget: ${budget} messages this session.** The system enforces this.
234
-
235
- Before editing files, check if another worker has reserved them by running:
236
-
237
- \`\`\`typescript
238
- pi_messenger({ action: "list" })
239
- \`\`\`
240
-
241
- If a file you need is reserved by another worker, message them to coordinate:
242
-
243
- \`\`\`typescript
244
- pi_messenger({ action: "send", to: "<their-name>", message: "I need to modify <file> for my task, can we coordinate?" })
245
- \`\`\`
246
-
247
- Do NOT edit files reserved by another worker without coordinating first.
248
-
249
- `;
250
- }
251
-
252
- let out = `## Coordination
253
-
254
- **Message budget: ${budget} messages this session.** The system enforces this — sends are rejected after the limit.
255
-
256
- **Broadcasts go to the team feed — only the user sees them live.** Other workers see your broadcasts in their initial context only. Use DMs for time-sensitive peer coordination.
257
-
258
- `;
259
-
260
- out += options.readOnly
261
- ? `### Announce yourself
262
- After joining the mesh and starting your task, announce what you are investigating:
263
-
264
- \`\`\`typescript
265
- pi_messenger({ action: "broadcast", message: "Starting <task-id> (<title>) — investigating <scope>" })
266
- \`\`\`
267
-
268
- `
269
- : `### Announce yourself
270
- After joining the mesh and starting your task, announce what you're working on:
271
-
272
- \`\`\`typescript
273
- pi_messenger({ action: "broadcast", message: "Starting <task-id> (<title>) — will create <files>" })
274
- \`\`\`
275
-
276
- `;
277
-
278
- if (level === "chatty") {
279
- out += `### Coordinate with peers
280
- If a concurrent task involves files or interfaces related to yours, send a brief DM. Only message when there's a concrete coordination need — shared files, interfaces, or blocking questions.
281
-
282
- \`\`\`typescript
283
- pi_messenger({ action: "send", to: "<peer-name>", message: "I'm exporting FormatOptions from types.ts — will you need it?" })
284
- \`\`\`
285
-
286
- ### Responding to messages
287
- If a peer asks you a direct question, reply briefly. Ignore messages that don't require a response. Do NOT start casual conversations.
288
-
289
- `;
290
- }
291
-
292
- out += options.readOnly
293
- ? `### On completion
294
- Announce what you found or recommend:
295
-
296
- \`\`\`typescript
297
- pi_messenger({ action: "broadcast", message: "Completed <task-id>: found <summary>" })
298
- \`\`\`
299
-
300
- `
301
- : `### On completion
302
- Announce what you built:
303
-
304
- \`\`\`typescript
305
- pi_messenger({ action: "broadcast", message: "Completed <task-id>: <file> exports <symbols>" })
306
- \`\`\`
307
-
308
- ### Reservations
309
- Before editing files, check if another worker has reserved them via \`pi_messenger({ action: "list" })\`. If a file you need is reserved, message the owner to coordinate. Do NOT edit reserved files without coordinating first.
310
-
311
- `;
312
-
313
- out += `### Questions about dependencies
314
- If your task depends on a completed task and something about its implementation is unclear, read the code and the task's progress log at \`.pi/messenger/crew/tasks/<task-id>.progress.md\`. Dependency authors are from previous waves and are no longer in the mesh.
315
-
316
- `;
317
-
318
- if (level === "chatty") {
319
- out += `### Claim next task
320
- After completing your assigned task, check if there are ready tasks you can pick up:
321
-
322
- \`\`\`typescript
323
- pi_messenger({ action: "task.ready" })
324
- \`\`\`
325
-
326
- If a task is ready, claim it only if it matches your assignment mode. If \`task.start\` fails (another worker claimed it first or the task needs approval), check for other ready tasks. Only claim if your current task completed cleanly and quickly.
327
-
328
- `;
329
- }
330
-
331
- return out;
332
- }
1
+ /**
2
+ * Crew - Worker Coordination
3
+ *
4
+ * Builds dependency sections, coordination context (concurrent tasks,
5
+ * recent activity, ready tasks), and coordination instructions for
6
+ * worker prompts. All functions use static data available at prompt-build
7
+ * time — no runtime worker state.
8
+ */
9
+
10
+ import type { Task } from "../types.ts";
11
+ import type { CrewConfig } from "../utils/config.ts";
12
+ import { readFeedEvents, type FeedEvent } from "../../feed.ts";
13
+ import * as store from "../store.ts";
14
+ import * as teamStore from "../team/store.ts";
15
+
16
+ interface CoordinationPromptOptions {
17
+ readOnly?: boolean;
18
+ }
19
+
20
+ // =============================================================================
21
+ // Dependency Section
22
+ // =============================================================================
23
+
24
+ export function buildDependencySection(
25
+ cwd: string,
26
+ task: Task,
27
+ config: CrewConfig,
28
+ options: CoordinationPromptOptions = {},
29
+ ): string {
30
+ if (config.dependencies === "advisory") {
31
+ const lines: string[] = [
32
+ "## Dependency Status\n",
33
+ "Your task has dependencies on other tasks. Some may not be complete yet — this is expected. Use the coordination system to work through it.",
34
+ "",
35
+ ];
36
+
37
+ for (const depId of task.depends_on) {
38
+ const dep = store.getTask(cwd, depId);
39
+ if (!dep) {
40
+ lines.push(`- ○ ${depId} — not yet started`);
41
+ continue;
42
+ }
43
+
44
+ if (dep.status === "done") {
45
+ const summary = dep.summary ? ` ${dep.summary}` : "";
46
+ lines.push(`- ✓ ${dep.id} (${dep.title}) — done${summary ? `.${summary}` : ""}`);
47
+ } else if (dep.status === "in_progress") {
48
+ const worker = dep.assigned_to ? `, worker: ${dep.assigned_to}` : "";
49
+ lines.push(`- ⟳ ${dep.id} (${dep.title}) — in progress${worker}`);
50
+ } else {
51
+ lines.push(`- ○ ${dep.id} (${dep.title}) — not yet started`);
52
+ }
53
+ }
54
+
55
+ lines.push(
56
+ "",
57
+ "**Working with pending dependencies:**",
58
+ "- Check if the dependency's output files exist. If yes, import and use them.",
59
+ "- If not, define what you need locally based on your task spec. Your spec describes the interfaces.",
60
+ );
61
+ if (config.coordination !== "none") {
62
+ lines.push("- DM in-progress workers for API details they're building.");
63
+ }
64
+ if (!options.readOnly) lines.push("- Reserve your files before editing to prevent conflicts.");
65
+ lines.push(
66
+ "- Do NOT block yourself because a dependency isn't done. Work around it.",
67
+ options.readOnly
68
+ ? "- Log findings, assumptions, and handoff notes in your progress for later reconciliation."
69
+ : "- Log any local definitions in your progress for later reconciliation.",
70
+ );
71
+
72
+ return lines.join("\n") + "\n\n";
73
+ }
74
+
75
+ const level = config.coordination;
76
+ const lines: string[] = ["## Dependencies\n", "Your task depends on these completed tasks:"];
77
+
78
+ for (const depId of task.depends_on) {
79
+ const dep = store.getTask(cwd, depId);
80
+ if (!dep) {
81
+ lines.push(`- ${depId}`);
82
+ continue;
83
+ }
84
+
85
+ if (level === "minimal") {
86
+ lines.push(`- ${depId}: ${dep.title}`);
87
+ } else {
88
+ const summary = dep.summary || "(no summary)";
89
+ lines.push(`- ${depId} (${dep.title}): ${summary}`);
90
+ }
91
+ }
92
+
93
+ return lines.join("\n") + "\n\n";
94
+ }
95
+
96
+ // =============================================================================
97
+ // Coordination Context (concurrent tasks, recent activity, ready tasks)
98
+ // =============================================================================
99
+
100
+ const ACTIVITY_EVENT_TYPES = new Set<string>([
101
+ "task.start",
102
+ "task.done",
103
+ "task.block",
104
+ "task.reset",
105
+ "reserve",
106
+ "release",
107
+ "message",
108
+ ]);
109
+
110
+ function formatFeedTime(isoTs: string): string {
111
+ const d = new Date(isoTs);
112
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
113
+ }
114
+
115
+ function formatFeedVerb(type: string): string {
116
+ switch (type) {
117
+ case "task.start":
118
+ return "started";
119
+ case "task.done":
120
+ return "completed";
121
+ case "task.block":
122
+ return "blocked";
123
+ case "task.reset":
124
+ return "reset";
125
+ case "reserve":
126
+ return "reserved";
127
+ case "release":
128
+ return "released";
129
+ default:
130
+ return type;
131
+ }
132
+ }
133
+
134
+ function formatActivityLine(event: FeedEvent): string {
135
+ const time = formatFeedTime(event.ts);
136
+ if (event.type === "message") {
137
+ if (event.target) {
138
+ return event.preview
139
+ ? `${time} ${event.agent} → ${event.target}: ${event.preview}`
140
+ : `${time} ${event.agent} → ${event.target}`;
141
+ }
142
+ return event.preview ? `${time} ${event.agent} ✦ ${event.preview}` : `${time} ${event.agent} ✦`;
143
+ }
144
+ const verb = formatFeedVerb(event.type);
145
+ const target = event.target ? ` ${event.target}` : "";
146
+ const preview = event.preview ? ` — ${event.preview}` : "";
147
+ return `${time} ${event.agent} ${verb}${target}${preview}`;
148
+ }
149
+
150
+ export function buildCoordinationContext(
151
+ cwd: string,
152
+ task: Task,
153
+ config: CrewConfig,
154
+ concurrentTasks: Task[],
155
+ options: CoordinationPromptOptions = {},
156
+ ): string {
157
+ if (config.coordination === "none") return "";
158
+
159
+ const level = config.coordination;
160
+ let out = "";
161
+
162
+ if (concurrentTasks.length > 0) {
163
+ out += `## Concurrent Tasks
164
+
165
+ These tasks are being worked on by other workers in this wave. Discover their agent names after joining the mesh via \`pi_messenger({ action: "list" })\`.
166
+
167
+ `;
168
+ for (const t of concurrentTasks) {
169
+ out += `- ${t.id}: ${t.title}\n`;
170
+ }
171
+ out += "\n";
172
+ }
173
+
174
+ if (level === "moderate" || level === "chatty") {
175
+ const events = readFeedEvents(cwd, 20);
176
+ const signal = events.filter(e => ACTIVITY_EVENT_TYPES.has(e.type)).slice(-8);
177
+ if (signal.length > 0) {
178
+ out += "## Recent Activity\n\n";
179
+ for (const e of signal) {
180
+ out += formatActivityLine(e) + "\n";
181
+ }
182
+ out += "\n";
183
+ }
184
+ }
185
+
186
+ if (level === "chatty") {
187
+ const concurrentIds = new Set(concurrentTasks.map(t => t.id));
188
+ const ready = store
189
+ .getReadyTasks(cwd, { advisory: config.dependencies === "advisory" })
190
+ .filter(t => t.id !== task.id && !concurrentIds.has(t.id));
191
+ const claimable = ready.filter(t => !teamStore.taskNeedsApproval(t));
192
+ const needsApproval = ready.filter(teamStore.taskPendingApproval);
193
+ const rejected = ready.filter(teamStore.taskNeedsRevision);
194
+ if (claimable.length > 0) {
195
+ out += `## Ready Tasks
196
+
197
+ ${options.readOnly ? "After completing your current task, only claim one of these if it fits your read-only assignment:" : "After completing your current task, you can claim one of these:"}
198
+ `;
199
+ for (const t of claimable) {
200
+ const deps = t.depends_on.length > 0 ? ` (deps: ${t.depends_on.join(", ")})` : "";
201
+ out += `- ${t.id}: ${t.title}${deps}\n`;
202
+ }
203
+ out += "\n";
204
+ }
205
+ if (needsApproval.length > 0) {
206
+ out += `## Ready Tasks Needing Approval
207
+
208
+ These tasks are ready but require lead approval before anyone can claim them:
209
+ `;
210
+ for (const t of needsApproval)
211
+ out += `- ${t.id}: ${t.title} — approve with \`pi_messenger({ action: "task.approve", id: "${t.id}" })\`\n`;
212
+ out += "\n";
213
+ }
214
+ if (rejected.length > 0) {
215
+ out += `## Rejected Tasks Needing Revision
216
+
217
+ These tasks need revision before they can be approved or claimed:
218
+ `;
219
+ for (const t of rejected)
220
+ out += `- ${t.id}: ${t.title}${t.approval?.feedback ? ` — ${t.approval.feedback}` : ""} — revise with \`pi_messenger({ action: "task.revise", id: "${t.id}", prompt: "Address approval feedback" })\`\n`;
221
+ out += "\n";
222
+ }
223
+ }
224
+
225
+ return out;
226
+ }
227
+
228
+ // =============================================================================
229
+ // Coordination Instructions
230
+ // =============================================================================
231
+
232
+ export function buildCoordinationInstructions(config: CrewConfig, options: CoordinationPromptOptions = {}): string {
233
+ const level = config.coordination;
234
+ if (level === "none") return "";
235
+
236
+ const budget = config.messageBudgets?.[level] ?? (level === "chatty" ? 10 : 5);
237
+
238
+ if (level === "minimal") {
239
+ if (options.readOnly) {
240
+ return `## Coordination
241
+
242
+ **Message budget: ${budget} messages this session.** The system enforces this.
243
+
244
+ Use \`pi_messenger({ action: "list" })\` to see active workers if your investigation overlaps with their work. Message a worker only when you need concrete context or a handoff detail.
245
+
246
+ `;
247
+ }
248
+
249
+ return `## Coordination
250
+
251
+ **Message budget: ${budget} messages this session.** The system enforces this.
252
+
253
+ Before editing files, check if another worker has reserved them by running:
254
+
255
+ \`\`\`typescript
256
+ pi_messenger({ action: "list" })
257
+ \`\`\`
258
+
259
+ If a file you need is reserved by another worker, message them to coordinate:
260
+
261
+ \`\`\`typescript
262
+ pi_messenger({ action: "send", to: "<their-name>", message: "I need to modify <file> for my task, can we coordinate?" })
263
+ \`\`\`
264
+
265
+ Do NOT edit files reserved by another worker without coordinating first.
266
+
267
+ `;
268
+ }
269
+
270
+ let out = `## Coordination
271
+
272
+ **Message budget: ${budget} messages this session.** The system enforces this — sends are rejected after the limit.
273
+
274
+ **Broadcasts go to the team feed — only the user sees them live.** Other workers see your broadcasts in their initial context only. Use DMs for time-sensitive peer coordination.
275
+
276
+ `;
277
+
278
+ out += options.readOnly
279
+ ? `### Announce yourself
280
+ After joining the mesh and starting your task, announce what you are investigating:
281
+
282
+ \`\`\`typescript
283
+ pi_messenger({ action: "broadcast", message: "Starting <task-id> (<title>) — investigating <scope>" })
284
+ \`\`\`
285
+
286
+ `
287
+ : `### Announce yourself
288
+ After joining the mesh and starting your task, announce what you're working on:
289
+
290
+ \`\`\`typescript
291
+ pi_messenger({ action: "broadcast", message: "Starting <task-id> (<title>) — will create <files>" })
292
+ \`\`\`
293
+
294
+ `;
295
+
296
+ if (level === "chatty") {
297
+ out += `### Coordinate with peers
298
+ If a concurrent task involves files or interfaces related to yours, send a brief DM. Only message when there's a concrete coordination need — shared files, interfaces, or blocking questions.
299
+
300
+ \`\`\`typescript
301
+ pi_messenger({ action: "send", to: "<peer-name>", message: "I'm exporting FormatOptions from types.ts — will you need it?" })
302
+ \`\`\`
303
+
304
+ ### Responding to messages
305
+ If a peer asks you a direct question, reply briefly. Ignore messages that don't require a response. Do NOT start casual conversations.
306
+
307
+ `;
308
+ }
309
+
310
+ out += options.readOnly
311
+ ? `### On completion
312
+ Announce what you found or recommend:
313
+
314
+ \`\`\`typescript
315
+ pi_messenger({ action: "broadcast", message: "Completed <task-id>: found <summary>" })
316
+ \`\`\`
317
+
318
+ `
319
+ : `### On completion
320
+ Announce what you built:
321
+
322
+ \`\`\`typescript
323
+ pi_messenger({ action: "broadcast", message: "Completed <task-id>: <file> exports <symbols>" })
324
+ \`\`\`
325
+
326
+ ### Reservations
327
+ Before editing files, check if another worker has reserved them via \`pi_messenger({ action: "list" })\`. If a file you need is reserved, message the owner to coordinate. Do NOT edit reserved files without coordinating first.
328
+
329
+ `;
330
+
331
+ out += `### Questions about dependencies
332
+ If your task depends on a completed task and something about its implementation is unclear, read the code and the task's progress log at \`.zeta/messenger/crew/tasks/<task-id>.progress.md\`. Dependency authors are from previous waves and are no longer in the mesh.
333
+
334
+ `;
335
+
336
+ if (level === "chatty") {
337
+ out += `### Claim next task
338
+ After completing your assigned task, check if there are ready tasks you can pick up:
339
+
340
+ \`\`\`typescript
341
+ pi_messenger({ action: "task.ready" })
342
+ \`\`\`
343
+
344
+ If a task is ready, claim it only if it matches your assignment mode. If \`task.start\` fails (another worker claimed it first or the task needs approval), check for other ready tasks. Only claim if your current task completed cleanly and quickly.
345
+
346
+ `;
347
+ }
348
+
349
+ return out;
350
+ }