@andares/pi-toolkits 0.12.3 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +100 -15
  2. package/README.zh-CN.md +94 -14
  3. package/package.json +19 -10
  4. package/src/features/ask/index.ts +6 -0
  5. package/src/features/init/apply.ts +32 -12
  6. package/src/features/init/audit-uat.test.ts +103 -0
  7. package/src/features/init/audit.ts +148 -0
  8. package/src/features/init/detect.ts +4 -0
  9. package/src/features/init/index.ts +47 -2
  10. package/src/features/init/plan.ts +11 -0
  11. package/src/features/init/refresh.test.ts +208 -0
  12. package/src/features/init/refresh.ts +255 -0
  13. package/src/features/init/spec.ts +20 -0
  14. package/src/features/init/templates/agents-skeleton.md +2 -0
  15. package/src/features/init/templates/uat-readme.md +53 -0
  16. package/src/features/init/templates/workflow-block.md +21 -0
  17. package/src/features/init/templates.test.ts +3 -1
  18. package/src/features/init/templates.ts +2 -0
  19. package/src/features/init/types.ts +12 -1
  20. package/src/features/permission/index.ts +32 -0
  21. package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
  22. package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
  23. package/src/features/plan/assets/index.html +14 -0
  24. package/src/features/plan/assets.test.ts +64 -0
  25. package/src/features/plan/blocks.test.ts +77 -0
  26. package/src/features/plan/blocks.ts +153 -0
  27. package/src/features/plan/diff.test.ts +144 -0
  28. package/src/features/plan/diff.ts +193 -0
  29. package/src/features/plan/feedback.test.ts +233 -0
  30. package/src/features/plan/feedback.ts +182 -0
  31. package/src/features/plan/index.test.ts +385 -0
  32. package/src/features/plan/index.ts +433 -0
  33. package/src/features/plan/prompt.test.ts +91 -0
  34. package/src/features/plan/prompt.ts +110 -0
  35. package/src/features/plan/render.test.ts +94 -0
  36. package/src/features/plan/render.ts +131 -0
  37. package/src/features/plan/server.test.ts +374 -0
  38. package/src/features/plan/server.ts +272 -0
  39. package/src/features/plan/store.test.ts +145 -0
  40. package/src/features/plan/store.ts +244 -0
  41. package/src/features/review/index.ts +54 -28
  42. package/src/features/review/review.test.ts +46 -1
  43. package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
  44. package/src/features/uat/assets/index-DCBQCsli.js +1 -0
  45. package/src/features/uat/assets/index.html +14 -0
  46. package/src/features/uat/constants.ts +23 -0
  47. package/src/features/uat/index.test.ts +404 -0
  48. package/src/features/uat/index.ts +329 -0
  49. package/src/features/uat/item-tool.ts +280 -0
  50. package/src/features/uat/ledger.test.ts +249 -0
  51. package/src/features/uat/ledger.ts +504 -0
  52. package/src/features/uat/prompt.ts +78 -0
  53. package/src/features/uat/record-tool.ts +167 -0
  54. package/src/features/uat/records.test.ts +145 -0
  55. package/src/features/uat/records.ts +268 -0
  56. package/src/features/uat/server.ts +181 -0
  57. package/src/features/uat/state.test.ts +41 -0
  58. package/src/features/uat/state.ts +67 -0
  59. package/src/index.ts +10 -1
  60. package/src/lib/ask-control.ts +25 -0
  61. package/src/lib/opener.test.ts +72 -0
  62. package/src/lib/opener.ts +121 -0
  63. package/src/lib/permission-control.ts +39 -0
  64. package/src/lib/startup.test.ts +1 -1
  65. package/src/lib/web-review.ts +341 -0
@@ -0,0 +1,433 @@
1
+ /**
2
+ * ask-plan — plan mode with a browser review round.
3
+ *
4
+ * The flow: `/ask-plan` opens a planning phase (read tools, questions, markdown
5
+ * writes only), the agent writes a spec and calls `plan_submit`, the review
6
+ * server opens the page in the operator's browser, annotations come back as a
7
+ * message, and the loop repeats until the plan is approved — then the phase ends
8
+ * and the agent implements.
9
+ *
10
+ * Three properties are load-bearing:
11
+ * - `plan_submit` returns immediately. Waiting for the decision inside the
12
+ * tool would pin the agent for as long as the operator takes to read; the
13
+ * decision arrives later as a normal user message instead.
14
+ * - the decision always carries the annotations. Approve and deny only choose
15
+ * the next step (implement vs revise); notes written for an approval still
16
+ * reach the model.
17
+ * - this feature never touches the model or its configuration:
18
+ * plannotator's habit of switching models silently is the reason this one
19
+ * is written from scratch.
20
+ */
21
+ import { readFileSync, existsSync } from "node:fs";
22
+ import { isAbsolute, join, relative, resolve } from "node:path";
23
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
24
+ import { Type } from "typebox";
25
+ import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
26
+ import type { GateHub } from "../../lib/gates.js";
27
+ import { getPermissionControl, type PermissionSnapshot } from "../../lib/permission-control.js";
28
+ import { getAskControl } from "../../lib/ask-control.js";
29
+ import { canonicalize, isWithin } from "../permission/paths.js";
30
+ import { parseCommandUnits } from "../permission/units.js";
31
+ import { buildFeedbackMarkdown } from "./feedback.js";
32
+ import { openInBrowser } from "../../lib/opener.js";
33
+ import { buildPlanKickoff, buildPlanSystemPrompt } from "./prompt.js";
34
+ import { renderBlockHtml } from "./render.js";
35
+ import { buildPlanState, startPlanServer, type PlanServerHandle } from "./server.js";
36
+ import {
37
+ appendPlanVersion,
38
+ createPlanSession,
39
+ latestVersion,
40
+ planSlug,
41
+ readVersionText,
42
+ type PlanSession,
43
+ } from "./store.js";
44
+
45
+ export const PLAN_COMMAND = "ask-plan";
46
+ export const PLAN_SUBMIT_TOOL = "plan_submit";
47
+
48
+ /** Files the planning phase may write: project markdown, nothing else. */
49
+ function isMarkdownPath(path: string): boolean {
50
+ return /\.mdx?$/i.test(path);
51
+ }
52
+
53
+ /** Resolve a markdown path inside the workspace; anything else is rejected. */
54
+ function planMarkdownPath(path: string, cwd: string): string | undefined {
55
+ if (path === "" || !isMarkdownPath(path)) return undefined;
56
+ const absolute = canonicalize(isAbsolute(path) ? path : resolve(cwd, path));
57
+ if (absolute === cwd || !isWithin(cwd, absolute)) return undefined;
58
+ return absolute;
59
+ }
60
+
61
+ function samePermissionSnapshot(a: PermissionSnapshot, b: PermissionSnapshot): boolean {
62
+ return (
63
+ a.enabled === b.enabled &&
64
+ a.modes.inRead === b.modes.inRead &&
65
+ a.modes.inWrite === b.modes.inWrite &&
66
+ a.modes.outRead === b.modes.outRead &&
67
+ a.modes.outWrite === b.modes.outWrite
68
+ );
69
+ }
70
+
71
+ function sessionIdOf(ctx: ExtensionContext): string {
72
+ try {
73
+ return ctx.sessionManager.getSessionId();
74
+ } catch {
75
+ return `pid-${process.pid}`;
76
+ }
77
+ }
78
+
79
+ const PLAN_SUBMIT_PARAMS = Type.Object({
80
+ path: Type.Optional(
81
+ Type.String({
82
+ description:
83
+ 'Spec file to submit, relative to the workspace root (default: the file chosen when plan mode started, e.g. "specs/ask-plan.md"). Write the file first — plan_submit reads it from disk.',
84
+ }),
85
+ ),
86
+ });
87
+
88
+ export interface PlanOptions {
89
+ /** `<agent-dir>`: review history lives at `<agentDir>/ask-plan/` (default: the host's). */
90
+ agentDir?: string;
91
+ /** Opening the browser is injectable so tests never spawn one. */
92
+ openBrowser?: (url: string) => unknown;
93
+ /** Milliseconds between a decision and closing the review server (tests inject 0). */
94
+ closeDelayMs?: number;
95
+ /** Port search starts here; the review server walks upward. */
96
+ portStart?: number;
97
+ }
98
+
99
+ export function registerPlan(pi: ExtensionAPI, gates: GateHub, options: PlanOptions = {}): void {
100
+ const open = options.openBrowser ?? openInBrowser;
101
+ const agentDir = options.agentDir ?? getAgentDir();
102
+
103
+ let active = false;
104
+ let session: PlanSession | undefined;
105
+ let server: PlanServerHandle | undefined;
106
+ let permissionBefore: PermissionSnapshot | undefined;
107
+ let permissionDuring: PermissionSnapshot | undefined;
108
+ let specPath: string | undefined;
109
+ let cwd = process.cwd();
110
+ let ctxRef: ExtensionContext | undefined;
111
+ let planSessionId: string | undefined;
112
+
113
+ function closeServer(): void {
114
+ if (!server) return;
115
+ void server.close();
116
+ server = undefined;
117
+ }
118
+
119
+ function toolSetWithSubmit(): string[] {
120
+ const tools = pi.getActiveTools().filter((name) => name !== PLAN_SUBMIT_TOOL);
121
+ return [...tools, PLAN_SUBMIT_TOOL];
122
+ }
123
+
124
+ function toolSetWithoutSubmit(): string[] {
125
+ return pi.getActiveTools().filter((name) => name !== PLAN_SUBMIT_TOOL);
126
+ }
127
+
128
+ function leave(ctx: ExtensionContext, reason: string): void {
129
+ if (!active) return;
130
+ active = false;
131
+ closeServer();
132
+ pi.setActiveTools(toolSetWithoutSubmit());
133
+ const control = getPermissionControl();
134
+ const current = control?.snapshot();
135
+ // Restore only if the operator has not changed the policy mid-plan. A
136
+ // manual `/ask-perm` during planning is newer intent and must win.
137
+ if (
138
+ control &&
139
+ permissionBefore &&
140
+ permissionDuring &&
141
+ current &&
142
+ samePermissionSnapshot(current, permissionDuring)
143
+ ) {
144
+ control.restore(ctx, permissionBefore);
145
+ }
146
+ permissionBefore = undefined;
147
+ permissionDuring = undefined;
148
+ planSessionId = undefined;
149
+ ctx.ui.notify(`ask-plan: ${reason}`, "info");
150
+ }
151
+
152
+ /** Compose the message the model receives for one decision. */
153
+ function decisionMessage(version: number): string {
154
+ if (!session) return "";
155
+ const current = session.versions.find((candidate) => candidate.n === version);
156
+ if (!current) return "";
157
+ const previous = session.versions.find((candidate) => candidate.n === version - 1);
158
+ const approved = current.decision?.action === "approve";
159
+ return buildFeedbackMarkdown({
160
+ decision: approved ? "approve" : "deny",
161
+ version,
162
+ totalVersions: latestVersion(session).n,
163
+ blocks: current.blocks,
164
+ diff: current.diff,
165
+ previousBlocks: previous?.blocks ?? [],
166
+ global: current.annotations.global,
167
+ perBlock: current.annotations.blocks,
168
+ // Approval quotes the reviewed snapshot, not the file's current bytes:
169
+ // the model may have kept editing after submitting this revision.
170
+ planPath: current.source ?? specPath,
171
+ planText: readApprovedText(version) ?? current.blocks.map((block) => block.text).join("\n\n"),
172
+ // During planning the tool is intentionally inactive. Recommend it on
173
+ // approval only when the project has the framework and the tool exists.
174
+ recordTool:
175
+ pi.getAllTools().some((tool) => tool.name === "record_change") &&
176
+ existsSync(join(cwd, ".agents/framework/state.toml")),
177
+ });
178
+ }
179
+
180
+ /** Text of one revision, or undefined when the snapshot file is unreadable. */
181
+ function readApprovedText(version: number): string | undefined {
182
+ if (!session) return undefined;
183
+ try {
184
+ return readVersionText(session, version);
185
+ } catch {
186
+ return undefined;
187
+ }
188
+ }
189
+
190
+ async function handleDecision(
191
+ decision: { action: "approve" | "deny"; version: number },
192
+ ctx: ExtensionContext,
193
+ ): Promise<void> {
194
+ // The operator may leave plan mode, or switch sessions, during the short
195
+ // close delay. A stale decision must not resurrect implementation or send
196
+ // an empty message into the new phase.
197
+ if (!active) return;
198
+ const message = decisionMessage(decision.version);
199
+ if (decision.action === "approve") {
200
+ // Leave the phase before the message goes out: the implementation
201
+ // turn must not run under the planning gates.
202
+ leave(ctx, "plan approved — implementing.");
203
+ } else {
204
+ ctx.ui.notify("ask-plan: feedback sent — the agent will revise the plan.", "info");
205
+ }
206
+ pi.sendUserMessage(message);
207
+ }
208
+
209
+ // ── Command ────────────────────────────────────────────────────────────
210
+
211
+ pi.registerCommand(PLAN_COMMAND, {
212
+ description:
213
+ "Plan first: research, write a spec, review it in the browser with block annotations, then implement after approval. `off` leaves the phase, `open` re-opens the review.",
214
+ handler: async (args: string, ctx: ExtensionContext) => {
215
+ const arg = args.trim();
216
+ ctxRef = ctx;
217
+ cwd = canonicalize(ctx.cwd || process.cwd());
218
+
219
+ if (arg === "off") {
220
+ if (!active) {
221
+ ctx.ui.notify("ask-plan: not in plan mode.", "info");
222
+ return;
223
+ }
224
+ leave(ctx, specPath ? `plan mode off — draft left at ${specPath}.` : "plan mode off.");
225
+ return;
226
+ }
227
+
228
+ if (arg === "open") {
229
+ if (!server) {
230
+ ctx.ui.notify("ask-plan: no review is open — submit a plan first.", "warning");
231
+ return;
232
+ }
233
+ open(server.url);
234
+ ctx.ui.notify(`ask-plan: ${server.url}`, "info");
235
+ return;
236
+ }
237
+
238
+ if (active) {
239
+ ctx.ui.notify("ask-plan: already planning. Use `off` to leave the phase.", "warning");
240
+ return;
241
+ }
242
+
243
+ const slug = planSlug(arg || "plan");
244
+ specPath = `specs/${slug}.md`;
245
+ session = undefined;
246
+ planSessionId = sessionIdOf(ctx);
247
+ const permission = getPermissionControl();
248
+ permissionBefore = permission?.snapshot();
249
+ permission?.enableDefaults(ctx);
250
+ permissionDuring = permission?.snapshot();
251
+ // Plan mode is intentionally less restrictive than ask mode. Let ask
252
+ // restore its own tool snapshot before we add plan_submit.
253
+ if (getAskControl()?.isActive()) getAskControl()?.exit(ctx);
254
+ active = true;
255
+ pi.setActiveTools(toolSetWithSubmit());
256
+ ctx.ui.notify(
257
+ `ask-plan: planning. Write the spec to ${specPath}, then call ${PLAN_SUBMIT_TOOL}.`,
258
+ "info",
259
+ );
260
+ pi.sendUserMessage(buildPlanKickoff(arg || undefined));
261
+ },
262
+ });
263
+
264
+ // ── Tool ───────────────────────────────────────────────────────────────
265
+
266
+ pi.registerTool<typeof PLAN_SUBMIT_PARAMS, { version?: number; url?: string }>({
267
+ name: PLAN_SUBMIT_TOOL,
268
+ label: "Submit plan for review",
269
+ description:
270
+ "Submit the spec file you just wrote so the operator can review and annotate it in the browser. Returns immediately; the decision arrives as a new message.",
271
+ promptSnippet: "Submit the plan for browser review (plan mode only)",
272
+ promptGuidelines: [
273
+ "Call plan_submit only after the spec file on disk is the version you want reviewed.",
274
+ "After submitting, end your turn: the operator's annotations arrive as a new message.",
275
+ "Never submit a file you have not written — plan_submit reads the file from disk.",
276
+ ],
277
+ parameters: PLAN_SUBMIT_PARAMS,
278
+ defaultActive: false,
279
+ async execute(_toolCallId: string, params: { path?: string }) {
280
+ if (!active) {
281
+ return {
282
+ content: [{ type: "text" as const, text: "Plan mode is off — use /ask-plan first." }],
283
+ details: {},
284
+ };
285
+ }
286
+ const target = params.path ?? specPath ?? "specs/plan.md";
287
+ const absolute = planMarkdownPath(target, cwd);
288
+ if (!absolute) {
289
+ return {
290
+ content: [
291
+ {
292
+ type: "text" as const,
293
+ text: `Submit only a markdown file inside the workspace (got ${target}).`,
294
+ },
295
+ ],
296
+ details: {},
297
+ };
298
+ }
299
+ let text: string;
300
+ try {
301
+ text = readFileSync(absolute, "utf8");
302
+ } catch {
303
+ return {
304
+ content: [
305
+ {
306
+ type: "text" as const,
307
+ text: `Cannot read ${target}. Write the spec file first, then call plan_submit again.`,
308
+ },
309
+ ],
310
+ details: {},
311
+ };
312
+ }
313
+ const source = relative(cwd, absolute) || target;
314
+ if (!session) {
315
+ session = createPlanSession({
316
+ agentDir,
317
+ slug: planSlug(source.replace(/\.mdx?$/i, "").replace(/^specs\//, "")),
318
+ text,
319
+ source,
320
+ });
321
+ } else {
322
+ appendPlanVersion(session, { text, source });
323
+ }
324
+ const version = latestVersion(session);
325
+ if (!server) {
326
+ server = await startPlanServer({
327
+ session,
328
+ render: renderBlockHtml,
329
+ portStart: options.portStart,
330
+ closeDelayMs: options.closeDelayMs,
331
+ onDecision: ({ action, version: decidedVersion }) => {
332
+ const ctx = ctxRef;
333
+ if (ctx) void handleDecision({ action, version: decidedVersion }, ctx);
334
+ },
335
+ });
336
+ open(server.url);
337
+ ctxRef?.ui.notify(`ask-plan: review open at ${server.url}`, "info");
338
+ } else {
339
+ server.broadcast("revision", { version: version.n });
340
+ }
341
+ const changed = buildPlanState(session, version.n).items.filter(
342
+ (item) => item.status !== "unchanged",
343
+ ).length;
344
+ return {
345
+ content: [
346
+ {
347
+ type: "text" as const,
348
+ text:
349
+ `Submitted v${version.n} of ${session.versions.length} (${changed} changed blocks). ` +
350
+ `Review: ${server.url}\nEnd your turn now — the decision arrives as a new message.`,
351
+ },
352
+ ],
353
+ details: { version: version.n, url: server.url },
354
+ };
355
+ },
356
+ });
357
+
358
+ // ── Gate: the planning phase writes markdown only ──────────────────────
359
+
360
+ gates.register({
361
+ name: "plan",
362
+ order: 5,
363
+ evaluate(event: ToolCallEvent) {
364
+ if (!active) return undefined;
365
+ if (event.toolName === "bash") {
366
+ // The promise is "plan mode does not implement", and a redirect is
367
+ // implementation just as much as `write` is. Temp paths outside the
368
+ // workspace stay allowed; opaque units are left to the permission gate,
369
+ // which already fails closed on them (no double prompt here).
370
+ const command = typeof event.input.command === "string" ? event.input.command : "";
371
+ if (command === "") return undefined;
372
+ for (const unit of parseCommandUnits(command, cwd)) {
373
+ if (unit.opaque) continue;
374
+ for (const target of unit.targets) {
375
+ if (target.effect !== "write") continue;
376
+ const absolute = canonicalize(target.path);
377
+ if (absolute === cwd || !isWithin(cwd, absolute)) continue;
378
+ if (/\.mdx?$/i.test(absolute)) continue;
379
+ return {
380
+ kind: "block" as const,
381
+ reason:
382
+ `Plan mode only writes markdown while the plan is under review (blocked bash write to ${target.path}). ` +
383
+ "Implement the change after the plan is approved; write the spec file instead.",
384
+ };
385
+ }
386
+ }
387
+ return undefined;
388
+ }
389
+ if (event.toolName !== "write" && event.toolName !== "edit") return undefined;
390
+ const path = typeof event.input.path === "string" ? event.input.path : "";
391
+ if (planMarkdownPath(path, cwd) !== undefined) return undefined;
392
+ return {
393
+ kind: "block" as const,
394
+ reason:
395
+ "Plan mode only writes markdown (.md/.mdx) while the plan is under review. " +
396
+ "Implement the change after the plan is approved, or write the spec file instead.",
397
+ };
398
+ },
399
+ });
400
+
401
+ // ── System prompt while planning ───────────────────────────────────────
402
+
403
+ pi.on("before_agent_start", (event) => {
404
+ if (!active) return undefined;
405
+ pi.setActiveTools(toolSetWithSubmit());
406
+ return {
407
+ systemPrompt: `${event.systemPrompt}\n\n${buildPlanSystemPrompt({
408
+ questionTool: pi.getActiveTools().includes("ask_user_question"),
409
+ })}`,
410
+ };
411
+ });
412
+
413
+ pi.on("session_shutdown", () => {
414
+ closeServer();
415
+ });
416
+
417
+ pi.on("session_start", (_event, ctx) => {
418
+ const nextSessionId = sessionIdOf(ctx);
419
+ if (nextSessionId === planSessionId) return;
420
+ // A different session must not inherit this session's gates, review server
421
+ // or permission snapshot. Permission's own session_start has already reset
422
+ // its state, so do not restore the old snapshot here.
423
+ active = false;
424
+ session = undefined;
425
+ permissionBefore = undefined;
426
+ permissionDuring = undefined;
427
+ planSessionId = undefined;
428
+ specPath = undefined;
429
+ ctxRef = ctx;
430
+ closeServer();
431
+ pi.setActiveTools(toolSetWithoutSubmit());
432
+ });
433
+ }
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ buildPlanKickoff,
4
+ buildPlanSystemPrompt,
5
+ INTERVIEW_GUIDE,
6
+ PLAN_MODE_BANNER,
7
+ SPEC_FRAMEWORK_GUIDE,
8
+ } from "./prompt.js";
9
+
10
+ describe("plan mode prompt", () => {
11
+ it("states what the phase allows and how a turn may end", () => {
12
+ expect(PLAN_MODE_BANNER).toContain("[ASK-PLAN — PLANNING]");
13
+ expect(PLAN_MODE_BANNER).toContain("writing/editing\nmarkdown files");
14
+ expect(PLAN_MODE_BANNER).toContain("Not allowed: editing other files");
15
+ expect(PLAN_MODE_BANNER).toContain("plan_submit");
16
+ expect(PLAN_MODE_BANNER).toContain("End every turn with either a question or a plan_submit call");
17
+ });
18
+
19
+ it("asks in rounds instead of guessing, and never names a tool the session lacks", () => {
20
+ expect(INTERVIEW_GUIDE).toContain("in rounds");
21
+ expect(INTERVIEW_GUIDE).toContain("Do not ask what you can read");
22
+ expect(buildPlanSystemPrompt({ questionTool: false })).toContain("ask in plain text");
23
+ expect(buildPlanSystemPrompt({ questionTool: true })).toContain("`ask_user_question` is available");
24
+ });
25
+
26
+ it("gives the spec framework in reading order", () => {
27
+ const order = [
28
+ "# SPEC: <name>",
29
+ "## Context",
30
+ "## Goal",
31
+ "## Scope",
32
+ "## Decisions",
33
+ "## Approach",
34
+ "## Data & contracts",
35
+ "## Files",
36
+ "## Milestones",
37
+ "## Verification",
38
+ "## Risks",
39
+ "## Open questions",
40
+ ];
41
+ let cursor = -1;
42
+ for (const heading of order) {
43
+ const index = SPEC_FRAMEWORK_GUIDE.indexOf(heading);
44
+ expect(index, `${heading} missing`).toBeGreaterThan(-1);
45
+ expect(index, `${heading} out of order`).toBeGreaterThan(cursor);
46
+ cursor = index;
47
+ }
48
+ });
49
+
50
+ it("explains paragraph-level review — the part that makes block annotations usable", () => {
51
+ expect(SPEC_FRAMEWORK_GUIDE).toContain("The operator annotates **blocks**");
52
+ expect(SPEC_FRAMEWORK_GUIDE).toContain("one idea per paragraph");
53
+ expect(SPEC_FRAMEWORK_GUIDE).toContain("no blank lines between items");
54
+ expect(SPEC_FRAMEWORK_GUIDE).toContain("fenced code blocks stay whole");
55
+ });
56
+
57
+ it("tells the model that notes arrive on approval too, and that a full rewrite ruins the diff", () => {
58
+ expect(SPEC_FRAMEWORK_GUIDE).toContain("Annotations arrive whatever the decision");
59
+ expect(SPEC_FRAMEWORK_GUIDE).toContain("change only the blocks that were annotated");
60
+ expect(SPEC_FRAMEWORK_GUIDE).toContain("every block turns red");
61
+ });
62
+
63
+ it("combines banner and guide without dropping either", () => {
64
+ const prompt = buildPlanSystemPrompt();
65
+ expect(prompt).toContain(PLAN_MODE_BANNER);
66
+ expect(prompt).toContain(SPEC_FRAMEWORK_GUIDE);
67
+ });
68
+
69
+ it("never tells the model which language to write in", () => {
70
+ // Framework prompts are authored in English, which is our choice of
71
+ // language for the prompt — not an instruction about the spec. The spec
72
+ // follows the operator's own language, so any directive would be a bug.
73
+ const prompt = buildPlanSystemPrompt().toLowerCase();
74
+ for (const banned of ["in english", "in chinese", "language", "write in"]) {
75
+ expect(prompt, `prompt must not mention "${banned}"`).not.toContain(banned);
76
+ }
77
+ });
78
+ });
79
+
80
+ describe("buildPlanKickoff", () => {
81
+ it("names the task when one was given", () => {
82
+ const kickoff = buildPlanKickoff("build /ask-plan");
83
+ expect(kickoff).toContain("Task: build /ask-plan");
84
+ expect(kickoff).toContain("plan_submit");
85
+ });
86
+
87
+ it("falls back to the session discussion", () => {
88
+ expect(buildPlanKickoff(undefined)).toContain("the work we have been discussing in this session");
89
+ expect(buildPlanKickoff(" ")).toContain("the work we have been discussing in this session");
90
+ });
91
+ });
@@ -0,0 +1,110 @@
1
+ /**
2
+ * plan prompt — what the agent is told when plan mode opens.
3
+ *
4
+ * Two parts, both injected as a system-prompt block on every plan-mode turn:
5
+ *
6
+ * 1. the framing: what the phase allows (write markdown, read everything,
7
+ * ask questions) and the one rule that has no exception — the turn ends by
8
+ * asking a question or by submitting the plan, never by going quiet;
9
+ * 2. the spec framework: a skill-style guide to the shape of a reviewable
10
+ * plan. It is deliberately a *default* shape, not a template to fill in:
11
+ * the operator reviews paragraphs, so the guide also explains how to write
12
+ * for paragraph-level review (one idea per block, headings on their own
13
+ * line, no blank lines inside a list) — that is the part models get wrong
14
+ * and the part that makes the browser review usable.
15
+ *
16
+ * Kept as a string constant rather than a bundled SKILL.md on purpose: a skill
17
+ * description would be paid for on every request in every session, while this
18
+ * text is only ever sent while plan mode is on.
19
+ */
20
+
21
+ export const PLAN_MODE_BANNER = [
22
+ "[ASK-PLAN — PLANNING]",
23
+ "You are planning this change with the operator before any code is written.",
24
+ "",
25
+ "Allowed now: reading tools, bash for inspection, and writing/editing",
26
+ "markdown files inside the project. Not allowed: editing other files, destructive commands,",
27
+ "or starting the implementation — that begins only after the plan is approved.",
28
+ "",
29
+ "Loop: explore → ask what the code cannot tell you → write the spec file → plan_submit.",
30
+ "End every turn with either a question or a plan_submit call. Do not end it silently.",
31
+ ].join("\n");
32
+
33
+ /**
34
+ * The interview half of planning. Deliberately capability-neutral: the session's
35
+ * question tool is a third-party extension in most installs, so the prompt says
36
+ * "the session's question tool" and the caller adds a line about availability —
37
+ * naming a tool the harness does not have sends the model into an empty call.
38
+ */
39
+ export const INTERVIEW_GUIDE = [
40
+ "[ASK-PLAN — INTERVIEW]",
41
+ "Settle ambiguity by asking, in rounds, before you write the spec — not after.",
42
+ "Use the session's question tool when one is available; otherwise ask in plain text and wait.",
43
+ "One round = 1-4 questions, each with concrete options when the choice is enumerable.",
44
+ "Ask about what the code cannot tell you: scope, precedence between existing behaviours,",
45
+ "error handling, and what must not change. Do not ask what you can read from the repo.",
46
+ "Stop asking when the next answer would not change the plan you are about to write.",
47
+ ].join("\n");
48
+
49
+ export const SPEC_FRAMEWORK_GUIDE = [
50
+ "[ASK-PLAN — SPEC FRAMEWORK]",
51
+ "Write the plan as one markdown file (convention: `specs/<slug>.md`) using roughly this shape.",
52
+ "Adapt it: drop sections that do not apply, merge two when they are thin, but keep the order —",
53
+ "the operator reads it top to bottom and reviews it paragraph by paragraph.",
54
+ "",
55
+ "1. `# SPEC: <name>` — one title line, what this change is.",
56
+ "2. `## Context` — why now: the problem, what breaks without it.",
57
+ "3. `## Goal` — the observable outcome, one paragraph, no implementation detail.",
58
+ "4. `## Scope` — what is in and, explicitly, what is **not** (the cheapest way to avoid",
59
+ " scope creep in review).",
60
+ "5. `## Decisions` — the points already settled, one line each with the reason (D1, D2, …).",
61
+ " A decision the operator made stays a decision; do not relitigate it in a later revision.",
62
+ "6. `## Approach` — the design you recommend. One option, the one you would build.",
63
+ "7. `## Data & contracts` — only when there is a schema, file format, endpoint or state machine.",
64
+ "8. `## Files` — the files you will add or change, each with one line of responsibility.",
65
+ "9. `## Milestones` — M1…Mn in build order, each with its own acceptance check, sized so that",
66
+ " one milestone is reviewable on its own.",
67
+ "10. `## Verification` — how the result will be proven: tests to add, commands to run, manual",
68
+ " checks that must pass.",
69
+ "11. `## Risks` — the three that actually worry you, each with the mitigation.",
70
+ "12. `## Open questions` — numbered, each saying who has to answer it. An empty section is fine",
71
+ " and better than inventing questions.",
72
+ "",
73
+ "### Write for paragraph-level review",
74
+ "The operator annotates **blocks** (paragraphs separated by a blank line), so the shape of the",
75
+ "text is the shape of the review:",
76
+ "- one idea per paragraph; if a paragraph needs two comments, it should be two paragraphs;",
77
+ "- a heading sits alone on its line, never glued to the paragraph under it;",
78
+ "- keep a list tight — no blank lines between items, so it stays one reviewable block;",
79
+ "- fenced code blocks stay whole (they are one block, blank lines and all);",
80
+ "- prefer direct statements over hedges: \"use X\" beats \"we could consider X\".",
81
+ "",
82
+ "### Revising after feedback",
83
+ "Annotations arrive whatever the decision — approving means \"go\", not \"notes ignored\".",
84
+ "When revising: change only the blocks that were annotated, keep the rest byte for byte, then",
85
+ "call plan_submit again. A full rewrite makes the diff useless: every block turns red and the",
86
+ "operator has to re-read the whole plan to find your three changes.",
87
+ ].join("\n");
88
+
89
+ /** The complete plan-mode system-prompt block. */
90
+ export function buildPlanSystemPrompt(options: { questionTool?: boolean } = {}): string {
91
+ const questionLine = options.questionTool
92
+ ? "`ask_user_question` is available in this session and is the preferred way to ask."
93
+ : "This session exposes no question tool: ask in plain text and wait for the reply.";
94
+ return `${PLAN_MODE_BANNER}\n${questionLine}\n\n${INTERVIEW_GUIDE}\n\n${SPEC_FRAMEWORK_GUIDE}`;
95
+ }
96
+
97
+ /**
98
+ * One-shot kickoff text for `/ask-plan <topic>`: sets the task and points at the
99
+ * framework without repeating it (it is already in the system prompt).
100
+ */
101
+ export function buildPlanKickoff(topic: string | undefined): string {
102
+ const subject = topic?.trim();
103
+ return [
104
+ "Start planning.",
105
+ subject ? `Task: ${subject}` : "Task: the work we have been discussing in this session.",
106
+ "",
107
+ "Explore the code before writing, ask me what you cannot infer, then write the spec file and",
108
+ "submit it with plan_submit. Do not implement anything yet.",
109
+ ].join("\n");
110
+ }