@makerkit/prd 0.0.3 → 0.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.
Files changed (63) hide show
  1. package/.turbo/turbo-build.log +78 -0
  2. package/.turbo/turbo-test.log +19 -0
  3. package/.turbo/turbo-typecheck.log +6 -0
  4. package/README.md +7 -1
  5. package/dist/README.md +71 -0
  6. package/dist/attachment-paths-BAhRGiib.js +112 -0
  7. package/dist/attachment-paths-C-SWgoSx.mjs +77 -0
  8. package/dist/index.d.ts +81 -0
  9. package/{index.js → dist/index.js} +257 -524
  10. package/{index.mjs → dist/index.mjs} +189 -462
  11. package/{mcp.d.ts → dist/mcp.d.ts} +2 -4
  12. package/{mcp.js → dist/mcp.js} +24 -24
  13. package/{mcp.mjs → dist/mcp.mjs} +24 -24
  14. package/{node.d.ts → dist/node.d.ts} +4 -4
  15. package/{node.js → dist/node.js} +28 -4
  16. package/{node.mjs → dist/node.mjs} +30 -6
  17. package/dist/operations.d.ts +141 -0
  18. package/dist/operations.js +22 -0
  19. package/dist/operations.mjs +1 -0
  20. package/dist/package.json +54 -0
  21. package/dist/prd-operations-BvFxo9bg.mjs +459 -0
  22. package/dist/prd-operations-CcahfbOy.js +584 -0
  23. package/dist/prd.service-CTwKZV-3.d.ts +114 -0
  24. package/{prompts-DJQ4FQ11.js → dist/prompts-1qhax_dj.js} +150 -167
  25. package/{prompts-B0VejF7q.mjs → dist/prompts-BlsYD0gf.mjs} +121 -132
  26. package/{prd.service-x5EpOoMv.d.ts → dist/schema-BwTnt0B9.d.ts} +545 -323
  27. package/package.json +26 -2
  28. package/src/__tests__/agent-workflow.test.ts +417 -0
  29. package/src/__tests__/attachments.test.ts +505 -0
  30. package/src/__tests__/node.test.ts +199 -0
  31. package/src/__tests__/plan-check.test.ts +390 -0
  32. package/src/__tests__/planning.test.ts +1137 -0
  33. package/src/__tests__/prd-operations.test.ts +571 -0
  34. package/src/__tests__/prd.service.test.ts +652 -0
  35. package/src/__tests__/prd.tool.test.ts +282 -0
  36. package/src/__tests__/templates.test.ts +145 -0
  37. package/src/applicability.ts +73 -0
  38. package/src/attachment-paths.ts +83 -0
  39. package/src/attachments.ts +166 -0
  40. package/src/edge-cases.ts +61 -0
  41. package/src/index.ts +33 -0
  42. package/src/markdown.ts +297 -0
  43. package/src/mcp/index.ts +875 -0
  44. package/src/mcp/tool-response.ts +85 -0
  45. package/src/node.ts +184 -0
  46. package/src/open-questions.ts +98 -0
  47. package/src/plan-check.ts +385 -0
  48. package/src/planning-operations.ts +524 -0
  49. package/src/prd-operations.ts +769 -0
  50. package/src/prd.service.ts +1165 -0
  51. package/src/prompts.ts +161 -0
  52. package/src/safe-file-name.ts +42 -0
  53. package/src/schema.ts +1090 -0
  54. package/src/templates.ts +173 -0
  55. package/src/testing/fake-mcp-server.ts +81 -0
  56. package/src/types.ts +381 -0
  57. package/tsconfig.json +23 -0
  58. package/tsconfig.lib.json +8 -0
  59. package/tsconfig.spec.json +7 -0
  60. package/tsdown.config.mts +12 -0
  61. package/vitest.config.mts +8 -0
  62. package/index.d.ts +0 -228
  63. /package/{LICENSE → dist/LICENSE} +0 -0
@@ -1,428 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_prompts = require("./prompts-DJQ4FQ11.js");
2
+ const require_prd_operations = require("./prd-operations-CcahfbOy.js");
3
+ const require_attachment_paths = require("./attachment-paths-BAhRGiib.js");
4
+ const require_prompts = require("./prompts-1qhax_dj.js");
3
5
  let node_path = require("node:path");
4
- //#region src/edge-cases.ts
5
- /**
6
- * Edge cases as stored, with hand-edited entries that would break readers
7
- * dropped: each needs a string id and case; status defaults to "open".
8
- */
9
- function normalizeEdgeCases(value) {
10
- if (!Array.isArray(value)) return [];
11
- return value.flatMap((entry) => {
12
- if (typeof entry !== "object" || entry === null) return [];
13
- const { id, case: caseText, expectedBehavior, status, storyIds } = entry;
14
- if (typeof id !== "string" || typeof caseText !== "string" || !caseText) return [];
15
- const ids = Array.isArray(storyIds) ? storyIds.filter((storyId) => typeof storyId === "string") : [];
16
- return [{
17
- id,
18
- case: caseText,
19
- expectedBehavior: typeof expectedBehavior === "string" ? expectedBehavior : "",
20
- status: status === "decided" ? "decided" : "open",
21
- ...ids.length > 0 ? { storyIds: ids } : {}
22
- }];
23
- });
24
- }
25
- /** The edge cases that apply to a story: those linked to it, and those linked to no story. */
26
- function edgeCasesForStory(prd, storyId) {
27
- return prd.edgeCases.filter((edgeCase) => !edgeCase.storyIds?.length || edgeCase.storyIds.includes(storyId));
28
- }
29
- /** Accepted decisions whose topic starts with `design`, e.g. `design:navigation`. */
30
- function designDecisions(prd) {
31
- return prd.decisionLog.filter((entry) => entry.status === "accepted" && entry.topic?.startsWith("design"));
32
- }
33
- //#endregion
34
- //#region src/prd-operations.ts
35
- /**
36
- * Pure PRD transforms.
37
- *
38
- * Everything here takes an already-loaded `StructuredPRD`, mutates it, and
39
- * returns the tool payload. No filesystem, no clock, no deps — the service is
40
- * left with load → transform → save, and every rule below is unit-testable
41
- * without a harness.
42
- */
43
- /**
44
- * Issues the next story id and advances the high-water mark.
45
- *
46
- * Deliberately not `max(existing) + 1`: delete the highest-numbered story and
47
- * that hands its id straight to the next one, so a story id quoted in a commit
48
- * or a decision-log topic would silently come to mean something else.
49
- */
50
- function nextId(items, prefix) {
51
- const highest = items.reduce((max, item) => {
52
- const match = new RegExp(`^${prefix}(\\d+)$`).exec(item.id);
53
- return match ? Math.max(max, Number(match[1])) : max;
54
- }, 0);
55
- return `${prefix}${String(highest + 1).padStart(3, "0")}`;
56
- }
57
- function nextStoryId(prd) {
58
- const highestPresent = prd.userStories.reduce((max, story) => {
59
- const match = /^US(\d+)$/.exec(story.id);
60
- return match ? Math.max(max, Number(match[1])) : max;
61
- }, 0);
62
- const next = Math.max(prd.metadata.lastStoryNumber ?? 0, highestPresent) + 1;
63
- prd.metadata.lastStoryNumber = next;
64
- return `US${String(next).padStart(3, "0")}`;
65
- }
66
- function recomputeProgress(prd) {
67
- const total = prd.userStories.length;
68
- const completed = prd.userStories.filter((story) => story.status === "completed").length;
69
- prd.progress = {
70
- completed,
71
- blocked: prd.userStories.filter((story) => story.status === "blocked").length,
72
- total,
73
- overall: total > 0 ? Math.round(completed / total * 100) : 0
74
- };
75
- }
76
- function appendChangeLog(prd, entry, today) {
77
- prd.changeLog.push(`${today}: ${entry}`);
78
- }
79
- function findStory(prd, storyId) {
80
- const story = prd.userStories.find((candidate) => candidate.id === storyId);
81
- if (!story) {
82
- const known = prd.userStories.map((candidate) => candidate.id).join(", ");
83
- throw new Error(`Story ${storyId} not found.` + (known ? ` Known stories: ${known}.` : " This PRD has no stories yet."));
84
- }
85
- return story;
86
- }
87
- const USER_STORY_SENTENCE = /^As an?\s+(.+?),\s*I want to\s+(.+?)\s+so that\s+(.+)$/i;
88
- /** Splits the rendered sentence back into its parts so one can be patched. */
89
- /** The parts of an "As a X, I want to Y so that Z" story, or undefined. */
90
- function splitUserStory(sentence) {
91
- const match = USER_STORY_SENTENCE.exec(sentence.trim());
92
- if (!match) return;
93
- return {
94
- userType: match[1],
95
- action: match[2],
96
- benefit: match[3]
97
- };
98
- }
99
- function renderUserStory(parts) {
100
- return `As a ${parts.userType}, I want to ${parts.action} so that ${parts.benefit}`;
101
- }
102
- function updateStory(prd, input, today) {
103
- const story = findStory(prd, input.storyId);
104
- const updated = [];
105
- if (input.userType !== void 0 || input.action !== void 0 || input.benefit !== void 0) {
106
- const current = splitUserStory(story.userStory);
107
- if (!current && (input.userType === void 0 || input.action === void 0 || input.benefit === void 0)) throw new Error(`Story ${story.id} does not use the "As a X, I want to Y so that Z" form, so its parts cannot be patched individually. Supply userType, action and benefit together.`);
108
- story.userStory = renderUserStory({
109
- userType: input.userType ?? current.userType,
110
- action: input.action ?? current.action,
111
- benefit: input.benefit ?? current.benefit
112
- });
113
- updated.push("userStory");
114
- if (input.benefit !== void 0 && input.businessValue === void 0) {
115
- story.businessValue = input.benefit;
116
- updated.push("businessValue");
117
- }
118
- }
119
- if (input.title !== void 0) {
120
- story.title = input.title;
121
- updated.push("title");
122
- }
123
- if (input.testSeams !== void 0) {
124
- story.testSeams = input.testSeams;
125
- updated.push("testSeams");
126
- }
127
- if (input.designNotes !== void 0) {
128
- story.designNotes = withoutBlanks(input.designNotes);
129
- updated.push("designNotes");
130
- }
131
- if (input.securityNotes !== void 0) {
132
- story.securityNotes = withoutBlanks(input.securityNotes);
133
- updated.push("securityNotes");
134
- }
135
- if (input.businessValue !== void 0) {
136
- story.businessValue = input.businessValue;
137
- updated.push("businessValue");
138
- }
139
- if (input.acceptanceCriteria !== void 0) {
140
- story.acceptanceCriteria = input.acceptanceCriteria.filter((entry) => entry.trim().length > 0);
141
- updated.push("acceptanceCriteria");
142
- }
143
- if (input.priority !== void 0) {
144
- story.priority = input.priority;
145
- updated.push("priority");
146
- }
147
- if (input.estimatedComplexity !== void 0) {
148
- story.estimatedComplexity = input.estimatedComplexity;
149
- updated.push("estimatedComplexity");
150
- }
151
- if (input.dependencies !== void 0) {
152
- story.dependencies = validateDependencies(prd, story.id, input.dependencies);
153
- updated.push("dependencies");
154
- }
155
- if (input.notes !== void 0) {
156
- story.notes = input.notes;
157
- updated.push("notes");
158
- }
159
- if (input.attachmentIds !== void 0) {
160
- story.attachmentIds = validateAttachmentIds(prd, input.attachmentIds);
161
- updated.push("attachmentIds");
162
- }
163
- if (input.phaseId !== void 0) {
164
- assignStoryToPhase(prd, {
165
- filename: input.filename,
166
- storyId: story.id,
167
- phaseId: input.phaseId
168
- }, today);
169
- updated.push("phase");
170
- }
171
- if (updated.length === 0) throw new Error(`No fields supplied to update on ${story.id}. Provide at least one of: title, userType, action, benefit, businessValue, acceptanceCriteria, priority, estimatedComplexity, dependencies, notes, testSeams, designNotes, securityNotes, attachmentIds, phaseId.`);
172
- appendChangeLog(prd, `Updated ${story.id} (${updated.join(", ")})`, today);
173
- return {
174
- story_id: story.id,
175
- title: story.title,
176
- updated_fields: [...new Set(updated)],
177
- story
178
- };
179
- }
180
- function findAttachment(prd, attachmentId) {
181
- const attachment = prd.attachments.find((candidate) => candidate.id === attachmentId);
182
- if (!attachment) throw new Error(`Attachment "${attachmentId}" not found.`);
183
- return attachment;
184
- }
185
- /** Attachment ids must name attachments in the PRD. */
186
- function validateAttachmentIds(prd, ids) {
187
- for (const id of ids) findAttachment(prd, id);
188
- return [...new Set(ids)];
189
- }
190
- /**
191
- * Dependencies must name real stories, never the story itself, and never form
192
- * a cycle — an unsatisfiable order is worse than no order at all.
193
- */
194
- function validateDependencies(prd, storyId, dependencies) {
195
- const unique = [...new Set(dependencies.filter((id) => id.trim().length > 0))];
196
- for (const id of unique) {
197
- if (id === storyId) throw new Error(`Story ${storyId} cannot depend on itself.`);
198
- findStory(prd, id);
199
- }
200
- const cycle = findCycle(new Map(prd.userStories.map((story) => [story.id, story.id === storyId ? unique : story.dependencies])), storyId);
201
- if (cycle) throw new Error(`Dependency cycle: ${cycle.join(" -> ")}. Remove one of these links.`);
202
- return unique;
203
- }
204
- function findCycle(edges, from) {
205
- const visiting = /* @__PURE__ */ new Set();
206
- const done = /* @__PURE__ */ new Set();
207
- const walk = (id, trail) => {
208
- if (done.has(id)) return void 0;
209
- if (visiting.has(id)) return [...trail, id];
210
- visiting.add(id);
211
- for (const next of edges.get(id) ?? []) {
212
- const found = walk(next, [...trail, id]);
213
- if (found) return found;
214
- }
215
- visiting.delete(id);
216
- done.add(id);
217
- };
218
- return walk(from, []);
219
- }
220
- function deleteStory(prd, storyId, today) {
221
- const story = findStory(prd, storyId);
222
- prd.userStories = prd.userStories.filter((candidate) => candidate.id !== storyId);
223
- const dependencyReferencesRemoved = [];
224
- for (const candidate of prd.userStories) if (candidate.dependencies.includes(storyId)) {
225
- candidate.dependencies = candidate.dependencies.filter((id) => id !== storyId);
226
- dependencyReferencesRemoved.push(candidate.id);
227
- }
228
- const phasesUpdated = [];
229
- for (const phase of prd.customPhases) if (phase.userStoryIds.includes(storyId)) {
230
- phase.userStoryIds = phase.userStoryIds.filter((id) => id !== storyId);
231
- phasesUpdated.push(phase.id);
232
- }
233
- prd.edgeCases = prd.edgeCases.flatMap((edgeCase) => {
234
- if (!edgeCase.storyIds?.includes(storyId)) return [edgeCase];
235
- const storyIds = edgeCase.storyIds.filter((id) => id !== storyId);
236
- return storyIds.length > 0 ? [{
237
- ...edgeCase,
238
- storyIds
239
- }] : [];
240
- });
241
- for (const question of prd.openQuestions) if (question.storyIds?.includes(storyId)) {
242
- const storyIds = question.storyIds.filter((id) => id !== storyId);
243
- if (storyIds.length > 0) question.storyIds = storyIds;
244
- else delete question.storyIds;
245
- }
246
- for (const entry of prd.decisionLog) if (entry.topic?.startsWith(`story:${storyId}:`) && entry.status === "accepted") entry.status = "superseded";
247
- recomputeProgress(prd);
248
- appendChangeLog(prd, `Deleted ${storyId} (${story.title})`, today);
249
- return {
250
- story_id: storyId,
251
- title: story.title,
252
- total_stories: prd.userStories.length,
253
- progress: prd.progress.overall,
254
- dependency_references_removed: dependencyReferencesRemoved,
255
- phases_updated: phasesUpdated
256
- };
257
- }
258
- function createPhase(prd, input, today) {
259
- const name = input.name.trim();
260
- if (prd.customPhases.some((phase) => phase.name.toLowerCase() === name.toLowerCase())) throw new Error(`A phase named "${name}" already exists.`);
261
- const phase = {
262
- id: nextId(prd.customPhases, "PHASE"),
263
- name,
264
- description: input.description,
265
- color: input.color,
266
- order: prd.customPhases.length,
267
- userStoryIds: []
268
- };
269
- prd.customPhases.push(phase);
270
- appendChangeLog(prd, `Created phase ${phase.id} (${name})`, today);
271
- return {
272
- phase: {
273
- id: phase.id,
274
- name: phase.name,
275
- description: phase.description,
276
- color: phase.color,
277
- order: phase.order,
278
- user_story_ids: phase.userStoryIds
279
- },
280
- total_phases: prd.customPhases.length
281
- };
282
- }
283
- function assignStoryToPhase(prd, input, today) {
284
- findStory(prd, input.storyId);
285
- const target = input.phaseId === null ? void 0 : prd.customPhases.find((phase) => phase.id === input.phaseId);
286
- if (input.phaseId !== null && !target) {
287
- const known = prd.customPhases.map((phase) => phase.id).join(", ");
288
- throw new Error(`Phase "${input.phaseId}" not found.` + (known ? ` Known phases: ${known}.` : " This PRD has no phases yet."));
289
- }
290
- const previous = prd.customPhases.find((phase) => phase.userStoryIds.includes(input.storyId));
291
- for (const phase of prd.customPhases) phase.userStoryIds = phase.userStoryIds.filter((id) => id !== input.storyId);
292
- target?.userStoryIds.push(input.storyId);
293
- appendChangeLog(prd, target ? `Assigned ${input.storyId} to ${target.id} (${target.name})` : `Removed ${input.storyId} from all phases`, today);
294
- return {
295
- story_id: input.storyId,
296
- phase_id: target?.id ?? null,
297
- phase_name: target?.name ?? null,
298
- moved_from: previous && previous.id !== target?.id ? previous.id : null
299
- };
300
- }
301
- /** Statuses that mean work on the story has started or finished. */
302
- const WORK_STATUSES = [
303
- "in_progress",
304
- "review",
305
- "completed"
306
- ];
307
- const PRIORITY_ORDER = {
308
- P0: 0,
309
- P1: 1,
310
- P2: 2,
311
- P3: 3
312
- };
313
- /** Dependencies of `story` that are not completed yet. */
314
- function incompleteDependencies(prd, story) {
315
- return story.dependencies.filter((id) => {
316
- return prd.userStories.find((candidate) => candidate.id === id)?.status !== "completed";
317
- });
318
- }
319
- /**
320
- * A story cannot be worked on, reviewed or completed before the stories it
321
- * depends on are completed. `not_started`, `research` and `blocked` stay
322
- * available so a story can still be planned or parked.
323
- */
324
- function assertCanEnterStatus(prd, story, status) {
325
- if (!WORK_STATUSES.includes(status)) return;
326
- const waitingOn = incompleteDependencies(prd, story);
327
- if (waitingOn.length > 0) throw new Error(`Cannot move ${story.id} to ${status}: it depends on ${waitingOn.join(", ")}, which ${waitingOn.length === 1 ? "is" : "are"} not completed yet.`);
328
- }
329
- /** Position of the story's phase; stories without a phase come last. */
330
- function phaseRank(prd, storyId) {
331
- const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(storyId));
332
- return phase ? phase.order : Number.MAX_SAFE_INTEGER;
333
- }
334
- /**
335
- * The next story to start: not started, every dependency completed, ordered
336
- * by phase, then priority, then position in the PRD.
337
- */
338
- function pickNextStory(prd) {
339
- const notStarted = prd.userStories.filter((story) => story.status === "not_started");
340
- const ready = notStarted.filter((story) => incompleteDependencies(prd, story).length === 0).sort((a, b) => phaseRank(prd, a.id) - phaseRank(prd, b.id) || PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority] || prd.userStories.indexOf(a) - prd.userStories.indexOf(b));
341
- const waiting = notStarted.map((story) => ({
342
- id: story.id,
343
- title: story.title,
344
- waiting_on: incompleteDependencies(prd, story)
345
- })).filter((entry) => entry.waiting_on.length > 0);
346
- return {
347
- story: ready[0] ?? null,
348
- ready_count: ready.length,
349
- in_progress: prd.userStories.filter((story) => story.status === "in_progress").map((story) => story.id),
350
- waiting
351
- };
352
- }
353
- /**
354
- * Everything an agent needs to work on one story without loading the whole
355
- * PRD: the story, the scope boundaries, its dependencies with their hand-off
356
- * logs, and the log of the most recently completed story.
357
- */
358
- /** `filename` is the PRD's file name, used to give attachment paths. */
359
- function buildStoryContext(prd, storyId, filename) {
360
- const story = findStory(prd, storyId);
361
- const linked = new Set(story.attachmentIds ?? []);
362
- const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(story.id)) ?? null;
363
- const lastCompleted = prd.userStories.filter((candidate) => candidate.status === "completed").filter((candidate) => candidate.id !== story.id).sort((a, b) => (a.completedAt ?? "").localeCompare(b.completedAt ?? "")).at(-1) ?? null;
364
- return {
365
- prd: {
366
- title: prd.introduction.title,
367
- overview: prd.introduction.overview,
368
- non_goals: prd.nonGoals,
369
- out_of_scope: prd.outOfScope,
370
- global_acceptance_criteria: prd.acceptanceCriteria.global,
371
- attachments: require_prompts.resolveAttachments(filename, prd.attachments)
372
- },
373
- story,
374
- attachments: require_prompts.resolveAttachments(filename, prd.attachments.filter((attachment) => linked.has(attachment.id))),
375
- phase: phase ? {
376
- id: phase.id,
377
- name: phase.name
378
- } : null,
379
- edge_cases: edgeCasesForStory(prd, story.id),
380
- open_questions: prd.openQuestions.filter((question) => question.storyIds?.includes(story.id)),
381
- security: {
382
- permissions: prd.technicalContracts.permissions,
383
- compliance: prd.technicalRequirements.complianceRequirements,
384
- considerations: prd.securityConsiderations,
385
- story_notes: story.securityNotes ?? []
386
- },
387
- not_applicable: prd.notApplicable,
388
- design: {
389
- guidance: prd.designGuidance,
390
- story_notes: story.designNotes ?? [],
391
- decisions: designDecisions(prd).map(({ id, decision, rationale }) => ({
392
- id,
393
- decision,
394
- rationale
395
- }))
396
- },
397
- dependencies: story.dependencies.map((id) => {
398
- const dependency = prd.userStories.find((candidate) => candidate.id === id);
399
- return {
400
- id,
401
- title: dependency?.title ?? null,
402
- status: dependency?.status ?? null,
403
- log: dependency?.log ?? []
404
- };
405
- }),
406
- previous_story: lastCompleted ? {
407
- id: lastCompleted.id,
408
- title: lastCompleted.title,
409
- log: lastCompleted.log ?? []
410
- } : null
411
- };
412
- }
413
- function appendStoryLog(prd, storyId, entry) {
414
- const story = findStory(prd, storyId);
415
- story.log = [...story.log ?? [], entry];
416
- return {
417
- story_id: story.id,
418
- entries: story.log.length
419
- };
420
- }
421
- function withoutBlanks(entries) {
422
- return entries.map((entry) => entry.trim()).filter(Boolean);
423
- }
424
- //#endregion
425
- //#region src/applicability.ts
6
+ // src/applicability.ts
426
7
  /**
427
8
  * Parts of a PRD that can be marked "not applicable" (e.g. no rollout plan
428
9
  * for an internal tool), so the plan check stops asking for them and agents
@@ -459,15 +40,14 @@ function setNotApplicable(prd, input, today) {
459
40
  const { [input.topic]: _removed, ...rest } = prd.notApplicable;
460
41
  prd.notApplicable = rest;
461
42
  }
462
- appendChangeLog(prd, input.notApplicable ? `Marked ${input.topic} not applicable` : `Marked ${input.topic} applicable`, today);
43
+ require_prd_operations.appendChangeLog(prd, input.notApplicable ? `Marked ${input.topic} not applicable` : `Marked ${input.topic} applicable`, today);
463
44
  return {
464
45
  topic: input.topic,
465
46
  not_applicable: input.notApplicable,
466
47
  reason: prd.notApplicable[input.topic] ?? null
467
48
  };
468
49
  }
469
- //#endregion
470
- //#region src/attachments.ts
50
+ // src/attachments.ts
471
51
  /**
472
52
  * Adds an attachment and links it to the given stories. The caller checks
473
53
  * that a `path` exists on disk; this only validates the PRD.
@@ -475,8 +55,8 @@ function setNotApplicable(prd, input, today) {
475
55
  function addAttachment(prd, input, today) {
476
56
  if (Boolean(input.path) === Boolean(input.url)) throw new Error("Give either path or url for an attachment, not both.");
477
57
  if (input.url && !/^https?:\/\//i.test(input.url)) throw new Error("An attachment url must start with http:// or https://.");
478
- const path = input.path ? require_prompts.assertSafeRelativePath(input.path, "attachment path") : void 0;
479
- const stories = (input.storyIds ?? []).map((id) => findStory(prd, id));
58
+ const path = input.path ? require_attachment_paths.assertSafeRelativePath(input.path, "attachment path") : void 0;
59
+ const stories = (input.storyIds ?? []).map((id) => require_prd_operations.findStory(prd, id));
480
60
  const id = nextAttachmentId(prd);
481
61
  prd.attachments.push({
482
62
  id,
@@ -485,10 +65,10 @@ function addAttachment(prd, input, today) {
485
65
  ...input.note ? { note: input.note } : {}
486
66
  });
487
67
  for (const story of stories) story.attachmentIds = [.../* @__PURE__ */ new Set([...story.attachmentIds ?? [], id])];
488
- appendChangeLog(prd, `Added attachment ${id} (${input.title})`, today);
68
+ require_prd_operations.appendChangeLog(prd, `Added attachment ${id} (${input.title})`, today);
489
69
  return {
490
70
  attachment_id: id,
491
- path: path ? require_prompts.attachmentProjectPath(input.filename, path) : null,
71
+ path: path ? require_attachment_paths.attachmentProjectPath(input.filename, path) : null,
492
72
  stories_updated: stories.map((story) => story.id),
493
73
  total_attachments: prd.attachments.length
494
74
  };
@@ -510,14 +90,14 @@ function nextAttachmentId(prd) {
510
90
  * on disk.
511
91
  */
512
92
  function removeAttachment(prd, attachmentId, today) {
513
- const attachment = findAttachment(prd, attachmentId);
93
+ const attachment = require_prd_operations.findAttachment(prd, attachmentId);
514
94
  prd.attachments = prd.attachments.filter((candidate) => candidate.id !== attachment.id);
515
95
  const storiesUpdated = [];
516
96
  for (const story of prd.userStories) if (story.attachmentIds?.includes(attachment.id)) {
517
97
  story.attachmentIds = story.attachmentIds.filter((id) => id !== attachment.id);
518
98
  storiesUpdated.push(story.id);
519
99
  }
520
- appendChangeLog(prd, `Removed attachment ${attachment.id} (${attachment.title})`, today);
100
+ require_prd_operations.appendChangeLog(prd, `Removed attachment ${attachment.id} (${attachment.title})`, today);
521
101
  return {
522
102
  attachment_id: attachment.id,
523
103
  stories_updated: storiesUpdated,
@@ -529,7 +109,7 @@ function removeAttachment(prd, attachmentId, today) {
529
109
  * storyIds, links are added and removed so exactly those stories use it.
530
110
  */
531
111
  function updateAttachment(prd, input, today) {
532
- const attachment = findAttachment(prd, input.attachmentId);
112
+ const attachment = require_prd_operations.findAttachment(prd, input.attachmentId);
533
113
  if (input.title !== void 0) attachment.title = input.title;
534
114
  if (input.note !== void 0) {
535
115
  if (input.note.trim()) attachment.note = input.note;
@@ -537,7 +117,7 @@ function updateAttachment(prd, input, today) {
537
117
  }
538
118
  const storiesUpdated = [];
539
119
  if (input.storyIds !== void 0) {
540
- const wanted = new Set(input.storyIds.map((id) => findStory(prd, id).id));
120
+ const wanted = new Set(input.storyIds.map((id) => require_prd_operations.findStory(prd, id).id));
541
121
  for (const story of prd.userStories) {
542
122
  const linked = story.attachmentIds?.includes(attachment.id) ?? false;
543
123
  if (wanted.has(story.id) && !linked) {
@@ -549,14 +129,13 @@ function updateAttachment(prd, input, today) {
549
129
  }
550
130
  }
551
131
  }
552
- appendChangeLog(prd, `Updated attachment ${attachment.id} (${attachment.title})`, today);
132
+ require_prd_operations.appendChangeLog(prd, `Updated attachment ${attachment.id} (${attachment.title})`, today);
553
133
  return {
554
134
  attachment_id: attachment.id,
555
135
  stories_updated: storiesUpdated
556
136
  };
557
137
  }
558
- //#endregion
559
- //#region src/markdown.ts
138
+ // src/markdown.ts
560
139
  const STATUS_LABELS = {
561
140
  not_started: "[not started]",
562
141
  research: "[research]",
@@ -640,6 +219,17 @@ function formatPrdMarkdown(prd, filename) {
640
219
  lines.push("", "---", "", `*Approver: ${prd.metadata.approver || "TBD"}*`, "");
641
220
  return lines.join("\n");
642
221
  }
222
+ /** The criterion, followed by how it is proven when the story says. */
223
+ function withProof(story, criterion) {
224
+ const proof = story.proofs?.find((entry) => entry.criterion === criterion);
225
+ if (!proof) return criterion;
226
+ const detail = [
227
+ proof.seam && `\`${proof.seam}\``,
228
+ proof.reason,
229
+ proof.rubric?.length && `rubric: ${proof.rubric.join("; ")}`
230
+ ].filter(Boolean).join(": ");
231
+ return `${criterion} *(proof: ${proof.kind}${detail ? ` — ${detail}` : ""})*`;
232
+ }
643
233
  function formatStory(story) {
644
234
  const lines = [
645
235
  `#### ${story.id}: ${story.title} ${STATUS_LABELS[story.status]} [${story.estimatedComplexity}]`,
@@ -649,7 +239,7 @@ function formatStory(story) {
649
239
  `**Business Value:** ${story.businessValue}`,
650
240
  "",
651
241
  "**Acceptance Criteria:**",
652
- ...bullets(story.acceptanceCriteria)
242
+ ...bullets(story.acceptanceCriteria.map((criterion) => withProof(story, criterion)))
653
243
  ];
654
244
  if (story.dependencies.length > 0) lines.push("", `**Dependencies:** ${story.dependencies.join(", ")}`);
655
245
  if (story.attachmentIds?.length) lines.push("", `**Attachments:** ${story.attachmentIds.join(", ")}`);
@@ -661,7 +251,7 @@ function formatStory(story) {
661
251
  }
662
252
  function formatAttachment(attachment, filename) {
663
253
  const title = oneLine(attachment.title).replace(/[[\]]/g, "\\$&");
664
- const target = attachment.url ? linkTarget(attachment.url) : filename ? linkTarget(encodeURI(`${require_prompts.attachmentsFolder(filename)}/${attachment.path}`)) : void 0;
254
+ const target = attachment.url ? linkTarget(attachment.url) : filename ? linkTarget(encodeURI(`${require_attachment_paths.attachmentsFolder(filename)}/${attachment.path}`)) : void 0;
665
255
  const label = target ? `[${title}](${target})` : `${title} (${attachment.path})`;
666
256
  const note = attachment.note ? ` - ${oneLine(attachment.note)}` : "";
667
257
  return `- ${attachment.id}: ${label}${note}`;
@@ -678,8 +268,7 @@ function bullets(items, emptyLabel) {
678
268
  if (items.length === 0) return emptyLabel ? [`- ${emptyLabel}`] : [];
679
269
  return items.map((item) => `- ${item}`);
680
270
  }
681
- //#endregion
682
- //#region src/open-questions.ts
271
+ // src/open-questions.ts
683
272
  /**
684
273
  * Open questions as stored. Older files hold plain strings; they become
685
274
  * questions with ids in list order. Entries without question text are dropped.
@@ -738,8 +327,7 @@ function blockingQuestions(prd) {
738
327
  const unfinished = new Set(prd.userStories.filter((story) => story.status !== "completed").map((story) => story.id));
739
328
  return prd.openQuestions.filter((question) => question.storyIds?.some((id) => unfinished.has(id)));
740
329
  }
741
- //#endregion
742
- //#region src/plan-check.ts
330
+ // src/plan-check.ts
743
331
  /** The not-applicable topic each "missing" check is about. */
744
332
  const CHECK_TOPICS = {
745
333
  "edge-cases": "edgeCases",
@@ -753,6 +341,16 @@ const CHECK_TOPICS = {
753
341
  };
754
342
  /** Above this many stories, grouping them into phases is recommended. */
755
343
  const PHASE_THRESHOLD = 5;
344
+ /**
345
+ * From this many stories, the problem and solution should be written out:
346
+ * stories say what to build, the prose says what is meant. Fewer words than
347
+ * MIN_INTENT_WORDS rarely carries that.
348
+ */
349
+ const INTENT_STORY_THRESHOLD = 3;
350
+ const MIN_INTENT_WORDS = 25;
351
+ function wordCount(text) {
352
+ return text.split(/\s+/).filter(Boolean).length;
353
+ }
756
354
  function checkPlan(prd) {
757
355
  const items = [];
758
356
  const stories = prd.userStories;
@@ -875,6 +473,48 @@ function checkPlan(prd) {
875
473
  severity: "recommended",
876
474
  storyIds: withoutSeams.map((story) => story.id)
877
475
  });
476
+ const unproven = stories.filter((story) => story.status !== "completed" && story.acceptanceCriteria.some((criterion) => !story.proofs?.some((proof) => proof.criterion === criterion)));
477
+ if (unproven.length > 0) items.push({
478
+ id: "unproven-criteria",
479
+ section: "userStories",
480
+ message: `${unproven.length} stories have acceptance criteria with no proof; say how each is shown to work (proofs)`,
481
+ severity: "recommended",
482
+ storyIds: unproven.map((story) => story.id)
483
+ });
484
+ const unjustifiedE2e = stories.filter((story) => story.status !== "completed" && story.proofs?.some((proof) => proof.kind === "e2e" && !proof.reason));
485
+ if (unjustifiedE2e.length > 0) items.push({
486
+ id: "e2e-proofs",
487
+ section: "userStories",
488
+ message: `${unjustifiedE2e.length} stories rely on e2e proofs without saying why a lower seam (service, server action, route) will not do`,
489
+ severity: "recommended",
490
+ storyIds: unjustifiedE2e.map((story) => story.id)
491
+ });
492
+ const mostlyManual = stories.filter((story) => {
493
+ const proofs = story.proofs ?? [];
494
+ const untested = proofs.filter((proof) => proof.kind === "manual" || proof.kind === "post-deploy");
495
+ return story.status !== "completed" && untested.length * 2 > proofs.length;
496
+ });
497
+ if (mostlyManual.length > 0) items.push({
498
+ id: "untested-proofs",
499
+ section: "userStories",
500
+ message: `${mostlyManual.length} stories are mostly proven by hand; split the criteria so the testable parts get a test`,
501
+ severity: "recommended",
502
+ storyIds: mostlyManual.map((story) => story.id)
503
+ });
504
+ if (stories.length >= INTENT_STORY_THRESHOLD) {
505
+ if (wordCount(prd.problemStatement.problem) < MIN_INTENT_WORDS) items.push({
506
+ id: "thin-problem",
507
+ section: "problemStatement",
508
+ message: "Describe the problem in a few sentences: who has it, when, and what it costs them. The stories are checked against it",
509
+ severity: "recommended"
510
+ });
511
+ if (wordCount(prd.solutionOverview.description) < MIN_INTENT_WORDS) items.push({
512
+ id: "thin-solution",
513
+ section: "solutionOverview",
514
+ message: "Describe the finished feature in a few sentences: what a person can do and how it feels. The stories are checked against it",
515
+ severity: "recommended"
516
+ });
517
+ }
878
518
  const phased = new Set(prd.customPhases.flatMap((phase) => phase.userStoryIds));
879
519
  const unphased = stories.filter((story) => !phased.has(story.id));
880
520
  if (stories.length > PHASE_THRESHOLD && unphased.length > 0) items.push({
@@ -901,8 +541,7 @@ function checkPlan(prd) {
901
541
  items: applicable
902
542
  };
903
543
  }
904
- //#endregion
905
- //#region src/planning-operations.ts
544
+ // src/planning-operations.ts
906
545
  /**
907
546
  * Pure transforms for shaping a PRD after it was created: sections, decisions,
908
547
  * open questions, glossary and phases. Same contract as `prd-operations`:
@@ -924,12 +563,21 @@ function updatePrdSection(prd, input, today) {
924
563
  }
925
564
  const value = parsed.data;
926
565
  let updated;
927
- if (input.section === "risks") {
566
+ if (input.section === "roadmap") {
567
+ const patch = value;
568
+ const merged = Object.fromEntries(Object.entries({
569
+ ...prd.roadmap,
570
+ ...patch
571
+ }).filter(([key, value]) => !(Object.hasOwn(patch, key) && value == null)));
572
+ if (Object.keys(merged).length > 0) prd.roadmap = merged;
573
+ else delete prd.roadmap;
574
+ updated = Object.keys(patch);
575
+ } else if (input.section === "risks") {
928
576
  const risks = value;
929
577
  const assigned = [];
930
578
  for (const risk of risks) assigned.push({
931
579
  ...risk,
932
- id: risk.id ?? nextId(assigned, "RISK")
580
+ id: risk.id ?? require_prd_operations.nextId(assigned, "RISK")
933
581
  });
934
582
  prd.risks = assigned;
935
583
  updated = assigned.map((risk) => risk.id);
@@ -938,7 +586,7 @@ function updatePrdSection(prd, input, today) {
938
586
  const assigned = [];
939
587
  for (const item of items) assigned.push({
940
588
  ...item,
941
- id: item.id ?? nextId(assigned, "DEP")
589
+ id: item.id ?? require_prd_operations.nextId(assigned, "DEP")
942
590
  });
943
591
  prd.dependencies = assigned;
944
592
  updated = assigned.map((item) => item.id);
@@ -969,7 +617,7 @@ function updatePrdSection(prd, input, today) {
969
617
  const { storyIds: linked, ...rest } = item;
970
618
  assigned.push({
971
619
  ...rest,
972
- id: item.id ?? nextId([...prd.edgeCases, ...assigned], "EC"),
620
+ id: item.id ?? require_prd_operations.nextId([...prd.edgeCases, ...assigned], "EC"),
973
621
  ...linked?.length ? { storyIds: linked } : {}
974
622
  });
975
623
  }
@@ -984,7 +632,7 @@ function updatePrdSection(prd, input, today) {
984
632
  Object.assign(prd[key], value);
985
633
  updated = Object.keys(value);
986
634
  }
987
- appendChangeLog(prd, `Updated ${input.section}`, today);
635
+ require_prd_operations.appendChangeLog(prd, `Updated ${input.section}`, today);
988
636
  return {
989
637
  section: input.section,
990
638
  updated
@@ -998,7 +646,7 @@ function addDecision(prd, input, today) {
998
646
  previous.status = "superseded";
999
647
  superseded = previous.id;
1000
648
  }
1001
- const id = nextId(prd.decisionLog, "DEC");
649
+ const id = require_prd_operations.nextId(prd.decisionLog, "DEC");
1002
650
  prd.decisionLog.push({
1003
651
  id,
1004
652
  date: today,
@@ -1008,13 +656,41 @@ function addDecision(prd, input, today) {
1008
656
  ...input.owner ? { owner: input.owner } : {},
1009
657
  ...input.topic ? { topic: input.topic } : {}
1010
658
  });
1011
- appendChangeLog(prd, superseded ? `Recorded ${id} (supersedes ${superseded})` : `Recorded ${id}`, today);
659
+ require_prd_operations.appendChangeLog(prd, superseded ? `Recorded ${id} (supersedes ${superseded})` : `Recorded ${id}`, today);
1012
660
  return {
1013
661
  decision_id: id,
1014
662
  superseded,
1015
663
  total_decisions: prd.decisionLog.length
1016
664
  };
1017
665
  }
666
+ /**
667
+ * The decision topic for a story's accepted deviations. Deleting the story
668
+ * supersedes them with its other decisions.
669
+ */
670
+ function deviationTopic(storyId) {
671
+ return `story:${storyId}:deviation`;
672
+ }
673
+ /**
674
+ * Deviations the reviewer accepted become decisions, so the PRD describes
675
+ * what was built rather than only what was planned. Each must be one the
676
+ * story logged; one already recorded is not recorded twice.
677
+ */
678
+ function assertLoggedDeviations(story, deviations) {
679
+ const logged = (story.log ?? []).flatMap((entry) => entry.deviations ?? []);
680
+ for (const deviation of deviations) if (!logged.includes(deviation)) throw new Error(`${story.id} did not log the deviation "${deviation}". Copy it exactly from the story log.`);
681
+ }
682
+ function recordDeviations(prd, story, deviations, today) {
683
+ assertLoggedDeviations(story, deviations);
684
+ const topic = deviationTopic(story.id);
685
+ const recorded = new Set(prd.decisionLog.filter((entry) => entry.topic === topic && entry.status === "accepted").map((entry) => entry.decision));
686
+ return [...new Set(deviations)].filter((deviation) => !recorded.has(deviation)).map((deviation) => addDecision(prd, {
687
+ filename: "",
688
+ decision: deviation,
689
+ rationale: `Departed from the plan while building ${story.id} (${story.title}); accepted at review.`,
690
+ topic,
691
+ status: "accepted"
692
+ }, today).decision_id);
693
+ }
1018
694
  function resolveOpenQuestion(prd, input, today) {
1019
695
  const wanted = input.question ? normalizeText(input.question) : null;
1020
696
  const index = prd.openQuestions.findIndex((question) => input.questionId ? question.id === input.questionId : normalizeText(question.question) === wanted);
@@ -1028,7 +704,7 @@ function resolveOpenQuestion(prd, input, today) {
1028
704
  topic: `open-question:${question.id}`,
1029
705
  status: "accepted"
1030
706
  }, today).decision_id;
1031
- else appendChangeLog(prd, `Resolved ${question.id}: ${question.question}`, today);
707
+ else require_prd_operations.appendChangeLog(prd, `Resolved ${question.id}: ${question.question}`, today);
1032
708
  return {
1033
709
  remaining_questions: prd.openQuestions.length,
1034
710
  decision_id: decisionId
@@ -1040,7 +716,7 @@ function decideEdgeCase(prd, input, today) {
1040
716
  if (!edgeCase) throw new Error(`Edge case "${input.edgeCaseId}" not found.`);
1041
717
  edgeCase.expectedBehavior = input.expectedBehavior.trim();
1042
718
  edgeCase.status = "decided";
1043
- appendChangeLog(prd, `Decided ${edgeCase.id}: ${edgeCase.case}`, today);
719
+ require_prd_operations.appendChangeLog(prd, `Decided ${edgeCase.id}: ${edgeCase.case}`, today);
1044
720
  return {
1045
721
  edge_case_id: edgeCase.id,
1046
722
  open_edge_cases: prd.edgeCases.filter((candidate) => candidate.status === "open").length
@@ -1059,7 +735,7 @@ function addGlossaryTerm(prd, input, today) {
1059
735
  definition: input.definition,
1060
736
  avoid: input.avoid
1061
737
  });
1062
- appendChangeLog(prd, `${existing ? "Redefined" : "Defined"} glossary term "${term}"`, today);
738
+ require_prd_operations.appendChangeLog(prd, `${existing ? "Redefined" : "Defined"} glossary term "${term}"`, today);
1063
739
  return {
1064
740
  term,
1065
741
  replaced: Boolean(existing),
@@ -1075,7 +751,7 @@ function updatePhase(prd, input, today) {
1075
751
  }
1076
752
  if (input.description !== void 0) phase.description = input.description;
1077
753
  if (input.color !== void 0) phase.color = input.color;
1078
- appendChangeLog(prd, `Updated phase ${phase.id}`, today);
754
+ require_prd_operations.appendChangeLog(prd, `Updated phase ${phase.id}`, today);
1079
755
  return phasesPayload(prd);
1080
756
  }
1081
757
  /** Deletes a phase; its stories stay in the PRD without a phase. */
@@ -1083,7 +759,7 @@ function deletePhase(prd, input, today) {
1083
759
  const phase = findPhase(prd, input.phaseId);
1084
760
  prd.customPhases = prd.customPhases.filter((other) => other.id !== phase.id);
1085
761
  renumberPhases(prd.customPhases);
1086
- appendChangeLog(prd, `Deleted phase ${phase.id} (${phase.name})`, today);
762
+ require_prd_operations.appendChangeLog(prd, `Deleted phase ${phase.id} (${phase.name})`, today);
1087
763
  return phasesPayload(prd);
1088
764
  }
1089
765
  function reorderPhases(prd, input, today) {
@@ -1092,7 +768,7 @@ function reorderPhases(prd, input, today) {
1092
768
  if (known.length !== given.length || known.some((id, index) => id !== given[index])) throw new Error(`phaseIds must list every phase exactly once. Phases: ${known.join(", ") || "none"}.`);
1093
769
  prd.customPhases = input.phaseIds.map((id) => findPhase(prd, id));
1094
770
  renumberPhases(prd.customPhases);
1095
- appendChangeLog(prd, `Reordered phases: ${input.phaseIds.join(", ")}`, today);
771
+ require_prd_operations.appendChangeLog(prd, `Reordered phases: ${input.phaseIds.join(", ")}`, today);
1096
772
  return phasesPayload(prd);
1097
773
  }
1098
774
  function findPhase(prd, phaseId) {
@@ -1119,8 +795,7 @@ function phasesPayload(prd) {
1119
795
  function normalizeText(value) {
1120
796
  return value.trim().replace(/\s+/g, " ").toLowerCase();
1121
797
  }
1122
- //#endregion
1123
- //#region src/prd.service.ts
798
+ // src/prd.service.ts
1124
799
  /**
1125
800
  * A write was based on an older revision of the PRD than the one on disk:
1126
801
  * someone else (an agent, Loop, another editor) changed it in between. Read
@@ -1144,11 +819,17 @@ function createPrdService(deps) {
1144
819
  }
1145
820
  var PrdService = class {
1146
821
  deps;
822
+ pendingWrite = Promise.resolve();
1147
823
  constructor(deps) {
1148
824
  this.deps = deps;
1149
825
  }
1150
826
  get prdsDir() {
1151
- return (0, node_path.join)(this.deps.rootPath, ".prds");
827
+ return this.deps.prdsDir ?? (0, node_path.join)(this.deps.rootPath, ".prds");
828
+ }
829
+ /** Path for agent-facing instructions, relative to the project when possible. */
830
+ get prdsPath() {
831
+ const path = (0, node_path.relative)(this.deps.rootPath, this.prdsDir);
832
+ return ((0, node_path.isAbsolute)(path) || path === ".." || path.startsWith(`..${node_path.sep}`) ? this.prdsDir : path || ".").split(node_path.sep).join("/");
1152
833
  }
1153
834
  async list() {
1154
835
  const filenames = await this.listFilenames();
@@ -1163,11 +844,20 @@ var PrdService = class {
1163
844
  progress: prd.progress.overall,
1164
845
  total_stories: prd.progress.total,
1165
846
  completed_stories: prd.progress.completed,
1166
- blocked_stories: prd.progress.blocked
847
+ blocked_stories: prd.progress.blocked,
848
+ ...prd.roadmap ? { roadmap: prd.roadmap } : {}
1167
849
  });
1168
850
  } catch (error) {
1169
851
  warnings.push(`Skipped ${filename}: ${error instanceof Error ? error.message : "unreadable"}`);
1170
852
  }
853
+ prds.sort((a, b) => {
854
+ const orderA = a.roadmap?.order ?? 1e400;
855
+ const orderB = b.roadmap?.order ?? 1e400;
856
+ const criticality = require_prompts.PrdCriticalitySchema.options;
857
+ const rankA = a.roadmap?.criticality ? criticality.indexOf(a.roadmap.criticality) : criticality.length;
858
+ const rankB = b.roadmap?.criticality ? criticality.indexOf(b.roadmap.criticality) : criticality.length;
859
+ return orderA === orderB ? rankA - rankB : orderA - orderB;
860
+ });
1171
861
  return {
1172
862
  prds,
1173
863
  total: prds.length,
@@ -1192,6 +882,7 @@ var PrdService = class {
1192
882
  const today = this.today();
1193
883
  const defaults = input.template ? require_prompts.getTemplate(input.template).defaults : {};
1194
884
  const prd = {
885
+ ...input.roadmap ? { roadmap: require_prompts.PrdRoadmapSchema.parse(input.roadmap) } : {},
1195
886
  introduction: {
1196
887
  title: input.title,
1197
888
  overview: input.overview,
@@ -1295,32 +986,34 @@ var PrdService = class {
1295
986
  async addUserStory(input) {
1296
987
  const filename = this.safeName(input.filename);
1297
988
  const prd = await this.load(filename);
1298
- const storyId = nextStoryId(prd);
989
+ const storyId = require_prd_operations.nextStoryId(prd);
1299
990
  const title = input.title?.trim() || titleFromAction(input.action);
1300
991
  const complexity = input.estimatedComplexity ?? assessComplexity(input.acceptanceCriteria);
992
+ const acceptanceCriteria = input.acceptanceCriteria.filter((entry) => entry.trim().length > 0);
1301
993
  prd.userStories.push({
1302
994
  id: storyId,
1303
995
  title,
1304
- userStory: renderUserStory(input),
996
+ userStory: require_prd_operations.renderUserStory(input),
1305
997
  businessValue: input.benefit,
1306
- acceptanceCriteria: input.acceptanceCriteria.filter((entry) => entry.trim().length > 0),
998
+ acceptanceCriteria,
1307
999
  status: "not_started",
1308
1000
  priority: input.priority,
1309
1001
  estimatedComplexity: complexity,
1310
1002
  dependencies: [],
1311
1003
  ...input.testSeams?.length ? { testSeams: input.testSeams } : {},
1004
+ ...input.proofs?.length ? { proofs: require_prd_operations.validateProofs(acceptanceCriteria, input.proofs) } : {},
1312
1005
  ...input.designNotes?.length ? { designNotes: input.designNotes } : {},
1313
1006
  ...input.securityNotes?.length ? { securityNotes: input.securityNotes } : {}
1314
1007
  });
1315
- if (input.dependencies?.length) findStory(prd, storyId).dependencies = validateDependencies(prd, storyId, input.dependencies);
1316
- if (input.attachmentIds?.length) findStory(prd, storyId).attachmentIds = validateAttachmentIds(prd, input.attachmentIds);
1317
- if (input.phaseId) assignStoryToPhase(prd, {
1008
+ if (input.dependencies?.length) require_prd_operations.findStory(prd, storyId).dependencies = require_prd_operations.validateDependencies(prd, storyId, input.dependencies);
1009
+ if (input.attachmentIds?.length) require_prd_operations.findStory(prd, storyId).attachmentIds = require_prd_operations.validateAttachmentIds(prd, input.attachmentIds);
1010
+ if (input.phaseId) require_prd_operations.assignStoryToPhase(prd, {
1318
1011
  filename,
1319
1012
  storyId,
1320
1013
  phaseId: input.phaseId
1321
1014
  }, this.today());
1322
- recomputeProgress(prd);
1323
- appendChangeLog(prd, `Added ${storyId} (${title})`, this.today());
1015
+ require_prd_operations.recomputeProgress(prd);
1016
+ require_prd_operations.appendChangeLog(prd, `Added ${storyId} (${title})`, this.today());
1324
1017
  await this.save(filename, prd);
1325
1018
  return {
1326
1019
  story_id: storyId,
@@ -1330,26 +1023,26 @@ var PrdService = class {
1330
1023
  };
1331
1024
  }
1332
1025
  async updateUserStory(input) {
1333
- return this.mutate(input.filename, (prd) => updateStory(prd, input, this.today()), input.expectedRevision);
1026
+ return this.mutate(input.filename, (prd) => require_prd_operations.updateStory(prd, input, this.today()), input.expectedRevision);
1334
1027
  }
1335
1028
  async deleteUserStory(input) {
1336
1029
  const filename = this.safeName(input.filename);
1337
1030
  const prd = await this.load(filename);
1338
- const result = deleteStory(prd, input.storyId, this.today());
1031
+ const result = require_prd_operations.deleteStory(prd, input.storyId, this.today());
1339
1032
  await this.save(filename, prd);
1340
1033
  return result;
1341
1034
  }
1342
1035
  async createCustomPhase(input) {
1343
1036
  const filename = this.safeName(input.filename);
1344
1037
  const prd = await this.load(filename);
1345
- const result = createPhase(prd, input, this.today());
1038
+ const result = require_prd_operations.createPhase(prd, input, this.today());
1346
1039
  await this.save(filename, prd);
1347
1040
  return result;
1348
1041
  }
1349
1042
  async assignStoryToPhase(input) {
1350
1043
  const filename = this.safeName(input.filename);
1351
1044
  const prd = await this.load(filename);
1352
- const result = assignStoryToPhase(prd, input, this.today());
1045
+ const result = require_prd_operations.assignStoryToPhase(prd, input, this.today());
1353
1046
  await this.save(filename, prd);
1354
1047
  return result;
1355
1048
  }
@@ -1358,7 +1051,11 @@ var PrdService = class {
1358
1051
  const current = await this.load(filename);
1359
1052
  const currentRevision = current.metadata.revision ?? 0;
1360
1053
  if (input.expectedRevision !== void 0 && input.expectedRevision !== currentRevision) throw new PrdRevisionConflictError(filename, input.expectedRevision, currentRevision);
1361
- assertCanEnterStatus(current, findStory(current, input.storyId), input.status);
1054
+ this.assertStoryStatusUpdate(current, input);
1055
+ if (input.recordDeviations?.length) {
1056
+ if (input.status !== "completed") throw new Error("Deviations are recorded only when a story is completed.");
1057
+ assertLoggedDeviations(require_prd_operations.findStory(current, input.storyId), input.recordDeviations);
1058
+ }
1362
1059
  let verification = null;
1363
1060
  if (input.status === "completed") {
1364
1061
  const result = await this.deps.verifyCompletion();
@@ -1370,8 +1067,7 @@ var PrdService = class {
1370
1067
  };
1371
1068
  }
1372
1069
  const prd = await this.load(filename);
1373
- const story = findStory(prd, input.storyId);
1374
- assertCanEnterStatus(prd, story, input.status);
1070
+ const story = this.assertStoryStatusUpdate(prd, input);
1375
1071
  const previousStatus = story.status;
1376
1072
  if (verification) {
1377
1073
  story.verification = {
@@ -1386,16 +1082,21 @@ var PrdService = class {
1386
1082
  delete story.completedAt;
1387
1083
  }
1388
1084
  story.status = input.status;
1085
+ if (input.status === "in_progress" || input.status === "review") {
1086
+ if (input.workerId) story.workerId = input.workerId;
1087
+ } else delete story.workerId;
1088
+ const recordedDecisions = input.recordDeviations?.length ? recordDeviations(prd, story, input.recordDeviations, this.today()) : [];
1389
1089
  if (input.notes) story.notes = input.notes;
1390
- recomputeProgress(prd);
1391
- appendChangeLog(prd, `${story.id} ${previousStatus} -> ${story.status}`, this.today());
1090
+ require_prd_operations.recomputeProgress(prd);
1091
+ require_prd_operations.appendChangeLog(prd, `${story.id} ${previousStatus} -> ${story.status}`, this.today());
1392
1092
  await this.save(filename, prd);
1393
1093
  return {
1394
1094
  story_id: story.id,
1395
1095
  title: story.title,
1396
1096
  status: story.status,
1397
1097
  progress: prd.progress.overall,
1398
- verification
1098
+ verification,
1099
+ recorded_decisions: recordedDecisions
1399
1100
  };
1400
1101
  }
1401
1102
  async exportMarkdown(input) {
@@ -1412,8 +1113,7 @@ var PrdService = class {
1412
1113
  async getImplementationPrompts(filename) {
1413
1114
  const name = this.safeName(filename);
1414
1115
  const prd = await this.load(name);
1415
- const prompts = [];
1416
- for (const story of prd.userStories.filter((s) => s.status === "not_started" && incompleteDependencies(prd, s).length === 0).slice(0, 3)) prompts.push(require_prompts.implementStoryPrompt(name, story.id));
1116
+ const prompts = require_prd_operations.pickNextStory(prd).story ? [require_prompts.implementStoryPrompt(name)] : [];
1417
1117
  return {
1418
1118
  prompts,
1419
1119
  total: prompts.length
@@ -1491,32 +1191,51 @@ var PrdService = class {
1491
1191
  return this.mutate(input.filename, (prd) => reorderPhases(prd, input, this.today()));
1492
1192
  }
1493
1193
  async getNextStory(filename) {
1494
- return pickNextStory(await this.load(this.safeName(filename)));
1194
+ return require_prd_operations.pickNextStory(await this.load(this.safeName(filename)));
1495
1195
  }
1496
1196
  async getStory(input) {
1497
1197
  const filename = this.safeName(input.filename);
1498
- return buildStoryContext(await this.load(filename), input.storyId, filename);
1198
+ const prd = await this.load(filename);
1199
+ return require_prd_operations.buildStoryContext(prd, input.storyId, filename, this.prdsPath);
1499
1200
  }
1500
1201
  async addStoryLog(input) {
1501
- const filename = this.safeName(input.filename);
1502
- const prd = await this.load(filename);
1503
- const result = appendStoryLog(prd, input.storyId, {
1504
- at: this.deps.now().toISOString(),
1505
- whatsNew: input.whatsNew,
1506
- technicalNotes: input.technicalNotes,
1507
- ...input.deviations?.length && { deviations: input.deviations }
1202
+ return this.mutate(input.filename, (prd) => {
1203
+ const story = require_prd_operations.findStory(prd, input.storyId);
1204
+ this.assertStoryOwner(story, input.workerId);
1205
+ if (input.workerId && !story.workerId) throw new Error(`Claim story ${story.id} before logging work.`);
1206
+ const result = require_prd_operations.appendStoryLog(prd, input.storyId, {
1207
+ at: this.deps.now().toISOString(),
1208
+ whatsNew: input.whatsNew,
1209
+ technicalNotes: input.technicalNotes,
1210
+ ...input.deviations?.length && { deviations: input.deviations }
1211
+ });
1212
+ require_prd_operations.appendChangeLog(prd, `Logged work on ${result.story_id}`, this.today());
1213
+ return result;
1508
1214
  });
1509
- appendChangeLog(prd, `Logged work on ${result.story_id}`, this.today());
1510
- await this.save(filename, prd);
1511
- return result;
1215
+ }
1216
+ assertStoryOwner(story, workerId) {
1217
+ if (story.workerId && story.workerId !== workerId) throw new Error(`Story ${story.id} is claimed by another worker.`);
1218
+ }
1219
+ assertStoryStatusUpdate(prd, input) {
1220
+ const story = require_prd_operations.findStory(prd, input.storyId);
1221
+ this.assertStoryOwner(story, input.workerId);
1222
+ require_prd_operations.assertCanEnterStatus(prd, story, input.status);
1223
+ if (input.workerId && !story.workerId) {
1224
+ const canClaim = input.status === "in_progress" && story.status !== "completed";
1225
+ const canResumeReview = input.status === "review" && story.status === "review";
1226
+ const canReportBlocker = input.status === "blocked" && story.status !== "completed" && Boolean(input.notes?.trim());
1227
+ if (!canClaim && !canResumeReview && !canReportBlocker) throw new Error(`Claim story ${story.id} before changing its status.`);
1228
+ }
1229
+ return story;
1512
1230
  }
1513
1231
  /** Files must already be in the PRD's folder, `.prds/<prd name>/`. */
1514
1232
  async addAttachment(input) {
1515
1233
  const filename = this.safeName(input.filename);
1516
1234
  if (input.path) {
1517
- const folder = require_prompts.attachmentsFolder(filename);
1518
- const path = require_prompts.assertSafeRelativePath(input.path, "attachment path");
1519
- if (!await this.deps.fileExists((0, node_path.join)(this.prdsDir, folder, path))) throw new Error(`File ".prds/${folder}/${path}" not found. Save it in .prds/${folder}/ first.`);
1235
+ const folder = require_attachment_paths.attachmentsFolder(filename);
1236
+ const path = require_attachment_paths.assertSafeRelativePath(input.path, "attachment path");
1237
+ const fullPath = (0, node_path.join)(this.prdsDir, folder, path);
1238
+ if (!await this.deps.fileExists(fullPath)) throw new Error(`File "${fullPath}" not found. Save it in ${this.prdsPath}/${folder}/ first.`);
1520
1239
  }
1521
1240
  return this.mutate(filename, (prd) => addAttachment(prd, {
1522
1241
  ...input,
@@ -1566,7 +1285,15 @@ var PrdService = class {
1566
1285
  }
1567
1286
  return normalizePrd(parsed, this.today());
1568
1287
  }
1569
- async save(filename, prd) {
1288
+ save(filename, prd) {
1289
+ const path = (0, node_path.join)(this.prdsDir, filename);
1290
+ const write = () => this.saveRevision(filename, prd);
1291
+ if (this.deps.withWriteLock) return this.deps.withWriteLock(path, write);
1292
+ const pending = this.pendingWrite.then(write);
1293
+ this.pendingWrite = pending.catch(() => void 0);
1294
+ return pending;
1295
+ }
1296
+ async saveRevision(filename, prd) {
1570
1297
  const today = this.today();
1571
1298
  const path = (0, node_path.join)(this.prdsDir, filename);
1572
1299
  const loadedRevision = prd.metadata.revision ?? 0;
@@ -1588,7 +1315,7 @@ var PrdService = class {
1588
1315
  }
1589
1316
  }
1590
1317
  safeName(filename) {
1591
- return require_prompts.assertSafeFileName(filename, "PRD file name");
1318
+ return require_attachment_paths.assertSafeFileName(filename, "PRD file name");
1592
1319
  }
1593
1320
  today() {
1594
1321
  return this.deps.now().toISOString().slice(0, 10);
@@ -1608,6 +1335,7 @@ function normalizePrd(input, today) {
1608
1335
  const highestQuestion = openQuestions.reduce((max, question) => Math.max(max, Number(/^Q(\d+)$/.exec(question.id)?.[1] ?? 0)), 0);
1609
1336
  return {
1610
1337
  ...prd,
1338
+ roadmap: require_prompts.PrdRoadmapSchema.passthrough().optional().parse(prd.roadmap),
1611
1339
  introduction: {
1612
1340
  title: prd.introduction?.title ?? "Untitled PRD",
1613
1341
  overview: prd.introduction?.overview ?? "",
@@ -1666,13 +1394,13 @@ function normalizePrd(input, today) {
1666
1394
  targetMetrics: prd.measurementPlan?.targetMetrics ?? [],
1667
1395
  guardrailMetrics: prd.measurementPlan?.guardrailMetrics ?? []
1668
1396
  },
1669
- edgeCases: normalizeEdgeCases(prd.edgeCases),
1397
+ edgeCases: require_prd_operations.normalizeEdgeCases(prd.edgeCases),
1670
1398
  securityConsiderations: Array.isArray(prd.securityConsiderations) ? prd.securityConsiderations.filter((item) => typeof item === "string") : [],
1671
1399
  notApplicable: normalizeNotApplicable(prd.notApplicable),
1672
1400
  designGuidance: Array.isArray(prd.designGuidance) ? prd.designGuidance.filter((item) => typeof item === "string") : [],
1673
1401
  decisionLog: prd.decisionLog ?? [],
1674
1402
  glossary: prd.glossary ?? [],
1675
- attachments: require_prompts.normalizeAttachments(prd.attachments),
1403
+ attachments: require_attachment_paths.normalizeAttachments(prd.attachments),
1676
1404
  agentTaskPackets: prd.agentTaskPackets ?? [],
1677
1405
  changeLog: prd.changeLog ?? [],
1678
1406
  metadata: {
@@ -1711,7 +1439,6 @@ function assessComplexity(criteria) {
1711
1439
  if (count <= 8) return "L";
1712
1440
  return "XL";
1713
1441
  }
1714
- //#endregion
1715
1442
  exports.AddAttachmentInputSchema = require_prompts.AddAttachmentInputSchema;
1716
1443
  exports.AddAttachmentOutputSchema = require_prompts.AddAttachmentOutputSchema;
1717
1444
  exports.AddDecisionInputSchema = require_prompts.AddDecisionInputSchema;
@@ -1730,6 +1457,7 @@ exports.CreateCustomPhaseInputSchema = require_prompts.CreateCustomPhaseInputSch
1730
1457
  exports.CreateCustomPhaseOutputSchema = require_prompts.CreateCustomPhaseOutputSchema;
1731
1458
  exports.CreatePrdInputSchema = require_prompts.CreatePrdInputSchema;
1732
1459
  exports.CreatePrdOutputSchema = require_prompts.CreatePrdOutputSchema;
1460
+ exports.CriterionProofSchema = require_prompts.CriterionProofSchema;
1733
1461
  exports.CustomPhaseSchema = require_prompts.CustomPhaseSchema;
1734
1462
  exports.DecideEdgeCaseInputSchema = require_prompts.DecideEdgeCaseInputSchema;
1735
1463
  exports.DecideEdgeCaseOutputSchema = require_prompts.DecideEdgeCaseOutputSchema;
@@ -1762,10 +1490,14 @@ exports.NOT_APPLICABLE_TOPICS = NOT_APPLICABLE_TOPICS;
1762
1490
  exports.NotApplicableTopicSchema = require_prompts.NotApplicableTopicSchema;
1763
1491
  exports.PRD_TEMPLATES = require_prompts.PRD_TEMPLATES;
1764
1492
  exports.PhasesOutputSchema = require_prompts.PhasesOutputSchema;
1493
+ exports.PrdCriticalitySchema = require_prompts.PrdCriticalitySchema;
1765
1494
  exports.PrdRevisionConflictError = PrdRevisionConflictError;
1495
+ exports.PrdRoadmapSchema = require_prompts.PrdRoadmapSchema;
1496
+ exports.PrdRoadmapUpdateSchema = require_prompts.PrdRoadmapUpdateSchema;
1766
1497
  exports.PrdSectionValueSchemas = require_prompts.PrdSectionValueSchemas;
1767
1498
  exports.PrdService = PrdService;
1768
1499
  exports.PrdSummarySchema = require_prompts.PrdSummarySchema;
1500
+ exports.ProofKindSchema = require_prompts.ProofKindSchema;
1769
1501
  exports.RemoveAttachmentInputSchema = require_prompts.RemoveAttachmentInputSchema;
1770
1502
  exports.RemoveAttachmentOutputSchema = require_prompts.RemoveAttachmentOutputSchema;
1771
1503
  exports.ReorderPhasesInputSchema = require_prompts.ReorderPhasesInputSchema;
@@ -1787,35 +1519,36 @@ exports.UpdateStoryStatusInputSchema = require_prompts.UpdateStoryStatusInputSch
1787
1519
  exports.UpdateStoryStatusOutputSchema = require_prompts.UpdateStoryStatusOutputSchema;
1788
1520
  exports.UpdateUserStoryInputSchema = require_prompts.UpdateUserStoryInputSchema;
1789
1521
  exports.UpdateUserStoryOutputSchema = require_prompts.UpdateUserStoryOutputSchema;
1790
- exports.appendChangeLog = appendChangeLog;
1791
- exports.appendStoryLog = appendStoryLog;
1522
+ exports.appendChangeLog = require_prd_operations.appendChangeLog;
1523
+ exports.appendStoryLog = require_prd_operations.appendStoryLog;
1792
1524
  exports.architectPrdPrompt = require_prompts.architectPrdPrompt;
1793
- exports.assertCanEnterStatus = assertCanEnterStatus;
1794
- exports.assignStoryToPhase = assignStoryToPhase;
1795
- exports.attachmentProjectPath = require_prompts.attachmentProjectPath;
1796
- exports.attachmentsFolder = require_prompts.attachmentsFolder;
1797
- exports.buildStoryContext = buildStoryContext;
1525
+ exports.assertCanEnterStatus = require_prd_operations.assertCanEnterStatus;
1526
+ exports.assignStoryToPhase = require_prd_operations.assignStoryToPhase;
1527
+ exports.attachmentProjectPath = require_attachment_paths.attachmentProjectPath;
1528
+ exports.attachmentsFolder = require_attachment_paths.attachmentsFolder;
1529
+ exports.buildStoryContext = require_prd_operations.buildStoryContext;
1798
1530
  exports.checkPlan = checkPlan;
1799
- exports.createPhase = createPhase;
1531
+ exports.createPhase = require_prd_operations.createPhase;
1800
1532
  exports.createPrdService = createPrdService;
1801
- exports.deleteStory = deleteStory;
1802
- exports.findAttachment = findAttachment;
1803
- exports.findStory = findStory;
1533
+ exports.deleteStory = require_prd_operations.deleteStory;
1534
+ exports.findAttachment = require_prd_operations.findAttachment;
1535
+ exports.findStory = require_prd_operations.findStory;
1804
1536
  exports.formatPrdMarkdown = formatPrdMarkdown;
1805
1537
  exports.getTemplate = require_prompts.getTemplate;
1806
1538
  exports.implementStoryPrompt = require_prompts.implementStoryPrompt;
1807
- exports.incompleteDependencies = incompleteDependencies;
1539
+ exports.incompleteDependencies = require_prd_operations.incompleteDependencies;
1808
1540
  exports.isNotApplicable = isNotApplicable;
1809
- exports.nextId = nextId;
1810
- exports.nextStoryId = nextStoryId;
1541
+ exports.nextId = require_prd_operations.nextId;
1542
+ exports.nextStoryId = require_prd_operations.nextStoryId;
1811
1543
  exports.normalizePrd = normalizePrd;
1812
- exports.pickNextStory = pickNextStory;
1813
- exports.recomputeProgress = recomputeProgress;
1814
- exports.renderUserStory = renderUserStory;
1815
- exports.resolveAttachments = require_prompts.resolveAttachments;
1544
+ exports.pickNextStory = require_prd_operations.pickNextStory;
1545
+ exports.recomputeProgress = require_prd_operations.recomputeProgress;
1546
+ exports.renderUserStory = require_prd_operations.renderUserStory;
1547
+ exports.resolveAttachments = require_attachment_paths.resolveAttachments;
1816
1548
  exports.reviewStoryPrompt = require_prompts.reviewStoryPrompt;
1817
1549
  exports.shapePrdPrompt = require_prompts.shapePrdPrompt;
1818
- exports.splitUserStory = splitUserStory;
1819
- exports.updateStory = updateStory;
1820
- exports.validateAttachmentIds = validateAttachmentIds;
1821
- exports.validateDependencies = validateDependencies;
1550
+ exports.splitUserStory = require_prd_operations.splitUserStory;
1551
+ exports.updateStory = require_prd_operations.updateStory;
1552
+ exports.validateAttachmentIds = require_prd_operations.validateAttachmentIds;
1553
+ exports.validateDependencies = require_prd_operations.validateDependencies;
1554
+ exports.validateProofs = require_prd_operations.validateProofs;