@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.
- package/CHANGELOG.md +676 -0
- package/README.md +424 -0
- package/config-overlay.ts +171 -0
- package/config.ts +209 -0
- package/crew/agents/crew-plan-sync.md +64 -0
- package/crew/agents/crew-planner.md +172 -0
- package/crew/agents/crew-reviewer.md +58 -0
- package/crew/agents/crew-worker.md +129 -0
- package/crew/agents.ts +434 -0
- package/crew/handlers/coordination.ts +332 -0
- package/crew/handlers/plan.ts +906 -0
- package/crew/handlers/review.ts +333 -0
- package/crew/handlers/revise.ts +376 -0
- package/crew/handlers/status.ts +295 -0
- package/crew/handlers/sync.ts +233 -0
- package/crew/handlers/task.ts +792 -0
- package/crew/handlers/team.ts +235 -0
- package/crew/handlers/work.ts +425 -0
- package/crew/id-allocator.ts +30 -0
- package/crew/index.ts +257 -0
- package/crew/live-progress.ts +58 -0
- package/crew/lobby.ts +473 -0
- package/crew/prompt.ts +252 -0
- package/crew/registry.ts +114 -0
- package/crew/spawn.ts +111 -0
- package/crew/state-autonomous.ts +164 -0
- package/crew/state-planning.ts +263 -0
- package/crew/state.ts +20 -0
- package/crew/store.ts +642 -0
- package/crew/task-actions.ts +131 -0
- package/crew/team/store.ts +479 -0
- package/crew/team/subagent-roles.ts +87 -0
- package/crew/team/types.ts +50 -0
- package/crew/types.ts +194 -0
- package/crew/utils/artifacts.ts +62 -0
- package/crew/utils/config.ts +156 -0
- package/crew/utils/discover.ts +219 -0
- package/crew/utils/install.ts +85 -0
- package/crew/utils/progress.ts +187 -0
- package/crew/utils/result.ts +16 -0
- package/crew/utils/risk-labels.ts +7 -0
- package/crew/utils/task-format.ts +14 -0
- package/crew/utils/team-roles.ts +28 -0
- package/crew/utils/truncate.ts +79 -0
- package/crew/utils/verdict.ts +55 -0
- package/feed.ts +268 -0
- package/handlers.ts +1107 -0
- package/index.ts +1206 -0
- package/install.mjs +189 -0
- package/lib.ts +467 -0
- package/overlay-actions.ts +511 -0
- package/overlay-coordinator.ts +150 -0
- package/overlay-render.ts +676 -0
- package/overlay.ts +830 -0
- package/package.json +62 -0
- package/skills/pi-messenger-crew/SKILL.md +347 -0
- package/store.ts +1139 -0
- package/vitest.config.ts +10 -0
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Review Handler
|
|
3
|
+
*
|
|
4
|
+
* Spawns reviewer with git diff context for task or plan review.
|
|
5
|
+
* Simplified: works with current plan
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { execSync } from "node:child_process";
|
|
9
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import type { CrewParams } from "../types.ts";
|
|
11
|
+
import { result } from "../utils/result.ts";
|
|
12
|
+
import { spawnAgents } from "../agents.ts";
|
|
13
|
+
import { discoverCrewAgents } from "../utils/discover.ts";
|
|
14
|
+
import { loadCrewConfig } from "../utils/config.ts";
|
|
15
|
+
import { parseVerdict, type ParsedReview } from "../utils/verdict.ts";
|
|
16
|
+
import * as store from "../store.ts";
|
|
17
|
+
|
|
18
|
+
export async function execute(
|
|
19
|
+
params: CrewParams,
|
|
20
|
+
ctx: ExtensionContext,
|
|
21
|
+
sessionModel?: string,
|
|
22
|
+
) {
|
|
23
|
+
const cwd = ctx.cwd;
|
|
24
|
+
const { target, type } = params;
|
|
25
|
+
const config = loadCrewConfig(store.getCrewDir(cwd));
|
|
26
|
+
const reviewerModel = config.models?.reviewer ?? sessionModel;
|
|
27
|
+
|
|
28
|
+
if (!target) {
|
|
29
|
+
return result("Error: target (task ID) required for review action.\n\nUsage: pi_messenger({ action: \"review\", target: \"task-1\" })", {
|
|
30
|
+
mode: "review",
|
|
31
|
+
error: "missing_target"
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Check for reviewer agent
|
|
36
|
+
const availableAgents = discoverCrewAgents(cwd);
|
|
37
|
+
const hasReviewer = availableAgents.some(a => a.name === "crew-reviewer");
|
|
38
|
+
if (!hasReviewer) {
|
|
39
|
+
return result("Error: crew-reviewer agent not found. Required for code review.", {
|
|
40
|
+
mode: "review",
|
|
41
|
+
error: "no_reviewer"
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (type && type !== "impl" && type !== "plan") {
|
|
46
|
+
return result("Error: review type must be 'impl' or 'plan'.", {
|
|
47
|
+
mode: "review",
|
|
48
|
+
error: "invalid_type",
|
|
49
|
+
type,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Determine review type: "impl" for task, "plan" for plan review
|
|
54
|
+
const reviewType = type ?? (target.startsWith("task-") ? "impl" : "plan");
|
|
55
|
+
|
|
56
|
+
if (reviewType === "impl") {
|
|
57
|
+
return reviewImplementation(cwd, target, reviewerModel);
|
|
58
|
+
} else {
|
|
59
|
+
return reviewPlan(cwd, reviewerModel);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// =============================================================================
|
|
64
|
+
// Implementation Review
|
|
65
|
+
// =============================================================================
|
|
66
|
+
|
|
67
|
+
export async function reviewImplementation(cwd: string, taskId: string, modelOverride?: string) {
|
|
68
|
+
const task = store.getTask(cwd, taskId);
|
|
69
|
+
if (!task) {
|
|
70
|
+
return result(`Error: Task ${taskId} not found.`, {
|
|
71
|
+
mode: "review",
|
|
72
|
+
error: "task_not_found",
|
|
73
|
+
target: taskId
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (task.status !== "done" && task.status !== "in_progress") {
|
|
78
|
+
return result(`Error: Task ${taskId} is ${task.status}. Can only review in_progress or done tasks.`, {
|
|
79
|
+
mode: "review",
|
|
80
|
+
error: "invalid_status",
|
|
81
|
+
status: task.status
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Get git diff
|
|
86
|
+
const baseCommit = task.base_commit;
|
|
87
|
+
if (!baseCommit) {
|
|
88
|
+
return result(`Error: Task ${taskId} has no base_commit. Cannot generate diff.`, {
|
|
89
|
+
mode: "review",
|
|
90
|
+
error: "no_base_commit"
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const taskBranch = getTaskBranch(taskId, cwd);
|
|
95
|
+
const diffResult = getGitDiff(baseCommit, cwd, taskBranch ?? undefined);
|
|
96
|
+
const diff = diffResult.text;
|
|
97
|
+
const commitLog = getCommitLog(baseCommit, cwd, taskBranch ?? undefined);
|
|
98
|
+
const diffError = taskBranch && diffResult.status === "empty"
|
|
99
|
+
? `**ERROR:** Task branch \`${taskBranch}\` exists but has no changes relative to base ${baseCommit.slice(0, 12)}. The implementation appears to be missing from the branch.`
|
|
100
|
+
: null;
|
|
101
|
+
|
|
102
|
+
// Get task spec for context
|
|
103
|
+
const taskSpec = store.getTaskSpec(cwd, taskId) ?? "";
|
|
104
|
+
const plan = store.getPlan(cwd);
|
|
105
|
+
|
|
106
|
+
// Build review prompt
|
|
107
|
+
const prompt = `# Code Review Request
|
|
108
|
+
|
|
109
|
+
## Task Information
|
|
110
|
+
|
|
111
|
+
**Task ID:** ${taskId}
|
|
112
|
+
**Task Title:** ${task.title}
|
|
113
|
+
**PRD:** ${plan?.prd ?? "Unknown"}
|
|
114
|
+
|
|
115
|
+
## Task Specification
|
|
116
|
+
|
|
117
|
+
${taskSpec || "*No spec available*"}
|
|
118
|
+
|
|
119
|
+
## Changes
|
|
120
|
+
### Commits
|
|
121
|
+
${commitLog || "*No commits*"}
|
|
122
|
+
|
|
123
|
+
### Diff
|
|
124
|
+
${diffError ?? `\`\`\`diff
|
|
125
|
+
${diff}
|
|
126
|
+
\`\`\``}
|
|
127
|
+
|
|
128
|
+
## Your Review
|
|
129
|
+
|
|
130
|
+
Review this implementation following the crew-reviewer protocol.
|
|
131
|
+
Output your verdict as SHIP, NEEDS_WORK, or MAJOR_RETHINK with detailed feedback.`;
|
|
132
|
+
|
|
133
|
+
// Spawn reviewer
|
|
134
|
+
const [reviewResult] = await spawnAgents([{
|
|
135
|
+
agent: "crew-reviewer",
|
|
136
|
+
task: prompt,
|
|
137
|
+
modelOverride,
|
|
138
|
+
}], cwd);
|
|
139
|
+
|
|
140
|
+
if (reviewResult.exitCode !== 0) {
|
|
141
|
+
return result(`Error: Reviewer failed: ${reviewResult.error ?? "Unknown error"}`, {
|
|
142
|
+
mode: "review",
|
|
143
|
+
error: "reviewer_failed"
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Parse verdict from output
|
|
148
|
+
const verdict: ParsedReview = parseVerdict(reviewResult.output);
|
|
149
|
+
|
|
150
|
+
// Store review feedback in task for retry context
|
|
151
|
+
store.updateTask(cwd, taskId, {
|
|
152
|
+
last_review: {
|
|
153
|
+
verdict: verdict.verdict,
|
|
154
|
+
summary: verdict.summary,
|
|
155
|
+
issues: verdict.issues,
|
|
156
|
+
suggestions: verdict.suggestions,
|
|
157
|
+
reviewed_at: new Date().toISOString()
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
const shortSummary = verdict.summary.split("\n")[0].slice(0, 120);
|
|
161
|
+
const progressMsg = `Review: ${verdict.verdict} — ${shortSummary}`;
|
|
162
|
+
store.appendTaskProgress(cwd, taskId, "system", progressMsg);
|
|
163
|
+
|
|
164
|
+
const text = `# Review: ${taskId}
|
|
165
|
+
|
|
166
|
+
**Verdict:** ${verdict.verdict}
|
|
167
|
+
|
|
168
|
+
${verdict.summary}
|
|
169
|
+
|
|
170
|
+
${verdict.issues.length > 0 ? `## Issues\n${verdict.issues.map(i => `- ${i}`).join("\n")}` : ""}
|
|
171
|
+
|
|
172
|
+
${verdict.suggestions.length > 0 ? `## Suggestions\n${verdict.suggestions.map(s => `- ${s}`).join("\n")}` : ""}
|
|
173
|
+
|
|
174
|
+
${verdict.verdict === "SHIP" ? "✅ Ready to merge!" : verdict.verdict === "NEEDS_WORK" ? "⚠️ Address issues and re-review." : "🔄 Consider re-planning this task."}`;
|
|
175
|
+
|
|
176
|
+
return result(text, {
|
|
177
|
+
mode: "review",
|
|
178
|
+
type: "impl",
|
|
179
|
+
taskId,
|
|
180
|
+
verdict: verdict.verdict,
|
|
181
|
+
issueCount: verdict.issues.length,
|
|
182
|
+
suggestionCount: verdict.suggestions.length
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// =============================================================================
|
|
187
|
+
// Plan Review
|
|
188
|
+
// =============================================================================
|
|
189
|
+
|
|
190
|
+
async function reviewPlan(cwd: string, modelOverride?: string) {
|
|
191
|
+
const plan = store.getPlan(cwd);
|
|
192
|
+
if (!plan) {
|
|
193
|
+
return result("Error: No plan found.", {
|
|
194
|
+
mode: "review",
|
|
195
|
+
error: "no_plan"
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const planSpec = store.getPlanSpec(cwd);
|
|
200
|
+
const tasks = store.getTasks(cwd);
|
|
201
|
+
|
|
202
|
+
// Build task overview
|
|
203
|
+
const taskOverview = tasks.map(t => {
|
|
204
|
+
const spec = store.getTaskSpec(cwd, t.id);
|
|
205
|
+
const deps = t.depends_on.length > 0 ? ` (deps: ${t.depends_on.join(", ")})` : "";
|
|
206
|
+
const specPreview = spec && !spec.includes("*Spec pending*")
|
|
207
|
+
? `\n ${spec.slice(0, 200)}${spec.length > 200 ? "..." : ""}`
|
|
208
|
+
: "";
|
|
209
|
+
return `- ${t.id}: ${t.title}${deps}${specPreview}`;
|
|
210
|
+
}).join("\n");
|
|
211
|
+
|
|
212
|
+
// Build review prompt
|
|
213
|
+
const prompt = `# Plan Review Request
|
|
214
|
+
|
|
215
|
+
## Plan Information
|
|
216
|
+
|
|
217
|
+
**PRD:** ${store.getPlanLabel(plan)}
|
|
218
|
+
**Tasks:** ${tasks.length}
|
|
219
|
+
**Progress:** ${plan.completed_count}/${plan.task_count}
|
|
220
|
+
|
|
221
|
+
## Plan Specification
|
|
222
|
+
|
|
223
|
+
${planSpec || "*No spec available*"}
|
|
224
|
+
|
|
225
|
+
## Task Breakdown
|
|
226
|
+
|
|
227
|
+
${taskOverview || "*No tasks*"}
|
|
228
|
+
|
|
229
|
+
## Your Review
|
|
230
|
+
|
|
231
|
+
Review this plan for:
|
|
232
|
+
1. Completeness - Are all requirements covered?
|
|
233
|
+
2. Task granularity - Are tasks appropriately sized?
|
|
234
|
+
3. Dependencies - Are dependencies correct and complete?
|
|
235
|
+
4. Gaps - Are there missing tasks or edge cases?
|
|
236
|
+
5. Parallelism - Are there unnecessary sequential dependencies? Tasks that don't share files or types should be independent.
|
|
237
|
+
6. Critical path - What's the longest dependency chain? Could it be shortened?
|
|
238
|
+
|
|
239
|
+
Output your verdict as SHIP (plan is solid), NEEDS_WORK (minor adjustments), or MAJOR_RETHINK (fundamental issues).`;
|
|
240
|
+
|
|
241
|
+
// Spawn reviewer
|
|
242
|
+
const [reviewResult] = await spawnAgents([{
|
|
243
|
+
agent: "crew-reviewer",
|
|
244
|
+
task: prompt,
|
|
245
|
+
modelOverride,
|
|
246
|
+
}], cwd);
|
|
247
|
+
|
|
248
|
+
if (reviewResult.exitCode !== 0) {
|
|
249
|
+
return result(`Error: Reviewer failed: ${reviewResult.error ?? "Unknown error"}`, {
|
|
250
|
+
mode: "review",
|
|
251
|
+
error: "reviewer_failed"
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Parse verdict
|
|
256
|
+
const verdict: ParsedReview = parseVerdict(reviewResult.output);
|
|
257
|
+
|
|
258
|
+
const text = `# Plan Review
|
|
259
|
+
|
|
260
|
+
**PRD:** ${store.getPlanLabel(plan)}
|
|
261
|
+
**Verdict:** ${verdict.verdict}
|
|
262
|
+
|
|
263
|
+
${verdict.summary}
|
|
264
|
+
|
|
265
|
+
${verdict.issues.length > 0 ? `## Issues\n${verdict.issues.map(i => `- ${i}`).join("\n")}` : ""}
|
|
266
|
+
|
|
267
|
+
${verdict.suggestions.length > 0 ? `## Suggestions\n${verdict.suggestions.map(s => `- ${s}`).join("\n")}` : ""}
|
|
268
|
+
|
|
269
|
+
${verdict.verdict === "SHIP" ? "✅ Plan is ready for execution!" : verdict.verdict === "NEEDS_WORK" ? "⚠️ Adjust plan before starting work." : "🔄 Consider re-planning with more context."}`;
|
|
270
|
+
|
|
271
|
+
return result(text, {
|
|
272
|
+
mode: "review",
|
|
273
|
+
type: "plan",
|
|
274
|
+
prd: plan.prd,
|
|
275
|
+
verdict: verdict.verdict,
|
|
276
|
+
issueCount: verdict.issues.length,
|
|
277
|
+
suggestionCount: verdict.suggestions.length
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// =============================================================================
|
|
282
|
+
// Helpers
|
|
283
|
+
// =============================================================================
|
|
284
|
+
|
|
285
|
+
// Resolve the task's branch (task/<id>), if it exists. Branches are shared
|
|
286
|
+
// refs, so this covers branches checked out in linked worktrees as well.
|
|
287
|
+
function getTaskBranch(taskId: string, cwd: string): string | null {
|
|
288
|
+
try {
|
|
289
|
+
execSync(`git rev-parse --verify refs/heads/task/${taskId}`, {
|
|
290
|
+
cwd,
|
|
291
|
+
encoding: "utf-8",
|
|
292
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
293
|
+
timeout: 2000,
|
|
294
|
+
});
|
|
295
|
+
return `task/${taskId}`;
|
|
296
|
+
} catch {
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
type GitDiffResult =
|
|
302
|
+
| { status: "content"; text: string }
|
|
303
|
+
| { status: "empty"; text: "*No changes*" }
|
|
304
|
+
| { status: "error"; text: string };
|
|
305
|
+
|
|
306
|
+
function getGitDiff(baseCommit: string, cwd: string, ref?: string): GitDiffResult {
|
|
307
|
+
const range = ref ? `${baseCommit}...${ref}` : `${baseCommit}..HEAD`;
|
|
308
|
+
try {
|
|
309
|
+
const diff = execSync(
|
|
310
|
+
`git diff ${range}`,
|
|
311
|
+
{ cwd, encoding: "utf-8", maxBuffer: 5 * 1024 * 1024, stdio: ["pipe", "pipe", "pipe"] }
|
|
312
|
+
);
|
|
313
|
+
if (diff.length > 50000) {
|
|
314
|
+
return { status: "content", text: diff.slice(0, 50000) + "\n\n[Diff truncated - too large]" };
|
|
315
|
+
}
|
|
316
|
+
return diff ? { status: "content", text: diff } : { status: "empty", text: "*No changes*" };
|
|
317
|
+
} catch (err) {
|
|
318
|
+
const message = err instanceof Error ? err.message : "Unknown error";
|
|
319
|
+
return { status: "error", text: `*Failed to get diff: ${message}*` };
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function getCommitLog(baseCommit: string, cwd: string, ref?: string): string {
|
|
324
|
+
const range = ref ? `${baseCommit}..${ref}` : `${baseCommit}..HEAD`;
|
|
325
|
+
try {
|
|
326
|
+
return execSync(
|
|
327
|
+
`git log ${range} --oneline --no-decorate`,
|
|
328
|
+
{ cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
|
|
329
|
+
).trim() || "*No commits*";
|
|
330
|
+
} catch {
|
|
331
|
+
return "*No commits*";
|
|
332
|
+
}
|
|
333
|
+
}
|
|
@@ -0,0 +1,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
|
+
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
|
+
}
|