@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,906 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Plan Handler
|
|
3
|
+
*
|
|
4
|
+
* Orchestrates planning: planner agent → parse tasks → create in store
|
|
5
|
+
* Simplified: PRD → plan → tasks
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import * as fs from "node:fs";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import type { CrewParams } from "../types.ts";
|
|
12
|
+
import { result } from "../utils/result.ts";
|
|
13
|
+
import { spawnAgents } from "../agents.ts";
|
|
14
|
+
import { discoverCrewAgents, discoverCrewSkills, type CrewSkillInfo } from "../utils/discover.ts";
|
|
15
|
+
import { loadCrewConfig } from "../utils/config.ts";
|
|
16
|
+
import { parseVerdict, type ParsedReview } from "../utils/verdict.ts";
|
|
17
|
+
import { logFeedEvent } from "../../feed.ts";
|
|
18
|
+
import {
|
|
19
|
+
finishPlanningRun,
|
|
20
|
+
isPlanningCancelled,
|
|
21
|
+
isPlanningForCwd,
|
|
22
|
+
resetPlanningCancellation,
|
|
23
|
+
restorePlanningState,
|
|
24
|
+
setPendingAutoWork,
|
|
25
|
+
setPlanningPhase,
|
|
26
|
+
startPlanningRun,
|
|
27
|
+
type PlanningPhase,
|
|
28
|
+
} from "../state.ts";
|
|
29
|
+
import { getLiveWorkers } from "../live-progress.ts";
|
|
30
|
+
import * as store from "../store.ts";
|
|
31
|
+
import * as teamStore from "../team/store.ts";
|
|
32
|
+
import type { TeamProfile, TeamRoleDefinition } from "../team/types.ts";
|
|
33
|
+
import { taskMetadataMarkers } from "../utils/task-format.ts";
|
|
34
|
+
|
|
35
|
+
const PRD_PATTERNS = [
|
|
36
|
+
"PRD.md", "prd.md",
|
|
37
|
+
"SPEC.md", "spec.md",
|
|
38
|
+
"REQUIREMENTS.md", "requirements.md",
|
|
39
|
+
"DESIGN.md", "design.md",
|
|
40
|
+
"PLAN.md", "plan.md",
|
|
41
|
+
"docs/PRD.md", "docs/prd.md",
|
|
42
|
+
"docs/SPEC.md", "docs/spec.md",
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
const PLANNER_AGENT = "crew-planner";
|
|
46
|
+
const PROGRESS_FILE = "planning-progress.md";
|
|
47
|
+
const OUTLINE_FILE = "planning-outline.md";
|
|
48
|
+
const MAX_PROGRESS_PROMPT_SIZE = 50000;
|
|
49
|
+
|
|
50
|
+
function getProgressPath(cwd: string): string {
|
|
51
|
+
return path.join(store.getCrewDir(cwd), PROGRESS_FILE);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readProgressFile(cwd: string): string {
|
|
55
|
+
const progressPath = getProgressPath(cwd);
|
|
56
|
+
if (!fs.existsSync(progressPath)) return "";
|
|
57
|
+
try {
|
|
58
|
+
return fs.readFileSync(progressPath, "utf-8");
|
|
59
|
+
} catch {
|
|
60
|
+
return "";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readProgressForPrompt(cwd: string): string {
|
|
65
|
+
const content = readProgressFile(cwd);
|
|
66
|
+
if (!content) return "";
|
|
67
|
+
if (content.length <= MAX_PROGRESS_PROMPT_SIZE) return content;
|
|
68
|
+
|
|
69
|
+
const runMatches = Array.from(content.matchAll(/^##\s*Run:\s*/gm));
|
|
70
|
+
if (runMatches.length === 0) {
|
|
71
|
+
const marker = "\n\n[Progress truncated]";
|
|
72
|
+
const limit = Math.max(0, MAX_PROGRESS_PROMPT_SIZE - marker.length);
|
|
73
|
+
return content.slice(0, limit) + marker;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const firstRunIndex = runMatches[0].index ?? 0;
|
|
77
|
+
const lastRunIndex = runMatches[runMatches.length - 1].index ?? firstRunIndex;
|
|
78
|
+
|
|
79
|
+
const notesSection = content.slice(0, firstRunIndex).trimEnd();
|
|
80
|
+
const currentRunSection = content.slice(lastRunIndex).trimStart();
|
|
81
|
+
const marker = "[Previous runs truncated]";
|
|
82
|
+
const prefix = `${notesSection}\n\n${marker}\n\n`;
|
|
83
|
+
if (prefix.length >= MAX_PROGRESS_PROMPT_SIZE) {
|
|
84
|
+
return prefix.slice(0, MAX_PROGRESS_PROMPT_SIZE);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const available = MAX_PROGRESS_PROMPT_SIZE - prefix.length;
|
|
88
|
+
const truncatedRun = currentRunSection.slice(0, available);
|
|
89
|
+
return `${prefix}${truncatedRun}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function startRunInProgress(cwd: string, prdPath: string): void {
|
|
93
|
+
const progressPath = getProgressPath(cwd);
|
|
94
|
+
if (!fs.existsSync(progressPath)) {
|
|
95
|
+
const initial = `# Planning Progress\n\n## Notes\n<!-- User notes here are read by the planner on every run.\n Add steering like "ignore auth" or "prioritize performance". -->\n\n`;
|
|
96
|
+
fs.mkdirSync(path.dirname(progressPath), { recursive: true });
|
|
97
|
+
fs.writeFileSync(progressPath, initial);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const header = `---\n## Run: ${new Date().toISOString()} — ${prdPath}\n`;
|
|
101
|
+
fs.appendFileSync(progressPath, `\n${header}`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function formatProgressTime(): string {
|
|
105
|
+
return new Date().toISOString().slice(11, 16);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function appendPassToProgress(cwd: string, passNum: number, content: string): void {
|
|
109
|
+
const progressPath = getProgressPath(cwd);
|
|
110
|
+
const header = `### Pass ${passNum} (${formatProgressTime()})\n`;
|
|
111
|
+
fs.appendFileSync(progressPath, `\n${header}${content}\n`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function appendReviewToProgress(
|
|
115
|
+
cwd: string,
|
|
116
|
+
reviewNum: number,
|
|
117
|
+
verdict: string,
|
|
118
|
+
content: string
|
|
119
|
+
): void {
|
|
120
|
+
const progressPath = getProgressPath(cwd);
|
|
121
|
+
const header = `### Review ${reviewNum} (${formatProgressTime()})\n`;
|
|
122
|
+
fs.appendFileSync(progressPath, `\n${header}**Verdict: ${verdict}**\n${content}\n`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function notify(ctx: ExtensionContext, message: string, type: "info" | "warning" | "error" = "info"): void {
|
|
126
|
+
if (!ctx.hasUI) return;
|
|
127
|
+
ctx.ui.notify(message, type);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function advancePhase(
|
|
131
|
+
cwd: string,
|
|
132
|
+
phase: PlanningPhase,
|
|
133
|
+
agentName: string,
|
|
134
|
+
feedType: "plan.pass.start" | "plan.pass.done" | "plan.review.start" | "plan.review.done",
|
|
135
|
+
target: string,
|
|
136
|
+
preview: string,
|
|
137
|
+
pass: number,
|
|
138
|
+
): void {
|
|
139
|
+
setPlanningPhase(cwd, phase, pass);
|
|
140
|
+
logFeedEvent(cwd, agentName, feedType, target, preview);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function wipeTasks(cwd: string): void {
|
|
144
|
+
const tasksDir = path.join(store.getCrewDir(cwd), "tasks");
|
|
145
|
+
if (fs.existsSync(tasksDir)) {
|
|
146
|
+
fs.rmSync(tasksDir, { recursive: true, force: true });
|
|
147
|
+
}
|
|
148
|
+
const blocksDir = path.join(store.getCrewDir(cwd), "blocks");
|
|
149
|
+
if (fs.existsSync(blocksDir)) {
|
|
150
|
+
fs.rmSync(blocksDir, { recursive: true, force: true });
|
|
151
|
+
}
|
|
152
|
+
store.updatePlan(cwd, { task_count: 0, completed_count: 0 });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function injectSteeringPrompt(cwd: string, prompt: string): void {
|
|
156
|
+
const progressPath = getProgressPath(cwd);
|
|
157
|
+
if (!fs.existsSync(progressPath)) return;
|
|
158
|
+
const content = fs.readFileSync(progressPath, "utf-8");
|
|
159
|
+
const runMatch = content.match(/^##\s+Run:/m);
|
|
160
|
+
const entry = `[${new Date().toISOString()}] Re-plan: ${prompt}\n\n`;
|
|
161
|
+
if (runMatch && runMatch.index !== undefined) {
|
|
162
|
+
const before = content.slice(0, runMatch.index);
|
|
163
|
+
const after = content.slice(runMatch.index);
|
|
164
|
+
fs.writeFileSync(progressPath, before + entry + after);
|
|
165
|
+
} else {
|
|
166
|
+
fs.appendFileSync(progressPath, `\n${entry}`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function setPlanningOutline(cwd: string, content: string): void {
|
|
171
|
+
const outlinePath = path.join(store.getCrewDir(cwd), OUTLINE_FILE);
|
|
172
|
+
fs.mkdirSync(path.dirname(outlinePath), { recursive: true });
|
|
173
|
+
fs.writeFileSync(outlinePath, content);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function pruneTransitiveDeps(cwd: string, taskIds: string[]): void {
|
|
177
|
+
const idDeps = new Map<string, string[]>();
|
|
178
|
+
for (const id of taskIds) {
|
|
179
|
+
const task = store.getTask(cwd, id);
|
|
180
|
+
if (task) idDeps.set(id, [...task.depends_on]);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function isReachable(from: string, to: string, visited = new Set<string>()): boolean {
|
|
184
|
+
if (visited.has(from)) return false;
|
|
185
|
+
visited.add(from);
|
|
186
|
+
const deps = idDeps.get(from);
|
|
187
|
+
if (!deps) return false;
|
|
188
|
+
if (deps.includes(to)) return true;
|
|
189
|
+
return deps.some(d => isReachable(d, to, visited));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
for (const id of taskIds) {
|
|
193
|
+
const deps = idDeps.get(id);
|
|
194
|
+
if (!deps || deps.length < 2) continue;
|
|
195
|
+
const pruned = deps.filter(dep =>
|
|
196
|
+
!deps.some(other => other !== dep && isReachable(other, dep))
|
|
197
|
+
);
|
|
198
|
+
if (pruned.length < deps.length) {
|
|
199
|
+
store.updateTask(cwd, id, { depends_on: pruned });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export async function execute(
|
|
205
|
+
params: CrewParams,
|
|
206
|
+
ctx: ExtensionContext,
|
|
207
|
+
agentName: string,
|
|
208
|
+
onProgress?: () => void,
|
|
209
|
+
sessionModel?: string,
|
|
210
|
+
) {
|
|
211
|
+
const cwd = ctx.cwd;
|
|
212
|
+
const { prd, prompt } = params;
|
|
213
|
+
const reportProgress = () => onProgress?.();
|
|
214
|
+
resetPlanningCancellation();
|
|
215
|
+
|
|
216
|
+
// Sync with persisted planning state so a concurrent/cross-process plan run
|
|
217
|
+
// (live pid) is rejected below instead of duplicating the task set.
|
|
218
|
+
restorePlanningState(cwd);
|
|
219
|
+
|
|
220
|
+
const existingPlan = store.getPlan(cwd);
|
|
221
|
+
if (existingPlan) {
|
|
222
|
+
const existingTasks = store.getTasks(cwd);
|
|
223
|
+
const planningActive = isPlanningForCwd(cwd);
|
|
224
|
+
|
|
225
|
+
if (planningActive) {
|
|
226
|
+
return result("Planning is already in progress.", { mode: "plan", error: "planning_active" });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (existingTasks.length > 0 && !prompt) {
|
|
230
|
+
const planRef = existingPlan.prompt
|
|
231
|
+
? `"${store.getPlanLabel(existingPlan)}"`
|
|
232
|
+
: existingPlan.prd;
|
|
233
|
+
return result(`A plan already exists for ${planRef}.\n\nTo re-plan with a steering prompt:\n pi_messenger({ action: "plan", prompt: "focus on..." })`, {
|
|
234
|
+
mode: "plan",
|
|
235
|
+
error: "plan_exists",
|
|
236
|
+
existingPrd: existingPlan.prd,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (existingTasks.length > 0 && prompt) {
|
|
241
|
+
const liveWorkers = getLiveWorkers(cwd);
|
|
242
|
+
const inProgress = existingTasks.filter(t => t.status === "in_progress" || liveWorkers.has(t.id));
|
|
243
|
+
if (inProgress.length > 0) {
|
|
244
|
+
return result(`Cannot re-plan: ${inProgress.length} task(s) in progress (${inProgress.map(t => t.id).join(", ")}). Stop or complete them first.`, {
|
|
245
|
+
mode: "plan",
|
|
246
|
+
error: "tasks_in_progress",
|
|
247
|
+
inProgress: inProgress.map(t => t.id),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
wipeTasks(cwd);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (existingTasks.length === 0 && !prompt) {
|
|
254
|
+
const crewDir = store.getCrewDir(cwd);
|
|
255
|
+
try { fs.rmSync(crewDir, { recursive: true, force: true }); } catch {}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
let prdPath: string;
|
|
260
|
+
let prdContent: string;
|
|
261
|
+
|
|
262
|
+
if (prd) {
|
|
263
|
+
prdPath = prd;
|
|
264
|
+
const fullPath = path.isAbsolute(prd) ? prd : path.join(cwd, prd);
|
|
265
|
+
if (!fs.existsSync(fullPath)) {
|
|
266
|
+
return result(`PRD file not found: ${prd}`, {
|
|
267
|
+
mode: "plan",
|
|
268
|
+
error: "prd_not_found",
|
|
269
|
+
prd
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
prdContent = fs.readFileSync(fullPath, "utf-8");
|
|
273
|
+
if (prdContent.length > MAX_PRD_SIZE) {
|
|
274
|
+
prdContent = prdContent.slice(0, MAX_PRD_SIZE) + "\n\n[Content truncated]";
|
|
275
|
+
}
|
|
276
|
+
} else {
|
|
277
|
+
const discovered = discoverPRD(cwd);
|
|
278
|
+
if (discovered) {
|
|
279
|
+
prdPath = discovered.relativePath;
|
|
280
|
+
prdContent = discovered.content;
|
|
281
|
+
} else if (prompt) {
|
|
282
|
+
prdPath = "(prompt)";
|
|
283
|
+
prdContent = prompt;
|
|
284
|
+
if (prdContent.length > MAX_PRD_SIZE) {
|
|
285
|
+
prdContent = prdContent.slice(0, MAX_PRD_SIZE) + "\n\n[Content truncated]";
|
|
286
|
+
}
|
|
287
|
+
} else {
|
|
288
|
+
return result(`No PRD file found. Create one of: ${PRD_PATTERNS.slice(0, 4).join(", ")}\n\nOr:\n pi_messenger({ action: "plan", prd: "path/to/PRD.md" })\n pi_messenger({ action: "plan", prompt: "Scan for bugs" })`, {
|
|
289
|
+
mode: "plan",
|
|
290
|
+
error: "no_prd",
|
|
291
|
+
searchedPatterns: PRD_PATTERNS
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const isPromptBased = prdPath === "(prompt)";
|
|
297
|
+
|
|
298
|
+
const availableAgents = discoverCrewAgents(cwd);
|
|
299
|
+
|
|
300
|
+
if (!availableAgents.some(a => a.name === PLANNER_AGENT)) {
|
|
301
|
+
return result(`Error: ${PLANNER_AGENT} agent not found. Check extension installation.`, {
|
|
302
|
+
mode: "plan",
|
|
303
|
+
error: "no_planner"
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const config = loadCrewConfig(store.getCrewDir(cwd));
|
|
308
|
+
const maxPasses = Math.max(1, config.planning.maxPasses);
|
|
309
|
+
const hasReviewer = availableAgents.some(a => a.name === "crew-reviewer");
|
|
310
|
+
const skills = discoverCrewSkills(cwd);
|
|
311
|
+
const activeTeam = teamStore.getActiveTeam(cwd);
|
|
312
|
+
const activeProfile = activeTeam ? teamStore.loadActiveProfile(cwd) : null;
|
|
313
|
+
const teamRoles = activeTeam ? teamStore.resolveRoles(cwd) : {};
|
|
314
|
+
const approvalLabels = activeTeam ? teamStore.activeApprovalLabels(cwd) : [];
|
|
315
|
+
|
|
316
|
+
const existingProgress = readProgressForPrompt(cwd);
|
|
317
|
+
|
|
318
|
+
const runLabel = isPromptBased
|
|
319
|
+
? (prompt!.length > 60 ? prompt!.slice(0, 57) + "..." : prompt!)
|
|
320
|
+
: prdPath;
|
|
321
|
+
|
|
322
|
+
store.createPlan(cwd, prdPath, isPromptBased ? prompt : undefined);
|
|
323
|
+
startRunInProgress(cwd, runLabel);
|
|
324
|
+
if (prompt && !isPromptBased) injectSteeringPrompt(cwd, prompt);
|
|
325
|
+
startPlanningRun(cwd, maxPasses);
|
|
326
|
+
setPlanningPhase(cwd, "read-prd", 0);
|
|
327
|
+
logFeedEvent(cwd, agentName, "plan.start", prdPath, `max passes ${maxPasses}`);
|
|
328
|
+
notify(ctx, `Planning started: ${isPromptBased ? runLabel : path.basename(prdPath)} (${maxPasses} pass${maxPasses === 1 ? "" : "es"})`, "info");
|
|
329
|
+
reportProgress();
|
|
330
|
+
|
|
331
|
+
let lastPlannerOutput = "";
|
|
332
|
+
let lastVerdict: ParsedReview | null = null;
|
|
333
|
+
let lastReviewOutput = "";
|
|
334
|
+
let passesCompleted = 0;
|
|
335
|
+
let plannerFailedPass: number | null = null;
|
|
336
|
+
|
|
337
|
+
for (let pass = 1; pass <= maxPasses; pass++) {
|
|
338
|
+
const passPhase: PlanningPhase = pass === 1 ? "scan-code" : "gap-analysis";
|
|
339
|
+
advancePhase(cwd, passPhase, agentName, "plan.pass.start", prdPath, `pass ${pass}/${maxPasses}`, pass);
|
|
340
|
+
reportProgress();
|
|
341
|
+
notify(ctx, `Planning pass ${pass}/${maxPasses} in progress`, "info");
|
|
342
|
+
|
|
343
|
+
const plannerPrompt = pass === 1
|
|
344
|
+
? buildFirstPassPrompt(prdPath, prdContent, existingProgress, isPromptBased, skills, activeTeam?.name, activeProfile, teamRoles, approvalLabels)
|
|
345
|
+
: buildRefinementPrompt(prdPath, prdContent, readProgressForPrompt(cwd), isPromptBased, skills, activeTeam?.name, activeProfile, teamRoles, approvalLabels);
|
|
346
|
+
|
|
347
|
+
const [plannerResult] = await spawnAgents([{
|
|
348
|
+
agent: PLANNER_AGENT,
|
|
349
|
+
task: plannerPrompt,
|
|
350
|
+
modelOverride: config.models?.planner ?? sessionModel,
|
|
351
|
+
taskId: "__planner__",
|
|
352
|
+
}], cwd);
|
|
353
|
+
|
|
354
|
+
if (isPlanningCancelled()) {
|
|
355
|
+
return result("Planning cancelled.", { mode: "plan", error: "cancelled" });
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (plannerResult.exitCode !== 0) {
|
|
359
|
+
if (pass === 1) {
|
|
360
|
+
finishPlanningRun(cwd, "failed", pass);
|
|
361
|
+
reportProgress();
|
|
362
|
+
logFeedEvent(cwd, agentName, "plan.failed", prdPath, `pass ${pass} failed`);
|
|
363
|
+
notify(ctx, "Planning failed on pass 1. No tasks were created.", "error");
|
|
364
|
+
store.deletePlan(cwd);
|
|
365
|
+
return result(`Error: Planner failed: ${plannerResult.error ?? "Unknown error"}`, {
|
|
366
|
+
mode: "plan",
|
|
367
|
+
error: "planner_failed"
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
appendPassToProgress(cwd, pass, `[Planner failed: ${plannerResult.error ?? "Unknown error"}]`);
|
|
372
|
+
logFeedEvent(cwd, agentName, "plan.failed", prdPath, `pass ${pass} failed, using previous pass output`);
|
|
373
|
+
notify(ctx, `Planner failed on pass ${pass}; using previous pass output.`, "warning");
|
|
374
|
+
plannerFailedPass = pass;
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
lastPlannerOutput = plannerResult.output;
|
|
379
|
+
passesCompleted = pass;
|
|
380
|
+
appendPassToProgress(cwd, pass, lastPlannerOutput);
|
|
381
|
+
advancePhase(cwd, "build-task-graph", agentName, "plan.pass.done", prdPath, `pass ${pass}/${maxPasses} complete`, pass);
|
|
382
|
+
reportProgress();
|
|
383
|
+
|
|
384
|
+
if (pass >= maxPasses) break;
|
|
385
|
+
if (!hasReviewer) break;
|
|
386
|
+
|
|
387
|
+
advancePhase(cwd, "review-pass", agentName, "plan.review.start", prdPath, `review pass ${pass}`, pass);
|
|
388
|
+
reportProgress();
|
|
389
|
+
notify(ctx, `Reviewing planning pass ${pass}/${maxPasses}`, "info");
|
|
390
|
+
|
|
391
|
+
const reviewPrompt = buildPlanReviewPrompt(
|
|
392
|
+
prdPath,
|
|
393
|
+
prdContent,
|
|
394
|
+
lastPlannerOutput,
|
|
395
|
+
pass,
|
|
396
|
+
lastReviewOutput,
|
|
397
|
+
isPromptBased,
|
|
398
|
+
);
|
|
399
|
+
|
|
400
|
+
const [reviewResult] = await spawnAgents([{
|
|
401
|
+
agent: "crew-reviewer",
|
|
402
|
+
task: reviewPrompt,
|
|
403
|
+
modelOverride: config.models?.reviewer ?? sessionModel,
|
|
404
|
+
taskId: "__reviewer__",
|
|
405
|
+
}], cwd);
|
|
406
|
+
|
|
407
|
+
if (isPlanningCancelled()) {
|
|
408
|
+
return result("Planning cancelled.", { mode: "plan", error: "cancelled" });
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if (reviewResult.exitCode !== 0) {
|
|
412
|
+
logFeedEvent(cwd, agentName, "plan.review.done", prdPath, `review pass ${pass} failed`);
|
|
413
|
+
setPlanningPhase(cwd, "build-steps", pass);
|
|
414
|
+
reportProgress();
|
|
415
|
+
notify(ctx, `Review failed on pass ${pass}; continuing with planner output.`, "warning");
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
lastVerdict = parseVerdict(reviewResult.output);
|
|
420
|
+
lastReviewOutput = reviewResult.output;
|
|
421
|
+
appendReviewToProgress(cwd, pass, lastVerdict.verdict, reviewResult.output);
|
|
422
|
+
advancePhase(cwd, "build-steps", agentName, "plan.review.done", prdPath, `review ${pass}: ${lastVerdict.verdict}`, pass);
|
|
423
|
+
reportProgress();
|
|
424
|
+
|
|
425
|
+
if (lastVerdict.verdict === "SHIP") break;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
setPlanningPhase(cwd, "build-steps", passesCompleted);
|
|
429
|
+
reportProgress();
|
|
430
|
+
|
|
431
|
+
const tasks = parseJsonTaskBlock(lastPlannerOutput) ?? parseTasksFromOutput(lastPlannerOutput);
|
|
432
|
+
const sections = extractPlanSections(lastPlannerOutput);
|
|
433
|
+
const outlineContent = sections
|
|
434
|
+
? `# Planning Outline\n\n## 1. PRD Understanding Summary\n${sections.prdSummary}\n\n## 2. Relevant Code/Docs/Resources Reviewed\n${sections.resourcesReviewed}\n\n## 3. Sequential Implementation Steps\n${sections.sequentialSteps}\n\n## 4. Parallelized Task Graph\n${sections.parallelTaskGraph}\n`
|
|
435
|
+
: `# Planning Outline\n\nStructured sections were not detected. Full planner output is included below.\n\n${lastPlannerOutput}`;
|
|
436
|
+
setPlanningOutline(cwd, outlineContent);
|
|
437
|
+
|
|
438
|
+
if (tasks.length === 0) {
|
|
439
|
+
store.setPlanSpec(cwd, lastPlannerOutput);
|
|
440
|
+
finishPlanningRun(cwd, "failed", passesCompleted);
|
|
441
|
+
reportProgress();
|
|
442
|
+
logFeedEvent(cwd, agentName, "plan.failed", prdPath, "no tasks parsed");
|
|
443
|
+
notify(ctx, "Planning finished but no tasks could be parsed. Review plan.md.", "warning");
|
|
444
|
+
|
|
445
|
+
return result(`Plan analysis complete but no tasks could be parsed.\n\nAnalysis saved to plan.md. Review and create tasks manually.`, {
|
|
446
|
+
mode: "plan",
|
|
447
|
+
prd: prdPath,
|
|
448
|
+
analysisLength: lastPlannerOutput.length
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const plannedTasks: { id: string; title: string; dependsOn: string[] }[] = [];
|
|
453
|
+
let newTaskCount = 0;
|
|
454
|
+
const titleToId = new Map<string, string>();
|
|
455
|
+
|
|
456
|
+
// Reconcile against tasks already on the board so a duplicated plan run
|
|
457
|
+
// reuses them by title instead of appending a second copy.
|
|
458
|
+
const existingByTitle = new Map(
|
|
459
|
+
store.getTasks(cwd).map(t => [t.title.toLowerCase(), t.id] as const),
|
|
460
|
+
);
|
|
461
|
+
|
|
462
|
+
for (let i = 0; i < tasks.length; i++) {
|
|
463
|
+
const task = tasks[i];
|
|
464
|
+
const titleKey = task.title.toLowerCase();
|
|
465
|
+
let taskId = titleToId.get(titleKey) ?? existingByTitle.get(titleKey);
|
|
466
|
+
if (!taskId) {
|
|
467
|
+
const role = teamStore.canonicalRoleForTask(cwd, task.role);
|
|
468
|
+
const riskLabels = teamStore.normalizeRiskLabels(task.riskLabels);
|
|
469
|
+
const approval = teamStore.approvalForTask(cwd, role, riskLabels);
|
|
470
|
+
const created = store.createTask(cwd, task.title, task.description, undefined, {
|
|
471
|
+
...(role ? { role } : {}),
|
|
472
|
+
...(riskLabels && riskLabels.length > 0 ? { risk_labels: riskLabels } : {}),
|
|
473
|
+
...(approval ? { approval } : {}),
|
|
474
|
+
...(task.skills && task.skills.length > 0 ? { skills: task.skills } : {}),
|
|
475
|
+
});
|
|
476
|
+
taskId = created.id;
|
|
477
|
+
newTaskCount++;
|
|
478
|
+
}
|
|
479
|
+
titleToId.set(titleKey, taskId);
|
|
480
|
+
titleToId.set(`task ${i + 1}`, taskId);
|
|
481
|
+
titleToId.set(`task-${i + 1}`, taskId);
|
|
482
|
+
if (!plannedTasks.some(t => t.id === taskId)) {
|
|
483
|
+
plannedTasks.push({ id: taskId, title: task.title, dependsOn: task.dependsOn });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
for (const task of plannedTasks) {
|
|
488
|
+
if (task.dependsOn.length > 0) {
|
|
489
|
+
const resolvedDeps: string[] = [];
|
|
490
|
+
for (const dep of task.dependsOn) {
|
|
491
|
+
const depId = titleToId.get(dep.toLowerCase());
|
|
492
|
+
if (depId && depId !== task.id) {
|
|
493
|
+
resolvedDeps.push(depId);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (resolvedDeps.length > 0) {
|
|
497
|
+
store.updateTask(cwd, task.id, { depends_on: resolvedDeps });
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
pruneTransitiveDeps(cwd, plannedTasks.map(t => t.id));
|
|
504
|
+
|
|
505
|
+
store.setPlanSpec(cwd, lastPlannerOutput);
|
|
506
|
+
|
|
507
|
+
const taskList = plannedTasks.map(t => {
|
|
508
|
+
const task = store.getTask(cwd, t.id);
|
|
509
|
+
const deps = task?.depends_on.length ? ` → deps: ${task.depends_on.join(", ")}` : "";
|
|
510
|
+
const markers = task ? taskMetadataMarkers(task) : "";
|
|
511
|
+
return ` - ${t.id}: ${t.title}${markers}${deps}`;
|
|
512
|
+
}).join("\n");
|
|
513
|
+
|
|
514
|
+
const passLabel = passesCompleted === 1 ? "pass" : "passes";
|
|
515
|
+
let planningSummary = "";
|
|
516
|
+
let warningLine = "";
|
|
517
|
+
|
|
518
|
+
if (plannerFailedPass !== null) {
|
|
519
|
+
planningSummary = `**Planning:** ${passesCompleted} ${passLabel} (pass ${plannerFailedPass} planner failed, using pass ${passesCompleted} output)`;
|
|
520
|
+
warningLine = "⚠️ Planner failed on refinement pass. Tasks created from initial plan.";
|
|
521
|
+
} else if (hasReviewer && maxPasses > 1 && lastVerdict) {
|
|
522
|
+
if (lastVerdict.verdict === "SHIP") {
|
|
523
|
+
planningSummary = `**Planning:** ${passesCompleted} ${passLabel}, reviewer verdict: SHIP`;
|
|
524
|
+
} else if (passesCompleted >= maxPasses) {
|
|
525
|
+
planningSummary = `**Planning:** ${passesCompleted} ${passLabel} (max reached, last verdict: ${lastVerdict.verdict})`;
|
|
526
|
+
warningLine = `⚠️ Unresolved review feedback saved to ${PROGRESS_FILE}`;
|
|
527
|
+
} else {
|
|
528
|
+
planningSummary = `**Planning:** ${passesCompleted} ${passLabel}, reviewer verdict: ${lastVerdict.verdict}`;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const planningBlock = planningSummary ? `${planningSummary}\n` : "";
|
|
533
|
+
const warningBlock = warningLine ? `${warningLine}\n` : "";
|
|
534
|
+
|
|
535
|
+
setPlanningPhase(cwd, "finalizing", passesCompleted);
|
|
536
|
+
reportProgress();
|
|
537
|
+
|
|
538
|
+
const successLabel = isPromptBased ? `"${runLabel}"` : `**${prdPath}**`;
|
|
539
|
+
const shouldAutoWork = params.autoWork !== false;
|
|
540
|
+
let nextSteps = `**Next steps:**
|
|
541
|
+
- Review tasks: \`pi_messenger({ action: "task.list" })\`
|
|
542
|
+
- Start work: \`pi_messenger({ action: "work" })\`
|
|
543
|
+
- Autonomous: \`pi_messenger({ action: "work", autonomous: true })\``;
|
|
544
|
+
if (shouldAutoWork) {
|
|
545
|
+
const ready = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" });
|
|
546
|
+
const startable = ready.filter(t => !teamStore.taskNeedsApproval(t));
|
|
547
|
+
const needsApproval = ready.filter(teamStore.taskNeedsApproval);
|
|
548
|
+
nextSteps = startable.length > 0
|
|
549
|
+
? `Workers will start automatically.`
|
|
550
|
+
: needsApproval.length > 0
|
|
551
|
+
? `Ready tasks need lead approval before workers can start:\n${needsApproval.map(t => `- \`pi_messenger({ action: "task.approve", id: "${t.id}" })\` — ${t.title}`).join("\n")}`
|
|
552
|
+
: `No tasks are startable yet. Review dependencies with \`pi_messenger({ action: "task.ready" })\`.`;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const text = `✅ Plan created from ${successLabel}
|
|
556
|
+
|
|
557
|
+
${planningBlock}**Tasks ready:** ${plannedTasks.length}
|
|
558
|
+
${warningBlock}
|
|
559
|
+
|
|
560
|
+
${taskList}
|
|
561
|
+
|
|
562
|
+
${nextSteps}`;
|
|
563
|
+
|
|
564
|
+
finishPlanningRun(cwd, "completed", passesCompleted);
|
|
565
|
+
reportProgress();
|
|
566
|
+
logFeedEvent(cwd, agentName, "plan.done", prdPath, `${plannedTasks.length} tasks ready`);
|
|
567
|
+
if (warningLine) {
|
|
568
|
+
notify(ctx, `Plan ready with ${plannedTasks.length} tasks (${warningLine})`, "warning");
|
|
569
|
+
} else {
|
|
570
|
+
notify(ctx, `Plan ready with ${plannedTasks.length} tasks.`, "info");
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
if (shouldAutoWork) {
|
|
574
|
+
setPendingAutoWork(cwd);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return result(text, {
|
|
578
|
+
mode: "plan",
|
|
579
|
+
prd: prdPath,
|
|
580
|
+
plannerAgent: PLANNER_AGENT,
|
|
581
|
+
tasksCreated: plannedTasks.map(t => ({ id: t.id, title: t.title })),
|
|
582
|
+
newTaskCount,
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// =============================================================================
|
|
587
|
+
// Prompt Builders
|
|
588
|
+
// =============================================================================
|
|
589
|
+
|
|
590
|
+
function formatSkillsForPlanner(skills: CrewSkillInfo[]): string {
|
|
591
|
+
if (skills.length === 0) return "";
|
|
592
|
+
|
|
593
|
+
const lines = skills.map(s => ` ${s.name} — ${s.description}`);
|
|
594
|
+
return `
|
|
595
|
+
## Available Skills
|
|
596
|
+
|
|
597
|
+
Workers can load these skills on demand during task execution. When creating tasks, you may include a \`skills\` array with relevant skill names to help workers prioritize which to read.
|
|
598
|
+
|
|
599
|
+
${lines.join("\n")}
|
|
600
|
+
|
|
601
|
+
`;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function formatTeamForPlanner(teamName: string | undefined, profile: TeamProfile | null, roles: Record<string, TeamRoleDefinition>, approvalLabels: string[]): string {
|
|
605
|
+
if (!teamName) return "";
|
|
606
|
+
const roleLines = Object.values(roles)
|
|
607
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
608
|
+
.map(role => ` ${role.name}${role.description ? ` — ${role.description}` : ""}${role.model ? ` (model: ${role.model})` : ""}`);
|
|
609
|
+
const approvalLine = approvalLabels.length > 0
|
|
610
|
+
? `\nHigh-risk labels requiring lead approval for editing roles: ${approvalLabels.join(", ")}\n`
|
|
611
|
+
: "";
|
|
612
|
+
|
|
613
|
+
return `
|
|
614
|
+
## Active Team
|
|
615
|
+
|
|
616
|
+
Team: ${teamName}${profile?.name ? `\nProfile: ${profile.name}` : ""}
|
|
617
|
+
|
|
618
|
+
Available roles for task assignment:
|
|
619
|
+
${roleLines.join("\n")}${approvalLine}
|
|
620
|
+
These are Team role labels and prompt context; Crew still runs tasks through Crew agents and does not launch pi-subagents.
|
|
621
|
+
When creating tasks, include optional \`role\` and \`riskLabels\` fields where useful. Use non-editing roles such as scout, researcher, reviewer, planner, oracle, and context-builder for investigation, planning, decision, or review tasks.
|
|
622
|
+
|
|
623
|
+
`;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
function tasksJsonFormatHint(skills: CrewSkillInfo[], teamActive: boolean): string {
|
|
627
|
+
const fields = ["title", "description", "dependsOn"];
|
|
628
|
+
if (skills.length > 0) fields.push("optionally skills (array of skill names from the Available Skills list that are relevant to the task)");
|
|
629
|
+
if (teamActive) fields.push("role", "riskLabels (array of high-risk labels such as auth or api-contract)");
|
|
630
|
+
return `${fields.slice(0, -1).join(", ")}${fields.length > 1 ? ", and " : ""}${fields[fields.length - 1]}`;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
function buildFirstPassPrompt(
|
|
634
|
+
prdPath: string,
|
|
635
|
+
prdContent: string,
|
|
636
|
+
existingProgress: string,
|
|
637
|
+
isPromptBased: boolean,
|
|
638
|
+
skills: CrewSkillInfo[],
|
|
639
|
+
teamName?: string,
|
|
640
|
+
profile: TeamProfile | null = null,
|
|
641
|
+
roles: Record<string, TeamRoleDefinition> = {},
|
|
642
|
+
approvalLabels: string[] = [],
|
|
643
|
+
): string {
|
|
644
|
+
const specType = isPromptBased ? "request" : "PRD";
|
|
645
|
+
const specLabel = isPromptBased ? "Request" : `PRD: ${prdPath}`;
|
|
646
|
+
const progressSection = existingProgress
|
|
647
|
+
? `\n## Previous Planning Context\n${existingProgress}\n`
|
|
648
|
+
: "";
|
|
649
|
+
const skillsSection = formatSkillsForPlanner(skills);
|
|
650
|
+
const teamSection = formatTeamForPlanner(teamName, profile, roles, approvalLabels);
|
|
651
|
+
|
|
652
|
+
return `Create a task breakdown for implementing this ${specType}.
|
|
653
|
+
|
|
654
|
+
## ${specLabel}
|
|
655
|
+
|
|
656
|
+
${prdContent}
|
|
657
|
+
${progressSection}${skillsSection}${teamSection}
|
|
658
|
+
You must follow this sequence strictly:
|
|
659
|
+
1) Understand the ${specType}
|
|
660
|
+
2) Review relevant code/docs/reference resources
|
|
661
|
+
3) Produce sequential implementation steps
|
|
662
|
+
4) Produce a parallel task graph
|
|
663
|
+
|
|
664
|
+
Return output in this exact section order and headings:
|
|
665
|
+
## 1. PRD Understanding Summary
|
|
666
|
+
## 2. Relevant Code/Docs/Resources Reviewed
|
|
667
|
+
## 3. Sequential Implementation Steps
|
|
668
|
+
## 4. Parallelized Task Graph
|
|
669
|
+
|
|
670
|
+
In section 4, include both:
|
|
671
|
+
- markdown task breakdown
|
|
672
|
+
- a \`tasks-json\` fenced block with task objects containing ${tasksJsonFormatHint(skills, !!teamName)}.`;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function buildRefinementPrompt(
|
|
676
|
+
prdPath: string,
|
|
677
|
+
prdContent: string,
|
|
678
|
+
progressFileContent: string,
|
|
679
|
+
isPromptBased: boolean,
|
|
680
|
+
skills: CrewSkillInfo[],
|
|
681
|
+
teamName?: string,
|
|
682
|
+
profile: TeamProfile | null = null,
|
|
683
|
+
roles: Record<string, TeamRoleDefinition> = {},
|
|
684
|
+
approvalLabels: string[] = [],
|
|
685
|
+
): string {
|
|
686
|
+
const specLabel = isPromptBased ? "Request" : `PRD: ${prdPath}`;
|
|
687
|
+
const skillsSection = formatSkillsForPlanner(skills);
|
|
688
|
+
const teamSection = formatTeamForPlanner(teamName, profile, roles, approvalLabels);
|
|
689
|
+
return `Refine your task breakdown based on review feedback.
|
|
690
|
+
|
|
691
|
+
## ${specLabel}
|
|
692
|
+
${prdContent}
|
|
693
|
+
${skillsSection}${teamSection}
|
|
694
|
+
## Planning Progress
|
|
695
|
+
${progressFileContent}
|
|
696
|
+
|
|
697
|
+
The planning progress above contains your previous findings and the reviewer's
|
|
698
|
+
feedback. Address the issues raised. You can use tools to re-examine specific
|
|
699
|
+
files if needed, but focus on refinement rather than full re-exploration.
|
|
700
|
+
|
|
701
|
+
Return output in this exact section order and headings:
|
|
702
|
+
## 1. PRD Understanding Summary
|
|
703
|
+
## 2. Relevant Code/Docs/Resources Reviewed
|
|
704
|
+
## 3. Sequential Implementation Steps
|
|
705
|
+
## 4. Parallelized Task Graph
|
|
706
|
+
|
|
707
|
+
In section 4, include both:
|
|
708
|
+
- markdown task breakdown
|
|
709
|
+
- a \`tasks-json\` fenced block with task objects containing ${tasksJsonFormatHint(skills, !!teamName)}.`;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function buildPlanReviewPrompt(
|
|
713
|
+
prdPath: string,
|
|
714
|
+
prdContent: string,
|
|
715
|
+
plannerOutput: string,
|
|
716
|
+
passNum: number,
|
|
717
|
+
previousReviewOutput: string,
|
|
718
|
+
isPromptBased: boolean,
|
|
719
|
+
): string {
|
|
720
|
+
const specType = isPromptBased ? "request" : "PRD";
|
|
721
|
+
const specHeader = isPromptBased ? "Request" : "PRD";
|
|
722
|
+
const specRef = isPromptBased ? "(see below)" : prdPath;
|
|
723
|
+
const previousReviewSection = previousReviewOutput
|
|
724
|
+
? `## Previous Review Feedback\n${previousReviewOutput}\n\nCheck whether the planner addressed the issues from your previous review.\n`
|
|
725
|
+
: "";
|
|
726
|
+
|
|
727
|
+
return `# Plan Review Request
|
|
728
|
+
|
|
729
|
+
**${specHeader}:** ${specRef}
|
|
730
|
+
**Planning Pass:** ${passNum}
|
|
731
|
+
|
|
732
|
+
## ${isPromptBased ? "Request" : "PRD Content"}
|
|
733
|
+
${prdContent}
|
|
734
|
+
|
|
735
|
+
## Planner Output (Pass ${passNum})
|
|
736
|
+
${plannerOutput}
|
|
737
|
+
|
|
738
|
+
${previousReviewSection}## Your Review
|
|
739
|
+
Evaluate this plan against the ${specType}:
|
|
740
|
+
1. Completeness — are all requirements from the ${specType} covered?
|
|
741
|
+
2. Task granularity — is each task completable in one work session?
|
|
742
|
+
3. Dependencies — correct and complete dependency chain?
|
|
743
|
+
4. Gaps — missing tasks, edge cases, security concerns?
|
|
744
|
+
5. Parallelism — are there unnecessary sequential dependencies? Tasks that don't share files or types should be independent. Flag any chain that could be split into concurrent streams.
|
|
745
|
+
6. Critical path — what's the longest dependency chain? Could it be shortened by restructuring?
|
|
746
|
+
|
|
747
|
+
Output your verdict as SHIP, NEEDS_WORK, or MAJOR_RETHINK with detailed feedback.`;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// =============================================================================
|
|
751
|
+
// Task Parsing
|
|
752
|
+
// =============================================================================
|
|
753
|
+
|
|
754
|
+
interface PlanSections {
|
|
755
|
+
prdSummary: string;
|
|
756
|
+
resourcesReviewed: string;
|
|
757
|
+
sequentialSteps: string;
|
|
758
|
+
parallelTaskGraph: string;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
interface ParsedTask {
|
|
762
|
+
title: string;
|
|
763
|
+
description: string;
|
|
764
|
+
dependsOn: string[];
|
|
765
|
+
skills?: string[];
|
|
766
|
+
role?: string;
|
|
767
|
+
riskLabels?: string[];
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function extractPlanSections(output: string): PlanSections | null {
|
|
771
|
+
const headingRegex = /^##\s+([1-4])\.\s+(.+)$/gm;
|
|
772
|
+
const headings: Array<{ index: number; num: number }> = [];
|
|
773
|
+
|
|
774
|
+
for (const match of output.matchAll(headingRegex)) {
|
|
775
|
+
headings.push({ index: match.index ?? 0, num: Number(match[1]) });
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
const expectedOrder = [1, 2, 3, 4];
|
|
779
|
+
if (headings.length < 4) return null;
|
|
780
|
+
const firstFour = headings.slice(0, 4);
|
|
781
|
+
if (!firstFour.every((h, idx) => h.num === expectedOrder[idx])) return null;
|
|
782
|
+
|
|
783
|
+
const end = output.length;
|
|
784
|
+
const section = (start: number, nextStart: number) => output.slice(start, nextStart).trim();
|
|
785
|
+
|
|
786
|
+
const s1Start = firstFour[0].index;
|
|
787
|
+
const s2Start = firstFour[1].index;
|
|
788
|
+
const s3Start = firstFour[2].index;
|
|
789
|
+
const s4Start = firstFour[3].index;
|
|
790
|
+
|
|
791
|
+
const s1Body = section(s1Start, s2Start).replace(/^##\s+1\.\s+.+\n?/, "").trim();
|
|
792
|
+
const s2Body = section(s2Start, s3Start).replace(/^##\s+2\.\s+.+\n?/, "").trim();
|
|
793
|
+
const s3Body = section(s3Start, s4Start).replace(/^##\s+3\.\s+.+\n?/, "").trim();
|
|
794
|
+
const s4Body = section(s4Start, end).replace(/^##\s+4\.\s+.+\n?/, "").trim();
|
|
795
|
+
|
|
796
|
+
if (!s1Body || !s2Body || !s3Body || !s4Body) return null;
|
|
797
|
+
|
|
798
|
+
return {
|
|
799
|
+
prdSummary: s1Body,
|
|
800
|
+
resourcesReviewed: s2Body,
|
|
801
|
+
sequentialSteps: s3Body,
|
|
802
|
+
parallelTaskGraph: s4Body,
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
function parseJsonTaskBlock(output: string): ParsedTask[] | null {
|
|
807
|
+
const match = output.match(/```tasks-json\s*\n([\s\S]*?)\n```/);
|
|
808
|
+
if (!match) return null;
|
|
809
|
+
try {
|
|
810
|
+
const parsed = JSON.parse(match[1]);
|
|
811
|
+
if (!Array.isArray(parsed)) return null;
|
|
812
|
+
const tasks = parsed
|
|
813
|
+
.filter((t: unknown): t is Record<string, unknown> => !!t && typeof t === "object" && !Array.isArray(t))
|
|
814
|
+
.filter(t => typeof t.title === "string" && t.title.trim().length > 0)
|
|
815
|
+
.map(t => ({
|
|
816
|
+
title: (t.title as string).trim(),
|
|
817
|
+
description: typeof t.description === "string" ? t.description : "",
|
|
818
|
+
dependsOn: Array.isArray(t.dependsOn) ? t.dependsOn.filter((d: unknown) => typeof d === "string") : [],
|
|
819
|
+
skills: Array.isArray(t.skills) ? t.skills.filter((s: unknown) => typeof s === "string") : undefined,
|
|
820
|
+
role: typeof t.role === "string" && t.role.trim().length > 0 ? t.role.trim() : undefined,
|
|
821
|
+
riskLabels: Array.isArray(t.riskLabels) ? t.riskLabels.filter((s: unknown) => typeof s === "string") : undefined,
|
|
822
|
+
}));
|
|
823
|
+
return tasks.length > 0 ? tasks : null;
|
|
824
|
+
} catch {
|
|
825
|
+
return null;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* Parses tasks from planner output (markdown fallback).
|
|
831
|
+
*
|
|
832
|
+
* Expected format:
|
|
833
|
+
* ### Task 1: [Title]
|
|
834
|
+
* [Description...]
|
|
835
|
+
* Dependencies: none | Task 1, Task 2
|
|
836
|
+
*/
|
|
837
|
+
function parseTasksFromOutput(output: string): ParsedTask[] {
|
|
838
|
+
const tasks: ParsedTask[] = [];
|
|
839
|
+
|
|
840
|
+
const taskRegex = /###\s*Task\s*\d+:\s*(.+?)\n([\s\S]*?)(?=###\s*Task\s*\d+:|## |$)/gi;
|
|
841
|
+
let match;
|
|
842
|
+
|
|
843
|
+
while ((match = taskRegex.exec(output)) !== null) {
|
|
844
|
+
const title = match[1].trim();
|
|
845
|
+
const body = match[2].trim();
|
|
846
|
+
|
|
847
|
+
const depsMatch = body.match(/Dependencies?:\s*(.+?)(?:\n|$)/i);
|
|
848
|
+
let dependsOn: string[] = [];
|
|
849
|
+
|
|
850
|
+
if (depsMatch) {
|
|
851
|
+
const depsText = depsMatch[1].trim().toLowerCase();
|
|
852
|
+
if (depsText !== "none" && depsText !== "n/a" && depsText !== "-") {
|
|
853
|
+
dependsOn = depsText
|
|
854
|
+
.split(/,\s*/)
|
|
855
|
+
.map(d => d.trim())
|
|
856
|
+
.filter(d => d.length > 0);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const description = body
|
|
861
|
+
.replace(/Dependencies?:\s*.+?(?:\n|$)/i, "")
|
|
862
|
+
.trim();
|
|
863
|
+
|
|
864
|
+
tasks.push({ title, description, dependsOn });
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
return tasks;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// =============================================================================
|
|
871
|
+
// PRD Discovery
|
|
872
|
+
// =============================================================================
|
|
873
|
+
|
|
874
|
+
interface DiscoveredPRD {
|
|
875
|
+
relativePath: string;
|
|
876
|
+
content: string;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
const MAX_PRD_SIZE = 100000;
|
|
880
|
+
|
|
881
|
+
function discoverPRD(cwd: string): DiscoveredPRD | null {
|
|
882
|
+
const seenPaths = new Set<string>();
|
|
883
|
+
|
|
884
|
+
for (const pattern of PRD_PATTERNS) {
|
|
885
|
+
const filePath = path.join(cwd, pattern);
|
|
886
|
+
if (fs.existsSync(filePath)) {
|
|
887
|
+
try {
|
|
888
|
+
const realPath = fs.realpathSync(filePath);
|
|
889
|
+
if (seenPaths.has(realPath)) continue;
|
|
890
|
+
seenPaths.add(realPath);
|
|
891
|
+
|
|
892
|
+
let content = fs.readFileSync(filePath, "utf-8");
|
|
893
|
+
|
|
894
|
+
if (content.length > MAX_PRD_SIZE) {
|
|
895
|
+
content = content.slice(0, MAX_PRD_SIZE) + "\n\n[Content truncated]";
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
return { relativePath: pattern, content };
|
|
899
|
+
} catch {
|
|
900
|
+
// Ignore read errors
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
return null;
|
|
906
|
+
}
|