@josecarlos61/pi-prompt-planner 0.0.0-stage → 1.0.5
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/README.md +42 -3
- package/index.js +1 -0
- package/package.json +16 -6
- package/src/index.js +13 -0
- package/src/planner.js +528 -0
- package/test/planner.test.js +265 -0
package/README.md
CHANGED
|
@@ -1,3 +1,42 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# pi-prompt-planner
|
|
2
|
+
|
|
3
|
+
Interactive step-by-step prompt planning extension for Pi.
|
|
4
|
+
|
|
5
|
+
Use `/plan <your prompt>` to break down an idea through guided user choices, select an implementation approach, review or refine the generated plan, and save a ready-to-use `.md` development plan file.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **`/plan <prompt>` command** (or run `/plan` without arguments to enter your prompt interactively)
|
|
10
|
+
- **Step-by-step clarifying questions**: The active model proposes 3–5 targeted questions with options; at each step you can pick an option, enter a custom answer, skip, or cancel
|
|
11
|
+
- **Approach selection**: Compare 2–3 generated implementation approaches or provide your own
|
|
12
|
+
- **Review & refine loop**: Edit the generated Markdown directly in Pi's editor or refine it with extra instructions before saving
|
|
13
|
+
- **Markdown export**: Save to `plans/<slug>.md`, `.pi/plans/<slug>.md`, `PLAN.md`, or a custom path, with optional prompt insertion into the editor to start development immediately
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
### Permanent installation
|
|
18
|
+
|
|
19
|
+
Install globally (all projects, saved to `~/.pi/agent/settings.json`):
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pi install npm:@josecarlos61/pi-prompt-planner
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Manage installed packages:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pi list
|
|
29
|
+
pi uninstall npm:@josecarlos61/pi-prompt-planner
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Quick test (one session)
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pi -e /path/to/pi-prompt-planner/src/index.js
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Running Tests
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm test --prefix pi-prompt-planner
|
|
42
|
+
```
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { default } from "./src/index.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@josecarlos61/pi-prompt-planner",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@josecarlos61/pi-prompt-planner",
|
|
3
|
+
"version": "1.0.5",
|
|
4
|
+
"description": "Interactive step-by-step prompt planner that generates a development Markdown plan via /plan",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": ["pi-package", "planner", "plan", "markdown", "workflow"],
|
|
7
|
+
"pi": {
|
|
8
|
+
"extensions": ["./index.js"]
|
|
9
|
+
},
|
|
10
|
+
"peerDependencies": {
|
|
11
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
12
|
+
},
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test test/*.test.js"
|
|
15
|
+
}
|
|
16
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { BorderedLoader } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { runPlanWorkflow } from "./planner.js";
|
|
3
|
+
|
|
4
|
+
export default function promptPlannerExtension(pi, deps = {}) {
|
|
5
|
+
const Loader = deps.BorderedLoader ?? BorderedLoader;
|
|
6
|
+
|
|
7
|
+
pi.registerCommand("plan", {
|
|
8
|
+
description: "Interactively plan a prompt step by step and save a development Markdown file",
|
|
9
|
+
handler: async (args, ctx) => {
|
|
10
|
+
await runPlanWorkflow(args, ctx, { BorderedLoader: Loader });
|
|
11
|
+
},
|
|
12
|
+
});
|
|
13
|
+
}
|
package/src/planner.js
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
const IGNORED_ENTRIES = new Set([".git", "node_modules", "dist", "build", ".next", ".cache"]);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Convert a title or prompt into a safe kebab-case filename slug.
|
|
8
|
+
*/
|
|
9
|
+
export function slugify(text, maxLength = 48) {
|
|
10
|
+
const cleaned = String(text || "")
|
|
11
|
+
.toLowerCase()
|
|
12
|
+
.replace(/[^a-z0-9\s-]/g, " ")
|
|
13
|
+
.trim()
|
|
14
|
+
.replace(/\s+/g, "-")
|
|
15
|
+
.replace(/-+/g, "-")
|
|
16
|
+
.slice(0, maxLength)
|
|
17
|
+
.replace(/-+$/, "");
|
|
18
|
+
|
|
19
|
+
return cleaned || "development-plan";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Extract a JSON object from an LLM text response, handling markdown fences or surrounding prose.
|
|
24
|
+
*/
|
|
25
|
+
export function extractJson(text) {
|
|
26
|
+
if (!text || typeof text !== "string") {
|
|
27
|
+
throw new Error("Empty model response");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const trimmed = text.trim();
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(trimmed);
|
|
33
|
+
} catch {
|
|
34
|
+
// Continue to fenced/substring extraction
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const fenceMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
38
|
+
if (fenceMatch) {
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(fenceMatch[1].trim());
|
|
41
|
+
} catch {
|
|
42
|
+
// Continue to brace extraction
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const firstBrace = trimmed.indexOf("{");
|
|
47
|
+
const lastBrace = trimmed.lastIndexOf("}");
|
|
48
|
+
if (firstBrace !== -1 && lastBrace > firstBrace) {
|
|
49
|
+
return JSON.parse(trimmed.slice(firstBrace, lastBrace + 1));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
throw new Error("Could not parse JSON from model response");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Collect lightweight workspace context from cwd for grounded planning.
|
|
57
|
+
*/
|
|
58
|
+
export function collectWorkspaceContext(cwd) {
|
|
59
|
+
if (!cwd) return "";
|
|
60
|
+
const lines = [`Working directory: ${cwd}`];
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
const entries = fs
|
|
64
|
+
.readdirSync(cwd, { withFileTypes: true })
|
|
65
|
+
.filter((entry) => !IGNORED_ENTRIES.has(entry.name))
|
|
66
|
+
.slice(0, 30)
|
|
67
|
+
.map((entry) => (entry.isDirectory() ? `${entry.name}/` : entry.name));
|
|
68
|
+
|
|
69
|
+
if (entries.length > 0) {
|
|
70
|
+
lines.push(`Top-level entries: ${entries.join(", ")}`);
|
|
71
|
+
}
|
|
72
|
+
} catch {
|
|
73
|
+
// Ignore unreadable directory
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
const pkgPath = path.join(cwd, "package.json");
|
|
78
|
+
if (fs.existsSync(pkgPath)) {
|
|
79
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
80
|
+
const pkgSummary = [
|
|
81
|
+
pkg.name ? `name=${pkg.name}` : null,
|
|
82
|
+
pkg.type ? `type=${pkg.type}` : null,
|
|
83
|
+
pkg.scripts ? `scripts=[${Object.keys(pkg.scripts).join(", ")}]` : null,
|
|
84
|
+
]
|
|
85
|
+
.filter(Boolean)
|
|
86
|
+
.join(", ");
|
|
87
|
+
if (pkgSummary) {
|
|
88
|
+
lines.push(`package.json: ${pkgSummary}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
// Ignore invalid package.json
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return lines.join("\n");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function resolvePlanPath(cwd, chosenPath) {
|
|
99
|
+
const trimmed = String(chosenPath || "").trim();
|
|
100
|
+
const withExt = path.extname(trimmed) ? trimmed : `${trimmed}.md`;
|
|
101
|
+
const absolutePath = path.isAbsolute(withExt) ? withExt : path.resolve(cwd, withExt);
|
|
102
|
+
const displayPath = path.relative(cwd, absolutePath) || path.basename(absolutePath);
|
|
103
|
+
return { absolutePath, displayPath };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function buildQuestionsMessages(prompt, workspaceContext) {
|
|
107
|
+
const systemPrompt = `You are a senior software architect helping a developer plan a task step by step.
|
|
108
|
+
Given the user's prompt and workspace context, produce a concise title and 3 to 5 clarifying questions that will meaningfully shape the implementation plan.
|
|
109
|
+
Each question should offer 2 to 4 concrete, practical options.
|
|
110
|
+
|
|
111
|
+
Return ONLY valid JSON matching this schema:
|
|
112
|
+
{
|
|
113
|
+
"title": "Short descriptive title",
|
|
114
|
+
"summary": "1-2 sentence understanding of the goal",
|
|
115
|
+
"questions": [
|
|
116
|
+
{
|
|
117
|
+
"question": "Clear question for the user?",
|
|
118
|
+
"options": ["Option A (recommended)", "Option B", "Option C"]
|
|
119
|
+
}
|
|
120
|
+
]
|
|
121
|
+
}`;
|
|
122
|
+
|
|
123
|
+
const userText = workspaceContext
|
|
124
|
+
? `Workspace Context:\n${workspaceContext}\n\nUser Prompt:\n${prompt}`
|
|
125
|
+
: `User Prompt:\n${prompt}`;
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
systemPrompt,
|
|
129
|
+
messages: [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }],
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function buildApproachesMessages(prompt, workspaceContext, qaPairs) {
|
|
134
|
+
const systemPrompt = `You are a senior software architect.
|
|
135
|
+
Based on the user's prompt, workspace context, and their answers to clarifying questions, propose 2 to 3 distinct implementation approaches.
|
|
136
|
+
|
|
137
|
+
Return ONLY valid JSON matching this schema:
|
|
138
|
+
{
|
|
139
|
+
"approaches": [
|
|
140
|
+
{
|
|
141
|
+
"name": "Short Approach Name",
|
|
142
|
+
"summary": "1 sentence summary of how it works",
|
|
143
|
+
"pros": "Key advantages",
|
|
144
|
+
"cons": "Trade-offs or risks",
|
|
145
|
+
"details": "Concrete technical notes"
|
|
146
|
+
}
|
|
147
|
+
]
|
|
148
|
+
}`;
|
|
149
|
+
|
|
150
|
+
const qaText =
|
|
151
|
+
qaPairs.length > 0
|
|
152
|
+
? qaPairs.map((item, idx) => `${idx + 1}. Q: ${item.question}\n A: ${item.answer}`).join("\n")
|
|
153
|
+
: "No additional clarifications provided.";
|
|
154
|
+
|
|
155
|
+
const userText = [
|
|
156
|
+
workspaceContext ? `Workspace Context:\n${workspaceContext}` : null,
|
|
157
|
+
`User Prompt:\n${prompt}`,
|
|
158
|
+
`Clarifying Decisions:\n${qaText}`,
|
|
159
|
+
]
|
|
160
|
+
.filter(Boolean)
|
|
161
|
+
.join("\n\n");
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
systemPrompt,
|
|
165
|
+
messages: [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }],
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function buildPlanMarkdownMessages(prompt, workspaceContext, title, qaPairs, selectedApproach) {
|
|
170
|
+
const systemPrompt = `You are a senior software engineer creating a clear, actionable Markdown development plan.
|
|
171
|
+
Write a well-structured Markdown document ready to be saved as a .md file and used directly for development.
|
|
172
|
+
|
|
173
|
+
Include these sections:
|
|
174
|
+
- # <Title>
|
|
175
|
+
- ## Overview
|
|
176
|
+
- ## Goals & Non-Goals
|
|
177
|
+
- ## Decisions & Requirements (incorporating the user's choices)
|
|
178
|
+
- ## Chosen Approach
|
|
179
|
+
- ## Architecture & File Changes
|
|
180
|
+
- ## Step-by-Step Implementation Tasks (use Markdown checkboxes \`- [ ]\`)
|
|
181
|
+
- ## Testing & Verification
|
|
182
|
+
- ## Risks & Edge Cases
|
|
183
|
+
|
|
184
|
+
Output ONLY the Markdown document (no wrapping code fences around the whole document).`;
|
|
185
|
+
|
|
186
|
+
const qaText =
|
|
187
|
+
qaPairs.length > 0
|
|
188
|
+
? qaPairs.map((item) => `- **${item.question}**: ${item.answer}`).join("\n")
|
|
189
|
+
: "- None specified";
|
|
190
|
+
|
|
191
|
+
const approachText =
|
|
192
|
+
typeof selectedApproach === "string"
|
|
193
|
+
? selectedApproach
|
|
194
|
+
: `**${selectedApproach.name}**: ${selectedApproach.summary}\nPros: ${selectedApproach.pros}\nCons: ${selectedApproach.cons}\nDetails: ${selectedApproach.details}`;
|
|
195
|
+
|
|
196
|
+
const userText = [
|
|
197
|
+
workspaceContext ? `Workspace Context:\n${workspaceContext}` : null,
|
|
198
|
+
`Plan Title: ${title}`,
|
|
199
|
+
`Original Prompt:\n${prompt}`,
|
|
200
|
+
`User Decisions:\n${qaText}`,
|
|
201
|
+
`Chosen Approach:\n${approachText}`,
|
|
202
|
+
]
|
|
203
|
+
.filter(Boolean)
|
|
204
|
+
.join("\n\n");
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
systemPrompt,
|
|
208
|
+
messages: [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }],
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function buildRefinePlanMessages(currentMarkdown, instructions) {
|
|
213
|
+
const systemPrompt = `You are a senior software engineer refining an existing Markdown development plan.
|
|
214
|
+
Apply the user's refinement instructions while keeping the document well-structured, actionable, and ready for development.
|
|
215
|
+
Output ONLY the updated Markdown document.`;
|
|
216
|
+
|
|
217
|
+
const userText = `Current Plan:\n${currentMarkdown}\n\nRefinement Instructions:\n${instructions}`;
|
|
218
|
+
|
|
219
|
+
return {
|
|
220
|
+
systemPrompt,
|
|
221
|
+
messages: [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }],
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function extractTextFromResponse(response) {
|
|
226
|
+
if (!response || response.stopReason === "aborted") {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
const text = (response.content || [])
|
|
230
|
+
.filter((c) => c && c.type === "text" && typeof c.text === "string")
|
|
231
|
+
.map((c) => c.text)
|
|
232
|
+
.join("\n")
|
|
233
|
+
.trim();
|
|
234
|
+
return text || null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function runModelStep(ctx, BorderedLoader, label, payload) {
|
|
238
|
+
const invokeModel = async (signal) => {
|
|
239
|
+
const response = await ctx.modelRegistry.complete(ctx.model, payload, signal ? { signal } : undefined);
|
|
240
|
+
return extractTextFromResponse(response);
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
if (ctx.mode === "tui" && typeof ctx.ui?.custom === "function" && BorderedLoader) {
|
|
244
|
+
return ctx.ui.custom((tui, theme, _kb, done) => {
|
|
245
|
+
const loader = new BorderedLoader(tui, theme, label);
|
|
246
|
+
loader.onAbort = () => done(null);
|
|
247
|
+
|
|
248
|
+
invokeModel(loader.signal)
|
|
249
|
+
.then(done)
|
|
250
|
+
.catch(() => done(null));
|
|
251
|
+
|
|
252
|
+
return loader;
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return invokeModel(undefined);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Execute the interactive step-by-step /plan workflow.
|
|
261
|
+
*/
|
|
262
|
+
export async function runPlanWorkflow(args, ctx, deps = {}) {
|
|
263
|
+
const { BorderedLoader } = deps;
|
|
264
|
+
|
|
265
|
+
if (!ctx.hasUI) {
|
|
266
|
+
ctx.ui?.notify?.("/plan requires an interactive UI", "error");
|
|
267
|
+
return { status: "error", reason: "no-ui" };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (!ctx.model) {
|
|
271
|
+
ctx.ui.notify("No model selected. Select a model before running /plan.", "error");
|
|
272
|
+
return { status: "error", reason: "no-model" };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
let prompt = String(args || "").trim();
|
|
276
|
+
if (!prompt) {
|
|
277
|
+
const entered = await ctx.ui.input("What would you like to plan?", "Describe the feature, refactor, or task...");
|
|
278
|
+
if (!entered || !entered.trim()) {
|
|
279
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
280
|
+
return { status: "cancelled" };
|
|
281
|
+
}
|
|
282
|
+
prompt = entered.trim();
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const workspaceContext = collectWorkspaceContext(ctx.cwd);
|
|
286
|
+
|
|
287
|
+
// Step 1: Generate clarifying questions
|
|
288
|
+
const questionsRaw = await runModelStep(
|
|
289
|
+
ctx,
|
|
290
|
+
BorderedLoader,
|
|
291
|
+
`Analyzing prompt with ${ctx.model.id}...`,
|
|
292
|
+
buildQuestionsMessages(prompt, workspaceContext),
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
if (!questionsRaw) {
|
|
296
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
297
|
+
return { status: "cancelled" };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
let parsedQuestions;
|
|
301
|
+
try {
|
|
302
|
+
parsedQuestions = extractJson(questionsRaw);
|
|
303
|
+
} catch {
|
|
304
|
+
ctx.ui.notify("Could not parse planning questions from model response.", "error");
|
|
305
|
+
return { status: "error", reason: "invalid-questions-json" };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const title = String(parsedQuestions?.title || prompt).trim();
|
|
309
|
+
const questions = Array.isArray(parsedQuestions?.questions) ? parsedQuestions.questions : [];
|
|
310
|
+
const qaPairs = [];
|
|
311
|
+
|
|
312
|
+
if (parsedQuestions?.summary) {
|
|
313
|
+
ctx.ui.notify(parsedQuestions.summary, "info");
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Step 1b: Walk through each question step by step
|
|
317
|
+
for (let i = 0; i < questions.length; i++) {
|
|
318
|
+
const q = questions[i];
|
|
319
|
+
const options = Array.isArray(q.options) ? q.options.map(String) : [];
|
|
320
|
+
const choice = await ctx.ui.select(`Step ${i + 1}/${questions.length}: ${q.question}`, [
|
|
321
|
+
...options,
|
|
322
|
+
"Custom answer...",
|
|
323
|
+
"Skip this question",
|
|
324
|
+
"Cancel planning",
|
|
325
|
+
]);
|
|
326
|
+
|
|
327
|
+
if (!choice || choice === "Cancel planning") {
|
|
328
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
329
|
+
return { status: "cancelled" };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (choice === "Skip this question") {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (choice === "Custom answer...") {
|
|
337
|
+
const custom = await ctx.ui.input(q.question, "Enter your answer...");
|
|
338
|
+
if (custom === undefined) {
|
|
339
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
340
|
+
return { status: "cancelled" };
|
|
341
|
+
}
|
|
342
|
+
if (custom.trim()) {
|
|
343
|
+
qaPairs.push({ question: q.question, answer: custom.trim() });
|
|
344
|
+
}
|
|
345
|
+
} else {
|
|
346
|
+
qaPairs.push({ question: q.question, answer: choice });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Step 2: Propose implementation approaches and let user choose
|
|
351
|
+
const approachesRaw = await runModelStep(
|
|
352
|
+
ctx,
|
|
353
|
+
BorderedLoader,
|
|
354
|
+
`Designing approaches with ${ctx.model.id}...`,
|
|
355
|
+
buildApproachesMessages(prompt, workspaceContext, qaPairs),
|
|
356
|
+
);
|
|
357
|
+
|
|
358
|
+
if (!approachesRaw) {
|
|
359
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
360
|
+
return { status: "cancelled" };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
let approaches = [];
|
|
364
|
+
try {
|
|
365
|
+
const parsedApproaches = extractJson(approachesRaw);
|
|
366
|
+
if (Array.isArray(parsedApproaches?.approaches)) {
|
|
367
|
+
approaches = parsedApproaches.approaches;
|
|
368
|
+
}
|
|
369
|
+
} catch {
|
|
370
|
+
// Fallback to a single default approach if JSON parsing fails
|
|
371
|
+
approaches = [];
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
let selectedApproach;
|
|
375
|
+
if (approaches.length > 0) {
|
|
376
|
+
const approachLabels = approaches.map((a) => `${a.name} — ${a.summary}`);
|
|
377
|
+
const approachChoice = await ctx.ui.select("Choose implementation approach:", [
|
|
378
|
+
...approachLabels,
|
|
379
|
+
"Provide custom approach...",
|
|
380
|
+
"Cancel planning",
|
|
381
|
+
]);
|
|
382
|
+
|
|
383
|
+
if (!approachChoice || approachChoice === "Cancel planning") {
|
|
384
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
385
|
+
return { status: "cancelled" };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (approachChoice === "Provide custom approach...") {
|
|
389
|
+
const customApproach = await ctx.ui.input("Describe your preferred approach:", "Enter approach...");
|
|
390
|
+
if (!customApproach || !customApproach.trim()) {
|
|
391
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
392
|
+
return { status: "cancelled" };
|
|
393
|
+
}
|
|
394
|
+
selectedApproach = customApproach.trim();
|
|
395
|
+
} else {
|
|
396
|
+
const idx = approachLabels.indexOf(approachChoice);
|
|
397
|
+
selectedApproach = approaches[idx] ?? approachChoice;
|
|
398
|
+
}
|
|
399
|
+
} else {
|
|
400
|
+
selectedApproach = "Standard pragmatic implementation based on user decisions.";
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Step 3: Generate Markdown development plan
|
|
404
|
+
let markdown = await runModelStep(
|
|
405
|
+
ctx,
|
|
406
|
+
BorderedLoader,
|
|
407
|
+
`Generating development plan with ${ctx.model.id}...`,
|
|
408
|
+
buildPlanMarkdownMessages(prompt, workspaceContext, title, qaPairs, selectedApproach),
|
|
409
|
+
);
|
|
410
|
+
|
|
411
|
+
if (!markdown) {
|
|
412
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
413
|
+
return { status: "cancelled" };
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Step 3b: Interactive review / edit / refine loop
|
|
417
|
+
while (true) {
|
|
418
|
+
const nextAction = await ctx.ui.select("Development plan ready. What would you like to do?", [
|
|
419
|
+
"Save Markdown file",
|
|
420
|
+
"Review / Edit in editor before saving",
|
|
421
|
+
"Refine plan with instructions",
|
|
422
|
+
"Cancel",
|
|
423
|
+
]);
|
|
424
|
+
|
|
425
|
+
if (!nextAction || nextAction === "Cancel") {
|
|
426
|
+
ctx.ui.notify("Planning cancelled.", "info");
|
|
427
|
+
return { status: "cancelled" };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
if (nextAction === "Review / Edit in editor before saving") {
|
|
431
|
+
const edited = await ctx.ui.editor("Review & edit development plan:", markdown);
|
|
432
|
+
if (edited !== undefined && edited.trim()) {
|
|
433
|
+
markdown = edited;
|
|
434
|
+
}
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (nextAction === "Refine plan with instructions") {
|
|
439
|
+
const instructions = await ctx.ui.input(
|
|
440
|
+
"Refinement instructions:",
|
|
441
|
+
"e.g. Add database schema details, split phase 2...",
|
|
442
|
+
);
|
|
443
|
+
if (!instructions || !instructions.trim()) {
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
const refined = await runModelStep(
|
|
447
|
+
ctx,
|
|
448
|
+
BorderedLoader,
|
|
449
|
+
`Refining plan with ${ctx.model.id}...`,
|
|
450
|
+
buildRefinePlanMessages(markdown, instructions.trim()),
|
|
451
|
+
);
|
|
452
|
+
if (refined) {
|
|
453
|
+
markdown = refined;
|
|
454
|
+
} else {
|
|
455
|
+
ctx.ui.notify("Refinement aborted; keeping previous draft.", "warning");
|
|
456
|
+
}
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
if (nextAction === "Save Markdown file") {
|
|
461
|
+
break;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Step 4: Choose output path and save .md file
|
|
466
|
+
const slug = slugify(title);
|
|
467
|
+
const defaultPlansPath = `plans/${slug}.md`;
|
|
468
|
+
const dotPiPlansPath = `.pi/plans/${slug}.md`;
|
|
469
|
+
|
|
470
|
+
let target = null;
|
|
471
|
+
while (!target) {
|
|
472
|
+
const pathChoice = await ctx.ui.select("Where should the development plan be saved?", [
|
|
473
|
+
defaultPlansPath,
|
|
474
|
+
dotPiPlansPath,
|
|
475
|
+
"PLAN.md",
|
|
476
|
+
"Custom path...",
|
|
477
|
+
"Cancel",
|
|
478
|
+
]);
|
|
479
|
+
|
|
480
|
+
if (!pathChoice || pathChoice === "Cancel") {
|
|
481
|
+
ctx.ui.notify("Planning cancelled (file not saved).", "info");
|
|
482
|
+
return { status: "cancelled" };
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
let chosenPath = pathChoice;
|
|
486
|
+
if (pathChoice === "Custom path...") {
|
|
487
|
+
const customPath = await ctx.ui.input("Enter Markdown file path:", defaultPlansPath);
|
|
488
|
+
if (!customPath || !customPath.trim()) {
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
chosenPath = customPath.trim();
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
const resolved = resolvePlanPath(ctx.cwd, chosenPath);
|
|
495
|
+
if (fs.existsSync(resolved.absolutePath)) {
|
|
496
|
+
const overwrite = await ctx.ui.confirm(
|
|
497
|
+
"File already exists",
|
|
498
|
+
`${resolved.displayPath} already exists. Overwrite it?`,
|
|
499
|
+
);
|
|
500
|
+
if (!overwrite) {
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
target = resolved;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
fs.mkdirSync(path.dirname(target.absolutePath), { recursive: true });
|
|
509
|
+
fs.writeFileSync(target.absolutePath, markdown.endsWith("\n") ? markdown : `${markdown}\n`, "utf8");
|
|
510
|
+
ctx.ui.notify(`Saved development plan to ${target.displayPath}`, "info");
|
|
511
|
+
|
|
512
|
+
if (typeof ctx.ui.confirm === "function" && typeof ctx.ui.setEditorText === "function") {
|
|
513
|
+
const loadPrompt = await ctx.ui.confirm(
|
|
514
|
+
"Ready for development",
|
|
515
|
+
`Load "Implement the development plan in ${target.displayPath}" into the editor?`,
|
|
516
|
+
);
|
|
517
|
+
if (loadPrompt) {
|
|
518
|
+
ctx.ui.setEditorText(`Implement the development plan in ${target.displayPath}`);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
return {
|
|
523
|
+
status: "saved",
|
|
524
|
+
path: target.absolutePath,
|
|
525
|
+
displayPath: target.displayPath,
|
|
526
|
+
markdown,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
extractJson,
|
|
9
|
+
resolvePlanPath,
|
|
10
|
+
runPlanWorkflow,
|
|
11
|
+
slugify,
|
|
12
|
+
} from "../src/planner.js";
|
|
13
|
+
|
|
14
|
+
function createTempDir() {
|
|
15
|
+
return fs.mkdtempSync(path.join(os.tmpdir(), "pi-prompt-planner-"));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
test("slugify creates safe kebab-case filenames", () => {
|
|
19
|
+
assert.equal(slugify("Build a REST API! (v2)"), "build-a-rest-api-v2");
|
|
20
|
+
assert.equal(slugify(" "), "development-plan");
|
|
21
|
+
assert.equal(slugify("A".repeat(100), 20), "a".repeat(20));
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("extractJson parses raw, fenced, and embedded JSON", () => {
|
|
25
|
+
assert.deepEqual(extractJson('{"title":"Auth"}'), { title: "Auth" });
|
|
26
|
+
assert.deepEqual(extractJson('```json\n{"title":"Auth"}\n```'), { title: "Auth" });
|
|
27
|
+
assert.deepEqual(extractJson('Here is the plan:\n{"title":"Auth"}\nDone.'), { title: "Auth" });
|
|
28
|
+
assert.throws(() => extractJson("not json at all"), /Could not parse JSON/);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("resolvePlanPath appends .md when missing and resolves relative to cwd", () => {
|
|
32
|
+
const cwd = path.resolve("/tmp/project");
|
|
33
|
+
const resolved = resolvePlanPath(cwd, "plans/my-feature");
|
|
34
|
+
assert.equal(resolved.absolutePath, path.join(cwd, "plans", "my-feature.md"));
|
|
35
|
+
assert.equal(resolved.displayPath, path.join("plans", "my-feature.md"));
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("runPlanWorkflow completes step-by-step choices and writes markdown file", async () => {
|
|
39
|
+
const cwd = createTempDir();
|
|
40
|
+
const notifications = [];
|
|
41
|
+
let editorText = "";
|
|
42
|
+
|
|
43
|
+
const selectQueue = [
|
|
44
|
+
"JWT + Refresh Tokens", // Q1 choice
|
|
45
|
+
"Custom answer...", // Q2 choice -> triggers input
|
|
46
|
+
"Modular Express — Clean separation of routes and services", // Approach choice
|
|
47
|
+
"Save Markdown file", // Review action
|
|
48
|
+
"plans/user-authentication.md", // Output path
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
const inputQueue = [
|
|
52
|
+
"PostgreSQL with Prisma", // Custom answer for Q2
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
const confirmQueue = [
|
|
56
|
+
true, // Load implement prompt into editor
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
let modelCall = 0;
|
|
60
|
+
const ctx = {
|
|
61
|
+
hasUI: true,
|
|
62
|
+
mode: "rpc",
|
|
63
|
+
cwd,
|
|
64
|
+
model: { id: "test-model" },
|
|
65
|
+
modelRegistry: {
|
|
66
|
+
async complete() {
|
|
67
|
+
modelCall += 1;
|
|
68
|
+
if (modelCall === 1) {
|
|
69
|
+
return {
|
|
70
|
+
stopReason: "stop",
|
|
71
|
+
content: [
|
|
72
|
+
{
|
|
73
|
+
type: "text",
|
|
74
|
+
text: JSON.stringify({
|
|
75
|
+
title: "User Authentication",
|
|
76
|
+
summary: "Add authentication endpoints and token handling.",
|
|
77
|
+
questions: [
|
|
78
|
+
{
|
|
79
|
+
question: "Which auth mechanism should we use?",
|
|
80
|
+
options: ["JWT + Refresh Tokens", "Session Cookies"],
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
question: "Which database will store users?",
|
|
84
|
+
options: ["SQLite", "PostgreSQL"],
|
|
85
|
+
},
|
|
86
|
+
],
|
|
87
|
+
}),
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
if (modelCall === 2) {
|
|
93
|
+
return {
|
|
94
|
+
stopReason: "stop",
|
|
95
|
+
content: [
|
|
96
|
+
{
|
|
97
|
+
type: "text",
|
|
98
|
+
text: JSON.stringify({
|
|
99
|
+
approaches: [
|
|
100
|
+
{
|
|
101
|
+
name: "Modular Express",
|
|
102
|
+
summary: "Clean separation of routes and services",
|
|
103
|
+
pros: "Testable",
|
|
104
|
+
cons: "More files",
|
|
105
|
+
details: "Use src/auth/",
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
name: "Single Middleware",
|
|
109
|
+
summary: "Minimal footprint",
|
|
110
|
+
pros: "Fast",
|
|
111
|
+
cons: "Harder to scale",
|
|
112
|
+
details: "Single file",
|
|
113
|
+
},
|
|
114
|
+
],
|
|
115
|
+
}),
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
stopReason: "stop",
|
|
122
|
+
content: [
|
|
123
|
+
{
|
|
124
|
+
type: "text",
|
|
125
|
+
text: "# User Authentication\n\n## Overview\nImplement auth.\n\n- [ ] Add user model\n- [ ] Add login endpoint",
|
|
126
|
+
},
|
|
127
|
+
],
|
|
128
|
+
};
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
ui: {
|
|
132
|
+
notify(msg, level) {
|
|
133
|
+
notifications.push({ msg, level });
|
|
134
|
+
},
|
|
135
|
+
async select() {
|
|
136
|
+
return selectQueue.shift();
|
|
137
|
+
},
|
|
138
|
+
async input() {
|
|
139
|
+
return inputQueue.shift();
|
|
140
|
+
},
|
|
141
|
+
async confirm() {
|
|
142
|
+
return confirmQueue.shift();
|
|
143
|
+
},
|
|
144
|
+
setEditorText(text) {
|
|
145
|
+
editorText = text;
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const result = await runPlanWorkflow("Build user authentication", ctx);
|
|
151
|
+
assert.equal(result.status, "saved");
|
|
152
|
+
|
|
153
|
+
const expectedFile = path.join(cwd, "plans", "user-authentication.md");
|
|
154
|
+
assert.equal(fs.existsSync(expectedFile), true);
|
|
155
|
+
const content = fs.readFileSync(expectedFile, "utf8");
|
|
156
|
+
assert.match(content, /# User Authentication/);
|
|
157
|
+
assert.match(content, /- \[ \] Add user model/);
|
|
158
|
+
assert.equal(editorText, `Implement the development plan in ${path.join("plans", "user-authentication.md")}`);
|
|
159
|
+
assert.ok(notifications.some((n) => n.level === "info" && n.msg.includes("Saved development plan")));
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test("runPlanWorkflow supports refining and editing before saving", async () => {
|
|
163
|
+
const cwd = createTempDir();
|
|
164
|
+
|
|
165
|
+
const selectQueue = [
|
|
166
|
+
"Simple CLI", // Approach
|
|
167
|
+
"Refine plan with instructions", // First review action
|
|
168
|
+
"Review / Edit in editor before saving", // Second review action
|
|
169
|
+
"Save Markdown file", // Third review action
|
|
170
|
+
"PLAN.md", // Output path
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
const inputQueue = ["Add unit test checklist"];
|
|
174
|
+
let modelCall = 0;
|
|
175
|
+
|
|
176
|
+
const ctx = {
|
|
177
|
+
hasUI: true,
|
|
178
|
+
mode: "rpc",
|
|
179
|
+
cwd,
|
|
180
|
+
model: { id: "test-model" },
|
|
181
|
+
modelRegistry: {
|
|
182
|
+
async complete() {
|
|
183
|
+
modelCall += 1;
|
|
184
|
+
if (modelCall === 1) {
|
|
185
|
+
return {
|
|
186
|
+
stopReason: "stop",
|
|
187
|
+
content: [{ type: "text", text: JSON.stringify({ title: "CLI Tool", questions: [] }) }],
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
if (modelCall === 2) {
|
|
191
|
+
return {
|
|
192
|
+
stopReason: "stop",
|
|
193
|
+
content: [
|
|
194
|
+
{
|
|
195
|
+
type: "text",
|
|
196
|
+
text: JSON.stringify({
|
|
197
|
+
approaches: [{ name: "Simple CLI", summary: "Node script", pros: "Fast", cons: "Basic", details: "" }],
|
|
198
|
+
}),
|
|
199
|
+
},
|
|
200
|
+
],
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
if (modelCall === 3) {
|
|
204
|
+
return {
|
|
205
|
+
stopReason: "stop",
|
|
206
|
+
content: [{ type: "text", text: "# CLI Tool\n\n- [ ] Build parser" }],
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
stopReason: "stop",
|
|
211
|
+
content: [{ type: "text", text: "# CLI Tool\n\n- [ ] Build parser\n- [ ] Add unit tests" }],
|
|
212
|
+
};
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
ui: {
|
|
216
|
+
notify() {},
|
|
217
|
+
async select() {
|
|
218
|
+
return selectQueue.shift();
|
|
219
|
+
},
|
|
220
|
+
async input() {
|
|
221
|
+
return inputQueue.shift();
|
|
222
|
+
},
|
|
223
|
+
async editor(_title, initial) {
|
|
224
|
+
return `${initial}\n- [ ] Manual edit task`;
|
|
225
|
+
},
|
|
226
|
+
async confirm() {
|
|
227
|
+
return false;
|
|
228
|
+
},
|
|
229
|
+
setEditorText() {},
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const result = await runPlanWorkflow("Build a CLI tool", ctx);
|
|
234
|
+
assert.equal(result.status, "saved");
|
|
235
|
+
const saved = fs.readFileSync(path.join(cwd, "PLAN.md"), "utf8");
|
|
236
|
+
assert.match(saved, /Add unit tests/);
|
|
237
|
+
assert.match(saved, /Manual edit task/);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
test("runPlanWorkflow handles missing model and cancellation", async () => {
|
|
241
|
+
const notifications = [];
|
|
242
|
+
const noModelResult = await runPlanWorkflow("Test", {
|
|
243
|
+
hasUI: true,
|
|
244
|
+
model: null,
|
|
245
|
+
ui: {
|
|
246
|
+
notify(msg, level) {
|
|
247
|
+
notifications.push({ msg, level });
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
assert.equal(noModelResult.status, "error");
|
|
252
|
+
assert.equal(noModelResult.reason, "no-model");
|
|
253
|
+
|
|
254
|
+
const cancelled = await runPlanWorkflow("", {
|
|
255
|
+
hasUI: true,
|
|
256
|
+
model: { id: "m" },
|
|
257
|
+
ui: {
|
|
258
|
+
notify() {},
|
|
259
|
+
async input() {
|
|
260
|
+
return "";
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
});
|
|
264
|
+
assert.equal(cancelled.status, "cancelled");
|
|
265
|
+
});
|