@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,376 +1,400 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import type { MessengerState } from "../../lib.ts";
4
- import type { CrewParams, Task } from "../types.ts";
5
- import { result } from "../utils/result.ts";
6
- import * as store from "../store.ts";
7
- import { logFeedEvent } from "../../feed.ts";
8
- import { spawnAgents } from "../agents.ts";
9
- import { getLiveWorkers } from "../live-progress.ts";
10
- import { isAutonomousForCwd, isPlanningForCwd } from "../state.ts";
11
- import { loadCrewConfig } from "../utils/config.ts";
12
-
13
- export interface ReviseResult {
14
- success: boolean;
15
- message: string;
16
- }
17
-
18
- // =============================================================================
19
- // Single task revision
20
- // =============================================================================
21
-
22
- export async function executeRevise(
23
- cwd: string,
24
- taskId: string,
25
- prompt: string | undefined,
26
- agentName: string,
27
- sessionModel?: string,
28
- ): Promise<ReviseResult> {
29
- const task = store.getTask(cwd, taskId);
30
- if (!task) return { success: false, message: `Task ${taskId} not found` };
31
- if (task.status === "in_progress") return { success: false, message: `Task ${taskId} is in_progress` };
32
- if (getLiveWorkers(cwd).has("__reviser__")) return { success: false, message: "A revision is already running" };
33
- if (isPlanningForCwd(cwd)) return { success: false, message: "Cannot revise during planning" };
34
- if (isAutonomousForCwd(cwd)) return { success: false, message: "Cannot revise during autonomous work" };
35
-
36
- if (prompt) {
37
- store.appendTaskProgress(cwd, taskId, agentName, `Revision requested: "${prompt}"`);
38
- }
39
-
40
- const spec = store.getTaskSpec(cwd, taskId) ?? "";
41
- const progress = store.getTaskProgress(cwd, taskId) ?? "";
42
- const blockContext = store.getBlockContext(cwd, taskId) ?? "";
43
- const prdContent = readPrd(cwd);
44
-
45
- const revisePrompt = buildRevisePrompt(task, spec, progress, blockContext, prdContent, prompt);
46
- const config = loadCrewConfig(store.getCrewDir(cwd));
47
-
48
- let output: string;
49
- try {
50
- const [agentResult] = await spawnAgents([{
51
- agent: "crew-planner",
52
- task: revisePrompt,
53
- taskId: "__reviser__",
54
- modelOverride: config.models?.planner ?? sessionModel,
55
- }], cwd);
56
-
57
- if (agentResult.exitCode !== 0) {
58
- const msg = `Revision failed: ${agentResult.error ?? "planner exited with error"}`;
59
- logFeedEvent(cwd, agentName, "task.revise", taskId, msg);
60
- return { success: false, message: msg };
61
- }
62
- output = agentResult.output;
63
- } catch (err) {
64
- const msg = `Revision failed: ${err instanceof Error ? err.message : "unknown error"}`;
65
- logFeedEvent(cwd, agentName, "task.revise", taskId, msg);
66
- return { success: false, message: msg };
67
- }
68
-
69
- const parsed = parseRevisedTask(output);
70
- if (!parsed) {
71
- const msg = "Revision failed: could not parse revised-task block from planner output";
72
- logFeedEvent(cwd, agentName, "task.revise", taskId, msg);
73
- return { success: false, message: msg };
74
- }
75
-
76
- if (parsed.title) store.updateTask(cwd, taskId, { title: parsed.title });
77
- store.setTaskSpec(cwd, taskId, parsed.spec);
78
-
79
- const preview = prompt ? prompt.slice(0, 60) : "revised";
80
- logFeedEvent(cwd, agentName, "task.revise", taskId, preview);
81
- return { success: true, message: `Revised ${taskId}${parsed.title ? `: ${parsed.title}` : ""}` };
82
- }
83
-
84
- export async function taskRevise(cwd: string, params: CrewParams, state: MessengerState) {
85
- const { id, prompt } = params;
86
- if (!id) return result("Error: id required for task.revise", { mode: "task.revise", error: "missing_id" });
87
-
88
- const r = await executeRevise(cwd, id, prompt ?? undefined, state.agentName || "unknown", state.model || undefined);
89
- if (!r.success) {
90
- return result(`Error: ${r.message}`, { mode: "task.revise", error: "revision_failed", id });
91
- }
92
- return result(r.message, { mode: "task.revise", id });
93
- }
94
-
95
- // =============================================================================
96
- // Subtree revision
97
- // =============================================================================
98
-
99
- export async function executeReviseTree(
100
- cwd: string,
101
- taskId: string,
102
- prompt: string | undefined,
103
- agentName: string,
104
- sessionModel?: string,
105
- ): Promise<ReviseResult> {
106
- const target = store.getTask(cwd, taskId);
107
- if (!target) return { success: false, message: `Task ${taskId} not found` };
108
- if (getLiveWorkers(cwd).has("__reviser__")) return { success: false, message: "A revision is already running" };
109
- if (isPlanningForCwd(cwd)) return { success: false, message: "Cannot revise during planning" };
110
- if (isAutonomousForCwd(cwd)) return { success: false, message: "Cannot revise during autonomous work" };
111
-
112
- const dependents = store.getTransitiveDependents(cwd, taskId);
113
- const subtreeAll = [target, ...dependents];
114
- const subtreeIds = new Set(subtreeAll.map(t => t.id));
115
-
116
- const liveWorkers = getLiveWorkers(cwd);
117
- const liveTasks = subtreeAll.filter(t => liveWorkers.has(t.id));
118
- if (liveTasks.length > 0) {
119
- return { success: false, message: `Cannot revise: ${liveTasks.map(t => t.id).join(", ")} have live workers` };
120
- }
121
-
122
- const doneTasks = subtreeAll.filter(t => t.status === "done");
123
- const revisable = subtreeAll.filter(t => t.status !== "done");
124
-
125
- if (prompt) {
126
- store.appendTaskProgress(cwd, taskId, agentName, `Tree revision requested: "${prompt}"`);
127
- }
128
-
129
- const prdContent = readPrd(cwd);
130
- const revisePrompt = buildReviseTreePrompt(subtreeAll, doneTasks, prdContent, prompt, cwd);
131
- const config = loadCrewConfig(store.getCrewDir(cwd));
132
-
133
- let output: string;
134
- try {
135
- const [agentResult] = await spawnAgents([{
136
- agent: "crew-planner",
137
- task: revisePrompt,
138
- taskId: "__reviser__",
139
- modelOverride: config.models?.planner ?? sessionModel,
140
- }], cwd);
141
-
142
- if (agentResult.exitCode !== 0) {
143
- const msg = `Tree revision failed: ${agentResult.error ?? "planner exited with error"}`;
144
- logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
145
- return { success: false, message: msg };
146
- }
147
- output = agentResult.output;
148
- } catch (err) {
149
- const msg = `Tree revision failed: ${err instanceof Error ? err.message : "unknown error"}`;
150
- logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
151
- return { success: false, message: msg };
152
- }
153
-
154
- const parsed = parseRevisionTaskBlock(output);
155
- if (!parsed || parsed.length === 0) {
156
- const msg = "Tree revision failed: could not parse tasks-json block from planner output";
157
- logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
158
- return { success: false, message: msg };
159
- }
160
-
161
- const existingEntries = parsed.filter(e => e.id);
162
- const newEntries = parsed.filter(e => !e.id && e.title);
163
-
164
- for (const entry of existingEntries) {
165
- if (!subtreeIds.has(entry.id!)) {
166
- const msg = `Tree revision failed: returned ID ${entry.id} is outside the subtree`;
167
- logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
168
- return { success: false, message: msg };
169
- }
170
- }
171
-
172
- const maxNew = Math.max(5, subtreeAll.length * 2);
173
- if (newEntries.length > maxNew) {
174
- const msg = `Tree revision failed: too many new tasks (${newEntries.length}, max ${maxNew})`;
175
- logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
176
- return { success: false, message: msg };
177
- }
178
-
179
- for (const entry of existingEntries) {
180
- if (entry.title) store.updateTask(cwd, entry.id!, { title: entry.title });
181
- store.setTaskSpec(cwd, entry.id!, entry.spec);
182
- }
183
-
184
- const titleToId = new Map<string, string>();
185
- for (const t of store.getTasks(cwd)) {
186
- titleToId.set(t.title.toLowerCase(), t.id);
187
- }
188
-
189
- for (const entry of newEntries) {
190
- const created = store.createTask(cwd, entry.title!, entry.spec, []);
191
- titleToId.set(entry.title!.toLowerCase(), created.id);
192
- }
193
-
194
- for (const entry of [...existingEntries, ...newEntries]) {
195
- if (!entry.dependsOn || entry.dependsOn.length === 0) continue;
196
- const entryId = entry.id ?? titleToId.get(entry.title!.toLowerCase());
197
- if (!entryId) continue;
198
-
199
- const resolvedDeps: string[] = [];
200
- for (const dep of entry.dependsOn) {
201
- const resolved = titleToId.get(dep.toLowerCase()) ?? (dep.startsWith("task-") ? dep : undefined);
202
- if (resolved && resolved !== entryId) resolvedDeps.push(resolved);
203
- }
204
- if (resolvedDeps.length > 0) {
205
- store.updateTask(cwd, entryId, { depends_on: resolvedDeps });
206
- }
207
- }
208
-
209
- for (const task of revisable) {
210
- store.updateTask(cwd, task.id, {
211
- status: "todo",
212
- started_at: undefined,
213
- completed_at: undefined,
214
- base_commit: undefined,
215
- assigned_to: undefined,
216
- summary: undefined,
217
- evidence: undefined,
218
- blocked_reason: undefined,
219
- });
220
- store.cleanupBlockFiles(cwd, task.id);
221
- }
222
-
223
- const preview = prompt ? prompt.slice(0, 60) : "revised tree";
224
- logFeedEvent(cwd, agentName, "task.revise-tree", taskId, `${taskId} + ${dependents.length} dependents — ${preview}`);
225
- return { success: true, message: `Revised ${taskId} + ${dependents.length} dependents` };
226
- }
227
-
228
- export async function taskReviseTree(cwd: string, params: CrewParams, state: MessengerState) {
229
- const { id, prompt } = params;
230
- if (!id) return result("Error: id required for task.revise-tree", { mode: "task.revise-tree", error: "missing_id" });
231
-
232
- const r = await executeReviseTree(cwd, id, prompt ?? undefined, state.agentName || "unknown", state.model || undefined);
233
- if (!r.success) {
234
- return result(`Error: ${r.message}`, { mode: "task.revise-tree", error: "revision_failed", id });
235
- }
236
- return result(r.message, { mode: "task.revise-tree", id });
237
- }
238
-
239
- // =============================================================================
240
- // Helpers
241
- // =============================================================================
242
-
243
- function readPrd(cwd: string): string {
244
- const plan = store.getPlan(cwd);
245
- if (!plan) return "";
246
- if (plan.prompt) return plan.prompt;
247
- const prdPath = path.isAbsolute(plan.prd) ? plan.prd : path.join(cwd, plan.prd);
248
- try { return fs.readFileSync(prdPath, "utf-8"); } catch { return ""; }
249
- }
250
-
251
- function buildRevisePrompt(
252
- task: Task,
253
- spec: string,
254
- progress: string,
255
- blockContext: string,
256
- prdContent: string,
257
- prompt: string | undefined,
258
- ): string {
259
- const parts: string[] = [
260
- `Revise the spec for task ${task.id}: "${task.title}"`,
261
- "",
262
- "## Current Spec",
263
- spec || "(no spec)",
264
- ];
265
-
266
- if (progress) parts.push("", "## Progress", progress);
267
- if (blockContext) parts.push("", "## Block Context", blockContext);
268
- if (prdContent) {
269
- const truncated = prdContent.length > 20000 ? prdContent.slice(0, 20000) + "\n[truncated]" : prdContent;
270
- parts.push("", "## PRD", truncated);
271
- }
272
- if (prompt) parts.push("", "## Revision Instructions", prompt);
273
-
274
- parts.push("", "## Output Format", `Return a single \`revised-task\` fenced block:
275
-
276
- \`\`\`revised-task
277
- {
278
- "title": "Updated title (or omit to keep current)",
279
- "spec": "Full revised spec content..."
280
- }
281
- \`\`\`
282
-
283
- The spec should be complete (not a diff). Include all sections the task needs.`);
284
-
285
- return parts.join("\n");
286
- }
287
-
288
- function buildReviseTreePrompt(
289
- subtree: Task[],
290
- doneTasks: Task[],
291
- prdContent: string,
292
- prompt: string | undefined,
293
- cwd: string,
294
- ): string {
295
- const parts: string[] = [
296
- `Revise the following task subtree. Done tasks are context (preserve them), non-done tasks are revisable.`,
297
- "",
298
- ];
299
-
300
- for (const task of subtree) {
301
- const isDone = doneTasks.some(d => d.id === task.id);
302
- const spec = store.getTaskSpec(cwd, task.id) ?? "(no spec)";
303
- const deps = task.depends_on.length > 0 ? `\nDependencies: ${task.depends_on.join(", ")}` : "";
304
- parts.push(`### ${task.id}: ${task.title} [${isDone ? "DONE - context only" : "REVISABLE"}]${deps}\n${spec}\n`);
305
- }
306
-
307
- if (prdContent) {
308
- const truncated = prdContent.length > 20000 ? prdContent.slice(0, 20000) + "\n[truncated]" : prdContent;
309
- parts.push("## PRD", truncated, "");
310
- }
311
- if (prompt) parts.push("## Revision Instructions", prompt, "");
312
-
313
- parts.push(`## Output Format
314
-
315
- Return a single \`tasks-json\` fenced block. Each task object must have:
316
- - \`id\`: the existing task ID (e.g. "task-3") for existing tasks, or OMIT for new tasks
317
- - \`title\`: task title
318
- - \`spec\`: full revised spec content
319
- - \`dependsOn\`: array of task IDs or titles this depends on
320
-
321
- Existing tasks that you don't include will be left unchanged.
322
- Do NOT include done tasks unless you need to reference them in dependencies.
323
-
324
- \`\`\`tasks-json
325
- [
326
- { "id": "task-3", "title": "...", "spec": "...", "dependsOn": [] },
327
- { "title": "New task", "spec": "...", "dependsOn": ["task-3"] }
328
- ]
329
- \`\`\``);
330
-
331
- return parts.join("\n");
332
- }
333
-
334
- function parseRevisedTask(output: string): { title?: string; spec: string } | null {
335
- const match = output.match(/```revised-task\s*\n([\s\S]*?)\n```/);
336
- if (!match) return null;
337
- try {
338
- const parsed = JSON.parse(match[1]);
339
- if (typeof parsed.spec !== "string" || !parsed.spec.trim()) return null;
340
- return {
341
- title: typeof parsed.title === "string" && parsed.title.trim() ? parsed.title.trim() : undefined,
342
- spec: parsed.spec,
343
- };
344
- } catch {
345
- return null;
346
- }
347
- }
348
-
349
- interface RevisionEntry {
350
- id?: string;
351
- title?: string;
352
- spec: string;
353
- dependsOn?: string[];
354
- }
355
-
356
- function parseRevisionTaskBlock(output: string): RevisionEntry[] | null {
357
- const match = output.match(/```tasks-json\s*\n([\s\S]*?)\n```/);
358
- if (!match) return null;
359
- try {
360
- const parsed = JSON.parse(match[1]);
361
- if (!Array.isArray(parsed)) return null;
362
- const entries: RevisionEntry[] = [];
363
- for (const raw of parsed) {
364
- if (typeof raw.spec !== "string" || !raw.spec.trim()) continue;
365
- entries.push({
366
- id: typeof raw.id === "string" && raw.id.trim() ? raw.id.trim() : undefined,
367
- title: typeof raw.title === "string" && raw.title.trim() ? raw.title.trim() : undefined,
368
- spec: raw.spec,
369
- dependsOn: Array.isArray(raw.dependsOn) ? raw.dependsOn.filter((d: unknown) => typeof d === "string") : [],
370
- });
371
- }
372
- return entries.length > 0 ? entries : null;
373
- } catch {
374
- return null;
375
- }
376
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { MessengerState } from "../../lib.ts";
4
+ import type { CrewParams, Task } from "../types.ts";
5
+ import { result } from "../utils/result.ts";
6
+ import * as store from "../store.ts";
7
+ import { logFeedEvent } from "../../feed.ts";
8
+ import { spawnAgents } from "../agents.ts";
9
+ import { getLiveWorkers } from "../live-progress.ts";
10
+ import { isAutonomousForCwd, isPlanningForCwd } from "../state.ts";
11
+ import { loadCrewConfig } from "../utils/config.ts";
12
+
13
+ export interface ReviseResult {
14
+ success: boolean;
15
+ message: string;
16
+ }
17
+
18
+ // =============================================================================
19
+ // Single task revision
20
+ // =============================================================================
21
+
22
+ export async function executeRevise(
23
+ cwd: string,
24
+ taskId: string,
25
+ prompt: string | undefined,
26
+ agentName: string,
27
+ sessionModel?: string,
28
+ ): Promise<ReviseResult> {
29
+ const task = store.getTask(cwd, taskId);
30
+ if (!task) return { success: false, message: `Task ${taskId} not found` };
31
+ if (task.status === "in_progress") return { success: false, message: `Task ${taskId} is in_progress` };
32
+ if (getLiveWorkers(cwd).has("__reviser__")) return { success: false, message: "A revision is already running" };
33
+ if (isPlanningForCwd(cwd)) return { success: false, message: "Cannot revise during planning" };
34
+ if (isAutonomousForCwd(cwd)) return { success: false, message: "Cannot revise during autonomous work" };
35
+
36
+ if (prompt) {
37
+ store.appendTaskProgress(cwd, taskId, agentName, `Revision requested: "${prompt}"`);
38
+ }
39
+
40
+ const spec = store.getTaskSpec(cwd, taskId) ?? "";
41
+ const progress = store.getTaskProgress(cwd, taskId) ?? "";
42
+ const blockContext = store.getBlockContext(cwd, taskId) ?? "";
43
+ const prdContent = readPrd(cwd);
44
+
45
+ const revisePrompt = buildRevisePrompt(task, spec, progress, blockContext, prdContent, prompt);
46
+ const config = loadCrewConfig(store.getCrewDir(cwd));
47
+
48
+ let output: string;
49
+ try {
50
+ const [agentResult] = await spawnAgents(
51
+ [
52
+ {
53
+ agent: "crew-planner",
54
+ task: revisePrompt,
55
+ taskId: "__reviser__",
56
+ modelOverride: config.models?.planner ?? sessionModel,
57
+ },
58
+ ],
59
+ cwd,
60
+ );
61
+
62
+ if (agentResult.exitCode !== 0) {
63
+ const msg = `Revision failed: ${agentResult.error ?? "planner exited with error"}`;
64
+ logFeedEvent(cwd, agentName, "task.revise", taskId, msg);
65
+ return { success: false, message: msg };
66
+ }
67
+ output = agentResult.output;
68
+ } catch (err) {
69
+ const msg = `Revision failed: ${err instanceof Error ? err.message : "unknown error"}`;
70
+ logFeedEvent(cwd, agentName, "task.revise", taskId, msg);
71
+ return { success: false, message: msg };
72
+ }
73
+
74
+ const parsed = parseRevisedTask(output);
75
+ if (!parsed) {
76
+ const msg = "Revision failed: could not parse revised-task block from planner output";
77
+ logFeedEvent(cwd, agentName, "task.revise", taskId, msg);
78
+ return { success: false, message: msg };
79
+ }
80
+
81
+ if (parsed.title) store.updateTask(cwd, taskId, { title: parsed.title });
82
+ store.setTaskSpec(cwd, taskId, parsed.spec);
83
+
84
+ const preview = prompt ? prompt.slice(0, 60) : "revised";
85
+ logFeedEvent(cwd, agentName, "task.revise", taskId, preview);
86
+ return { success: true, message: `Revised ${taskId}${parsed.title ? `: ${parsed.title}` : ""}` };
87
+ }
88
+
89
+ export async function taskRevise(cwd: string, params: CrewParams, state: MessengerState) {
90
+ const { id, prompt } = params;
91
+ if (!id) return result("Error: id required for task.revise", { mode: "task.revise", error: "missing_id" });
92
+
93
+ const r = await executeRevise(cwd, id, prompt ?? undefined, state.agentName || "unknown", state.model || undefined);
94
+ if (!r.success) {
95
+ return result(`Error: ${r.message}`, { mode: "task.revise", error: "revision_failed", id });
96
+ }
97
+ return result(r.message, { mode: "task.revise", id });
98
+ }
99
+
100
+ // =============================================================================
101
+ // Subtree revision
102
+ // =============================================================================
103
+
104
+ export async function executeReviseTree(
105
+ cwd: string,
106
+ taskId: string,
107
+ prompt: string | undefined,
108
+ agentName: string,
109
+ sessionModel?: string,
110
+ ): Promise<ReviseResult> {
111
+ const target = store.getTask(cwd, taskId);
112
+ if (!target) return { success: false, message: `Task ${taskId} not found` };
113
+ if (getLiveWorkers(cwd).has("__reviser__")) return { success: false, message: "A revision is already running" };
114
+ if (isPlanningForCwd(cwd)) return { success: false, message: "Cannot revise during planning" };
115
+ if (isAutonomousForCwd(cwd)) return { success: false, message: "Cannot revise during autonomous work" };
116
+
117
+ const dependents = store.getTransitiveDependents(cwd, taskId);
118
+ const subtreeAll = [target, ...dependents];
119
+ const subtreeIds = new Set(subtreeAll.map(t => t.id));
120
+
121
+ const liveWorkers = getLiveWorkers(cwd);
122
+ const liveTasks = subtreeAll.filter(t => liveWorkers.has(t.id));
123
+ if (liveTasks.length > 0) {
124
+ return { success: false, message: `Cannot revise: ${liveTasks.map(t => t.id).join(", ")} have live workers` };
125
+ }
126
+
127
+ const doneTasks = subtreeAll.filter(t => t.status === "done");
128
+ const revisable = subtreeAll.filter(t => t.status !== "done");
129
+
130
+ if (prompt) {
131
+ store.appendTaskProgress(cwd, taskId, agentName, `Tree revision requested: "${prompt}"`);
132
+ }
133
+
134
+ const prdContent = readPrd(cwd);
135
+ const revisePrompt = buildReviseTreePrompt(subtreeAll, doneTasks, prdContent, prompt, cwd);
136
+ const config = loadCrewConfig(store.getCrewDir(cwd));
137
+
138
+ let output: string;
139
+ try {
140
+ const [agentResult] = await spawnAgents(
141
+ [
142
+ {
143
+ agent: "crew-planner",
144
+ task: revisePrompt,
145
+ taskId: "__reviser__",
146
+ modelOverride: config.models?.planner ?? sessionModel,
147
+ },
148
+ ],
149
+ cwd,
150
+ );
151
+
152
+ if (agentResult.exitCode !== 0) {
153
+ const msg = `Tree revision failed: ${agentResult.error ?? "planner exited with error"}`;
154
+ logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
155
+ return { success: false, message: msg };
156
+ }
157
+ output = agentResult.output;
158
+ } catch (err) {
159
+ const msg = `Tree revision failed: ${err instanceof Error ? err.message : "unknown error"}`;
160
+ logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
161
+ return { success: false, message: msg };
162
+ }
163
+
164
+ const parsed = parseRevisionTaskBlock(output);
165
+ if (!parsed || parsed.length === 0) {
166
+ const msg = "Tree revision failed: could not parse tasks-json block from planner output";
167
+ logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
168
+ return { success: false, message: msg };
169
+ }
170
+
171
+ const existingEntries = parsed.filter(e => e.id);
172
+ const newEntries = parsed.filter(e => !e.id && e.title);
173
+
174
+ for (const entry of existingEntries) {
175
+ if (!subtreeIds.has(entry.id!)) {
176
+ const msg = `Tree revision failed: returned ID ${entry.id} is outside the subtree`;
177
+ logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
178
+ return { success: false, message: msg };
179
+ }
180
+ }
181
+
182
+ const maxNew = Math.max(5, subtreeAll.length * 2);
183
+ if (newEntries.length > maxNew) {
184
+ const msg = `Tree revision failed: too many new tasks (${newEntries.length}, max ${maxNew})`;
185
+ logFeedEvent(cwd, agentName, "task.revise-tree", taskId, msg);
186
+ return { success: false, message: msg };
187
+ }
188
+
189
+ for (const entry of existingEntries) {
190
+ if (entry.title) store.updateTask(cwd, entry.id!, { title: entry.title });
191
+ store.setTaskSpec(cwd, entry.id!, entry.spec);
192
+ }
193
+
194
+ const titleToId = new Map<string, string>();
195
+ for (const t of store.getTasks(cwd)) {
196
+ titleToId.set(t.title.toLowerCase(), t.id);
197
+ }
198
+
199
+ for (const entry of newEntries) {
200
+ const created = store.createTask(cwd, entry.title!, entry.spec, []);
201
+ titleToId.set(entry.title!.toLowerCase(), created.id);
202
+ }
203
+
204
+ for (const entry of [...existingEntries, ...newEntries]) {
205
+ if (!entry.dependsOn || entry.dependsOn.length === 0) continue;
206
+ const entryId = entry.id ?? titleToId.get(entry.title!.toLowerCase());
207
+ if (!entryId) continue;
208
+
209
+ const resolvedDeps: string[] = [];
210
+ for (const dep of entry.dependsOn) {
211
+ const resolved = titleToId.get(dep.toLowerCase()) ?? (dep.startsWith("task-") ? dep : undefined);
212
+ if (resolved && resolved !== entryId) resolvedDeps.push(resolved);
213
+ }
214
+ if (resolvedDeps.length > 0) {
215
+ store.updateTask(cwd, entryId, { depends_on: resolvedDeps });
216
+ }
217
+ }
218
+
219
+ for (const task of revisable) {
220
+ store.updateTask(cwd, task.id, {
221
+ status: "todo",
222
+ started_at: undefined,
223
+ completed_at: undefined,
224
+ base_commit: undefined,
225
+ assigned_to: undefined,
226
+ summary: undefined,
227
+ evidence: undefined,
228
+ blocked_reason: undefined,
229
+ });
230
+ store.cleanupBlockFiles(cwd, task.id);
231
+ }
232
+
233
+ const preview = prompt ? prompt.slice(0, 60) : "revised tree";
234
+ logFeedEvent(cwd, agentName, "task.revise-tree", taskId, `${taskId} + ${dependents.length} dependents — ${preview}`);
235
+ return { success: true, message: `Revised ${taskId} + ${dependents.length} dependents` };
236
+ }
237
+
238
+ export async function taskReviseTree(cwd: string, params: CrewParams, state: MessengerState) {
239
+ const { id, prompt } = params;
240
+ if (!id) return result("Error: id required for task.revise-tree", { mode: "task.revise-tree", error: "missing_id" });
241
+
242
+ const r = await executeReviseTree(
243
+ cwd,
244
+ id,
245
+ prompt ?? undefined,
246
+ state.agentName || "unknown",
247
+ state.model || undefined,
248
+ );
249
+ if (!r.success) {
250
+ return result(`Error: ${r.message}`, { mode: "task.revise-tree", error: "revision_failed", id });
251
+ }
252
+ return result(r.message, { mode: "task.revise-tree", id });
253
+ }
254
+
255
+ // =============================================================================
256
+ // Helpers
257
+ // =============================================================================
258
+
259
+ function readPrd(cwd: string): string {
260
+ const plan = store.getPlan(cwd);
261
+ if (!plan) return "";
262
+ if (plan.prompt) return plan.prompt;
263
+ const prdPath = path.isAbsolute(plan.prd) ? plan.prd : path.join(cwd, plan.prd);
264
+ try {
265
+ return fs.readFileSync(prdPath, "utf-8");
266
+ } catch {
267
+ return "";
268
+ }
269
+ }
270
+
271
+ function buildRevisePrompt(
272
+ task: Task,
273
+ spec: string,
274
+ progress: string,
275
+ blockContext: string,
276
+ prdContent: string,
277
+ prompt: string | undefined,
278
+ ): string {
279
+ const parts: string[] = [
280
+ `Revise the spec for task ${task.id}: "${task.title}"`,
281
+ "",
282
+ "## Current Spec",
283
+ spec || "(no spec)",
284
+ ];
285
+
286
+ if (progress) parts.push("", "## Progress", progress);
287
+ if (blockContext) parts.push("", "## Block Context", blockContext);
288
+ if (prdContent) {
289
+ const truncated = prdContent.length > 20000 ? prdContent.slice(0, 20000) + "\n[truncated]" : prdContent;
290
+ parts.push("", "## PRD", truncated);
291
+ }
292
+ if (prompt) parts.push("", "## Revision Instructions", prompt);
293
+
294
+ parts.push(
295
+ "",
296
+ "## Output Format",
297
+ `Return a single \`revised-task\` fenced block:
298
+
299
+ \`\`\`revised-task
300
+ {
301
+ "title": "Updated title (or omit to keep current)",
302
+ "spec": "Full revised spec content..."
303
+ }
304
+ \`\`\`
305
+
306
+ The spec should be complete (not a diff). Include all sections the task needs.`,
307
+ );
308
+
309
+ return parts.join("\n");
310
+ }
311
+
312
+ function buildReviseTreePrompt(
313
+ subtree: Task[],
314
+ doneTasks: Task[],
315
+ prdContent: string,
316
+ prompt: string | undefined,
317
+ cwd: string,
318
+ ): string {
319
+ const parts: string[] = [
320
+ `Revise the following task subtree. Done tasks are context (preserve them), non-done tasks are revisable.`,
321
+ "",
322
+ ];
323
+
324
+ for (const task of subtree) {
325
+ const isDone = doneTasks.some(d => d.id === task.id);
326
+ const spec = store.getTaskSpec(cwd, task.id) ?? "(no spec)";
327
+ const deps = task.depends_on.length > 0 ? `\nDependencies: ${task.depends_on.join(", ")}` : "";
328
+ parts.push(`### ${task.id}: ${task.title} [${isDone ? "DONE - context only" : "REVISABLE"}]${deps}\n${spec}\n`);
329
+ }
330
+
331
+ if (prdContent) {
332
+ const truncated = prdContent.length > 20000 ? prdContent.slice(0, 20000) + "\n[truncated]" : prdContent;
333
+ parts.push("## PRD", truncated, "");
334
+ }
335
+ if (prompt) parts.push("## Revision Instructions", prompt, "");
336
+
337
+ parts.push(`## Output Format
338
+
339
+ Return a single \`tasks-json\` fenced block. Each task object must have:
340
+ - \`id\`: the existing task ID (e.g. "task-3") for existing tasks, or OMIT for new tasks
341
+ - \`title\`: task title
342
+ - \`spec\`: full revised spec content
343
+ - \`dependsOn\`: array of task IDs or titles this depends on
344
+
345
+ Existing tasks that you don't include will be left unchanged.
346
+ Do NOT include done tasks unless you need to reference them in dependencies.
347
+
348
+ \`\`\`tasks-json
349
+ [
350
+ { "id": "task-3", "title": "...", "spec": "...", "dependsOn": [] },
351
+ { "title": "New task", "spec": "...", "dependsOn": ["task-3"] }
352
+ ]
353
+ \`\`\``);
354
+
355
+ return parts.join("\n");
356
+ }
357
+
358
+ function parseRevisedTask(output: string): { title?: string; spec: string } | null {
359
+ const match = output.match(/```revised-task\s*\n([\s\S]*?)\n```/);
360
+ if (!match) return null;
361
+ try {
362
+ const parsed = JSON.parse(match[1]);
363
+ if (typeof parsed.spec !== "string" || !parsed.spec.trim()) return null;
364
+ return {
365
+ title: typeof parsed.title === "string" && parsed.title.trim() ? parsed.title.trim() : undefined,
366
+ spec: parsed.spec,
367
+ };
368
+ } catch {
369
+ return null;
370
+ }
371
+ }
372
+
373
+ interface RevisionEntry {
374
+ id?: string;
375
+ title?: string;
376
+ spec: string;
377
+ dependsOn?: string[];
378
+ }
379
+
380
+ function parseRevisionTaskBlock(output: string): RevisionEntry[] | null {
381
+ const match = output.match(/```tasks-json\s*\n([\s\S]*?)\n```/);
382
+ if (!match) return null;
383
+ try {
384
+ const parsed = JSON.parse(match[1]);
385
+ if (!Array.isArray(parsed)) return null;
386
+ const entries: RevisionEntry[] = [];
387
+ for (const raw of parsed) {
388
+ if (typeof raw.spec !== "string" || !raw.spec.trim()) continue;
389
+ entries.push({
390
+ id: typeof raw.id === "string" && raw.id.trim() ? raw.id.trim() : undefined,
391
+ title: typeof raw.title === "string" && raw.title.trim() ? raw.title.trim() : undefined,
392
+ spec: raw.spec,
393
+ dependsOn: Array.isArray(raw.dependsOn) ? raw.dependsOn.filter((d: unknown) => typeof d === "string") : [],
394
+ });
395
+ }
396
+ return entries.length > 0 ? entries : null;
397
+ } catch {
398
+ return null;
399
+ }
400
+ }