@makerkit/prd 0.0.4 → 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} +155 -562
  10. package/{index.mjs → dist/index.mjs} +87 -497
  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-oI_6dxvx.js → dist/prompts-1qhax_dj.js} +113 -164
  25. package/{prompts-CPlFVutB.mjs → dist/prompts-BlsYD0gf.mjs} +96 -129
  26. package/{prd.service-CV0-aQHk.d.ts → dist/schema-BwTnt0B9.d.ts} +424 -336
  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 -233
  63. /package/{LICENSE → dist/LICENSE} +0 -0
@@ -1,466 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_prompts = require("./prompts-oI_6dxvx.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
- if (input.proofs === void 0 && story.proofs?.length) {
143
- const kept = story.proofs.filter((proof) => story.acceptanceCriteria.includes(proof.criterion));
144
- if (kept.length !== story.proofs.length) {
145
- story.proofs = kept;
146
- updated.push("proofs");
147
- }
148
- }
149
- }
150
- if (input.proofs !== void 0) {
151
- story.proofs = validateProofs(story.acceptanceCriteria, input.proofs);
152
- updated.push("proofs");
153
- }
154
- if (input.priority !== void 0) {
155
- story.priority = input.priority;
156
- updated.push("priority");
157
- }
158
- if (input.estimatedComplexity !== void 0) {
159
- story.estimatedComplexity = input.estimatedComplexity;
160
- updated.push("estimatedComplexity");
161
- }
162
- if (input.dependencies !== void 0) {
163
- story.dependencies = validateDependencies(prd, story.id, input.dependencies);
164
- updated.push("dependencies");
165
- }
166
- if (input.notes !== void 0) {
167
- story.notes = input.notes;
168
- updated.push("notes");
169
- }
170
- if (input.attachmentIds !== void 0) {
171
- story.attachmentIds = validateAttachmentIds(prd, input.attachmentIds);
172
- updated.push("attachmentIds");
173
- }
174
- if (input.phaseId !== void 0) {
175
- assignStoryToPhase(prd, {
176
- filename: input.filename,
177
- storyId: story.id,
178
- phaseId: input.phaseId
179
- }, today);
180
- updated.push("phase");
181
- }
182
- 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, proofs, designNotes, securityNotes, attachmentIds, phaseId.`);
183
- appendChangeLog(prd, `Updated ${story.id} (${updated.join(", ")})`, today);
184
- return {
185
- story_id: story.id,
186
- title: story.title,
187
- updated_fields: [...new Set(updated)],
188
- story
189
- };
190
- }
191
- function findAttachment(prd, attachmentId) {
192
- const attachment = prd.attachments.find((candidate) => candidate.id === attachmentId);
193
- if (!attachment) throw new Error(`Attachment "${attachmentId}" not found.`);
194
- return attachment;
195
- }
196
- /** Attachment ids must name attachments in the PRD. */
197
- function validateAttachmentIds(prd, ids) {
198
- for (const id of ids) findAttachment(prd, id);
199
- return [...new Set(ids)];
200
- }
201
- /**
202
- * Each proof must name one of the story's criteria, at most once, and a proof
203
- * no test makes must say why — the reason is what a reviewer judges.
204
- */
205
- function validateProofs(criteria, proofs) {
206
- const seen = /* @__PURE__ */ new Set();
207
- return proofs.map((proof) => {
208
- const criterion = criteria.find((candidate) => candidate.trim() === proof.criterion.trim());
209
- if (criterion === void 0) throw new Error(`Proof names a criterion the story does not have: "${proof.criterion}". Copy the criterion exactly.`);
210
- if (seen.has(criterion)) throw new Error(`Criterion "${criterion}" has more than one proof.`);
211
- seen.add(criterion);
212
- const reason = proof.reason?.trim();
213
- if ((proof.kind === "manual" || proof.kind === "post-deploy") && !reason) throw new Error(`A ${proof.kind} proof needs a reason: why no test can prove "${criterion}".`);
214
- const rubric = (proof.rubric ?? []).map((point) => point.trim()).filter(Boolean);
215
- if (proof.kind === "judge" && rubric.length === 0) throw new Error(`A judge proof needs a rubric: what the reviewer scores "${criterion}" against.`);
216
- const seam = proof.seam?.trim();
217
- const fallback = proof.fallback?.trim();
218
- return {
219
- criterion,
220
- kind: proof.kind,
221
- ...seam ? { seam } : {},
222
- ...reason ? { reason } : {},
223
- ...fallback ? { fallback } : {},
224
- ...rubric.length > 0 ? { rubric } : {}
225
- };
226
- });
227
- }
228
- /**
229
- * Dependencies must name real stories, never the story itself, and never form
230
- * a cycle — an unsatisfiable order is worse than no order at all.
231
- */
232
- function validateDependencies(prd, storyId, dependencies) {
233
- const unique = [...new Set(dependencies.filter((id) => id.trim().length > 0))];
234
- for (const id of unique) {
235
- if (id === storyId) throw new Error(`Story ${storyId} cannot depend on itself.`);
236
- findStory(prd, id);
237
- }
238
- const cycle = findCycle(new Map(prd.userStories.map((story) => [story.id, story.id === storyId ? unique : story.dependencies])), storyId);
239
- if (cycle) throw new Error(`Dependency cycle: ${cycle.join(" -> ")}. Remove one of these links.`);
240
- return unique;
241
- }
242
- function findCycle(edges, from) {
243
- const visiting = /* @__PURE__ */ new Set();
244
- const done = /* @__PURE__ */ new Set();
245
- const walk = (id, trail) => {
246
- if (done.has(id)) return void 0;
247
- if (visiting.has(id)) return [...trail, id];
248
- visiting.add(id);
249
- for (const next of edges.get(id) ?? []) {
250
- const found = walk(next, [...trail, id]);
251
- if (found) return found;
252
- }
253
- visiting.delete(id);
254
- done.add(id);
255
- };
256
- return walk(from, []);
257
- }
258
- function deleteStory(prd, storyId, today) {
259
- const story = findStory(prd, storyId);
260
- prd.userStories = prd.userStories.filter((candidate) => candidate.id !== storyId);
261
- const dependencyReferencesRemoved = [];
262
- for (const candidate of prd.userStories) if (candidate.dependencies.includes(storyId)) {
263
- candidate.dependencies = candidate.dependencies.filter((id) => id !== storyId);
264
- dependencyReferencesRemoved.push(candidate.id);
265
- }
266
- const phasesUpdated = [];
267
- for (const phase of prd.customPhases) if (phase.userStoryIds.includes(storyId)) {
268
- phase.userStoryIds = phase.userStoryIds.filter((id) => id !== storyId);
269
- phasesUpdated.push(phase.id);
270
- }
271
- prd.edgeCases = prd.edgeCases.flatMap((edgeCase) => {
272
- if (!edgeCase.storyIds?.includes(storyId)) return [edgeCase];
273
- const storyIds = edgeCase.storyIds.filter((id) => id !== storyId);
274
- return storyIds.length > 0 ? [{
275
- ...edgeCase,
276
- storyIds
277
- }] : [];
278
- });
279
- for (const question of prd.openQuestions) if (question.storyIds?.includes(storyId)) {
280
- const storyIds = question.storyIds.filter((id) => id !== storyId);
281
- if (storyIds.length > 0) question.storyIds = storyIds;
282
- else delete question.storyIds;
283
- }
284
- for (const entry of prd.decisionLog) if (entry.topic?.startsWith(`story:${storyId}:`) && entry.status === "accepted") entry.status = "superseded";
285
- recomputeProgress(prd);
286
- appendChangeLog(prd, `Deleted ${storyId} (${story.title})`, today);
287
- return {
288
- story_id: storyId,
289
- title: story.title,
290
- total_stories: prd.userStories.length,
291
- progress: prd.progress.overall,
292
- dependency_references_removed: dependencyReferencesRemoved,
293
- phases_updated: phasesUpdated
294
- };
295
- }
296
- function createPhase(prd, input, today) {
297
- const name = input.name.trim();
298
- if (prd.customPhases.some((phase) => phase.name.toLowerCase() === name.toLowerCase())) throw new Error(`A phase named "${name}" already exists.`);
299
- const phase = {
300
- id: nextId(prd.customPhases, "PHASE"),
301
- name,
302
- description: input.description,
303
- color: input.color,
304
- order: prd.customPhases.length,
305
- userStoryIds: []
306
- };
307
- prd.customPhases.push(phase);
308
- appendChangeLog(prd, `Created phase ${phase.id} (${name})`, today);
309
- return {
310
- phase: {
311
- id: phase.id,
312
- name: phase.name,
313
- description: phase.description,
314
- color: phase.color,
315
- order: phase.order,
316
- user_story_ids: phase.userStoryIds
317
- },
318
- total_phases: prd.customPhases.length
319
- };
320
- }
321
- function assignStoryToPhase(prd, input, today) {
322
- findStory(prd, input.storyId);
323
- const target = input.phaseId === null ? void 0 : prd.customPhases.find((phase) => phase.id === input.phaseId);
324
- if (input.phaseId !== null && !target) {
325
- const known = prd.customPhases.map((phase) => phase.id).join(", ");
326
- throw new Error(`Phase "${input.phaseId}" not found.` + (known ? ` Known phases: ${known}.` : " This PRD has no phases yet."));
327
- }
328
- const previous = prd.customPhases.find((phase) => phase.userStoryIds.includes(input.storyId));
329
- for (const phase of prd.customPhases) phase.userStoryIds = phase.userStoryIds.filter((id) => id !== input.storyId);
330
- target?.userStoryIds.push(input.storyId);
331
- appendChangeLog(prd, target ? `Assigned ${input.storyId} to ${target.id} (${target.name})` : `Removed ${input.storyId} from all phases`, today);
332
- return {
333
- story_id: input.storyId,
334
- phase_id: target?.id ?? null,
335
- phase_name: target?.name ?? null,
336
- moved_from: previous && previous.id !== target?.id ? previous.id : null
337
- };
338
- }
339
- /** Statuses that mean work on the story has started or finished. */
340
- const WORK_STATUSES = [
341
- "in_progress",
342
- "review",
343
- "completed"
344
- ];
345
- const PRIORITY_ORDER = {
346
- P0: 0,
347
- P1: 1,
348
- P2: 2,
349
- P3: 3
350
- };
351
- /** Dependencies of `story` that are not completed yet. */
352
- function incompleteDependencies(prd, story) {
353
- return story.dependencies.filter((id) => {
354
- return prd.userStories.find((candidate) => candidate.id === id)?.status !== "completed";
355
- });
356
- }
357
- /**
358
- * A story cannot be worked on, reviewed or completed before the stories it
359
- * depends on are completed. `not_started`, `research` and `blocked` stay
360
- * available so a story can still be planned or parked.
361
- */
362
- function assertCanEnterStatus(prd, story, status) {
363
- if (!WORK_STATUSES.includes(status)) return;
364
- const waitingOn = incompleteDependencies(prd, story);
365
- 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.`);
366
- }
367
- /** Position of the story's phase; stories without a phase come last. */
368
- function phaseRank(prd, storyId) {
369
- const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(storyId));
370
- return phase ? phase.order : Number.MAX_SAFE_INTEGER;
371
- }
372
- /**
373
- * The next story to start: not started, every dependency completed, ordered
374
- * by phase, then priority, then position in the PRD.
375
- */
376
- function pickNextStory(prd) {
377
- const notStarted = prd.userStories.filter((story) => story.status === "not_started");
378
- 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));
379
- const waiting = notStarted.map((story) => ({
380
- id: story.id,
381
- title: story.title,
382
- waiting_on: incompleteDependencies(prd, story)
383
- })).filter((entry) => entry.waiting_on.length > 0);
384
- return {
385
- story: ready[0] ?? null,
386
- ready_count: ready.length,
387
- in_progress: prd.userStories.filter((story) => story.status === "in_progress").map((story) => story.id),
388
- waiting
389
- };
390
- }
391
- /**
392
- * Everything an agent needs to work on one story without loading the whole
393
- * PRD: the story, the scope boundaries, its dependencies with their hand-off
394
- * logs, and the log of the most recently completed story.
395
- */
396
- /** `filename` is the PRD's file name, used to give attachment paths. */
397
- function buildStoryContext(prd, storyId, filename) {
398
- const story = findStory(prd, storyId);
399
- const linked = new Set(story.attachmentIds ?? []);
400
- const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(story.id)) ?? null;
401
- 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;
402
- return {
403
- prd: {
404
- title: prd.introduction.title,
405
- overview: prd.introduction.overview,
406
- non_goals: prd.nonGoals,
407
- out_of_scope: prd.outOfScope,
408
- global_acceptance_criteria: prd.acceptanceCriteria.global,
409
- attachments: require_prompts.resolveAttachments(filename, prd.attachments)
410
- },
411
- story,
412
- attachments: require_prompts.resolveAttachments(filename, prd.attachments.filter((attachment) => linked.has(attachment.id))),
413
- phase: phase ? {
414
- id: phase.id,
415
- name: phase.name
416
- } : null,
417
- edge_cases: edgeCasesForStory(prd, story.id),
418
- open_questions: prd.openQuestions.filter((question) => question.storyIds?.includes(story.id)),
419
- security: {
420
- permissions: prd.technicalContracts.permissions,
421
- compliance: prd.technicalRequirements.complianceRequirements,
422
- considerations: prd.securityConsiderations,
423
- story_notes: story.securityNotes ?? []
424
- },
425
- not_applicable: prd.notApplicable,
426
- design: {
427
- guidance: prd.designGuidance,
428
- story_notes: story.designNotes ?? [],
429
- decisions: designDecisions(prd).map(({ id, decision, rationale }) => ({
430
- id,
431
- decision,
432
- rationale
433
- }))
434
- },
435
- dependencies: story.dependencies.map((id) => {
436
- const dependency = prd.userStories.find((candidate) => candidate.id === id);
437
- return {
438
- id,
439
- title: dependency?.title ?? null,
440
- status: dependency?.status ?? null,
441
- log: dependency?.log ?? []
442
- };
443
- }),
444
- previous_story: lastCompleted ? {
445
- id: lastCompleted.id,
446
- title: lastCompleted.title,
447
- log: lastCompleted.log ?? []
448
- } : null
449
- };
450
- }
451
- function appendStoryLog(prd, storyId, entry) {
452
- const story = findStory(prd, storyId);
453
- story.log = [...story.log ?? [], entry];
454
- return {
455
- story_id: story.id,
456
- entries: story.log.length
457
- };
458
- }
459
- function withoutBlanks(entries) {
460
- return entries.map((entry) => entry.trim()).filter(Boolean);
461
- }
462
- //#endregion
463
- //#region src/applicability.ts
6
+ // src/applicability.ts
464
7
  /**
465
8
  * Parts of a PRD that can be marked "not applicable" (e.g. no rollout plan
466
9
  * for an internal tool), so the plan check stops asking for them and agents
@@ -497,15 +40,14 @@ function setNotApplicable(prd, input, today) {
497
40
  const { [input.topic]: _removed, ...rest } = prd.notApplicable;
498
41
  prd.notApplicable = rest;
499
42
  }
500
- 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);
501
44
  return {
502
45
  topic: input.topic,
503
46
  not_applicable: input.notApplicable,
504
47
  reason: prd.notApplicable[input.topic] ?? null
505
48
  };
506
49
  }
507
- //#endregion
508
- //#region src/attachments.ts
50
+ // src/attachments.ts
509
51
  /**
510
52
  * Adds an attachment and links it to the given stories. The caller checks
511
53
  * that a `path` exists on disk; this only validates the PRD.
@@ -513,8 +55,8 @@ function setNotApplicable(prd, input, today) {
513
55
  function addAttachment(prd, input, today) {
514
56
  if (Boolean(input.path) === Boolean(input.url)) throw new Error("Give either path or url for an attachment, not both.");
515
57
  if (input.url && !/^https?:\/\//i.test(input.url)) throw new Error("An attachment url must start with http:// or https://.");
516
- const path = input.path ? require_prompts.assertSafeRelativePath(input.path, "attachment path") : void 0;
517
- 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));
518
60
  const id = nextAttachmentId(prd);
519
61
  prd.attachments.push({
520
62
  id,
@@ -523,10 +65,10 @@ function addAttachment(prd, input, today) {
523
65
  ...input.note ? { note: input.note } : {}
524
66
  });
525
67
  for (const story of stories) story.attachmentIds = [.../* @__PURE__ */ new Set([...story.attachmentIds ?? [], id])];
526
- appendChangeLog(prd, `Added attachment ${id} (${input.title})`, today);
68
+ require_prd_operations.appendChangeLog(prd, `Added attachment ${id} (${input.title})`, today);
527
69
  return {
528
70
  attachment_id: id,
529
- path: path ? require_prompts.attachmentProjectPath(input.filename, path) : null,
71
+ path: path ? require_attachment_paths.attachmentProjectPath(input.filename, path) : null,
530
72
  stories_updated: stories.map((story) => story.id),
531
73
  total_attachments: prd.attachments.length
532
74
  };
@@ -548,14 +90,14 @@ function nextAttachmentId(prd) {
548
90
  * on disk.
549
91
  */
550
92
  function removeAttachment(prd, attachmentId, today) {
551
- const attachment = findAttachment(prd, attachmentId);
93
+ const attachment = require_prd_operations.findAttachment(prd, attachmentId);
552
94
  prd.attachments = prd.attachments.filter((candidate) => candidate.id !== attachment.id);
553
95
  const storiesUpdated = [];
554
96
  for (const story of prd.userStories) if (story.attachmentIds?.includes(attachment.id)) {
555
97
  story.attachmentIds = story.attachmentIds.filter((id) => id !== attachment.id);
556
98
  storiesUpdated.push(story.id);
557
99
  }
558
- appendChangeLog(prd, `Removed attachment ${attachment.id} (${attachment.title})`, today);
100
+ require_prd_operations.appendChangeLog(prd, `Removed attachment ${attachment.id} (${attachment.title})`, today);
559
101
  return {
560
102
  attachment_id: attachment.id,
561
103
  stories_updated: storiesUpdated,
@@ -567,7 +109,7 @@ function removeAttachment(prd, attachmentId, today) {
567
109
  * storyIds, links are added and removed so exactly those stories use it.
568
110
  */
569
111
  function updateAttachment(prd, input, today) {
570
- const attachment = findAttachment(prd, input.attachmentId);
112
+ const attachment = require_prd_operations.findAttachment(prd, input.attachmentId);
571
113
  if (input.title !== void 0) attachment.title = input.title;
572
114
  if (input.note !== void 0) {
573
115
  if (input.note.trim()) attachment.note = input.note;
@@ -575,7 +117,7 @@ function updateAttachment(prd, input, today) {
575
117
  }
576
118
  const storiesUpdated = [];
577
119
  if (input.storyIds !== void 0) {
578
- 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));
579
121
  for (const story of prd.userStories) {
580
122
  const linked = story.attachmentIds?.includes(attachment.id) ?? false;
581
123
  if (wanted.has(story.id) && !linked) {
@@ -587,14 +129,13 @@ function updateAttachment(prd, input, today) {
587
129
  }
588
130
  }
589
131
  }
590
- appendChangeLog(prd, `Updated attachment ${attachment.id} (${attachment.title})`, today);
132
+ require_prd_operations.appendChangeLog(prd, `Updated attachment ${attachment.id} (${attachment.title})`, today);
591
133
  return {
592
134
  attachment_id: attachment.id,
593
135
  stories_updated: storiesUpdated
594
136
  };
595
137
  }
596
- //#endregion
597
- //#region src/markdown.ts
138
+ // src/markdown.ts
598
139
  const STATUS_LABELS = {
599
140
  not_started: "[not started]",
600
141
  research: "[research]",
@@ -710,7 +251,7 @@ function formatStory(story) {
710
251
  }
711
252
  function formatAttachment(attachment, filename) {
712
253
  const title = oneLine(attachment.title).replace(/[[\]]/g, "\\$&");
713
- 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;
714
255
  const label = target ? `[${title}](${target})` : `${title} (${attachment.path})`;
715
256
  const note = attachment.note ? ` - ${oneLine(attachment.note)}` : "";
716
257
  return `- ${attachment.id}: ${label}${note}`;
@@ -727,8 +268,7 @@ function bullets(items, emptyLabel) {
727
268
  if (items.length === 0) return emptyLabel ? [`- ${emptyLabel}`] : [];
728
269
  return items.map((item) => `- ${item}`);
729
270
  }
730
- //#endregion
731
- //#region src/open-questions.ts
271
+ // src/open-questions.ts
732
272
  /**
733
273
  * Open questions as stored. Older files hold plain strings; they become
734
274
  * questions with ids in list order. Entries without question text are dropped.
@@ -787,8 +327,7 @@ function blockingQuestions(prd) {
787
327
  const unfinished = new Set(prd.userStories.filter((story) => story.status !== "completed").map((story) => story.id));
788
328
  return prd.openQuestions.filter((question) => question.storyIds?.some((id) => unfinished.has(id)));
789
329
  }
790
- //#endregion
791
- //#region src/plan-check.ts
330
+ // src/plan-check.ts
792
331
  /** The not-applicable topic each "missing" check is about. */
793
332
  const CHECK_TOPICS = {
794
333
  "edge-cases": "edgeCases",
@@ -1002,8 +541,7 @@ function checkPlan(prd) {
1002
541
  items: applicable
1003
542
  };
1004
543
  }
1005
- //#endregion
1006
- //#region src/planning-operations.ts
544
+ // src/planning-operations.ts
1007
545
  /**
1008
546
  * Pure transforms for shaping a PRD after it was created: sections, decisions,
1009
547
  * open questions, glossary and phases. Same contract as `prd-operations`:
@@ -1025,12 +563,21 @@ function updatePrdSection(prd, input, today) {
1025
563
  }
1026
564
  const value = parsed.data;
1027
565
  let updated;
1028
- 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") {
1029
576
  const risks = value;
1030
577
  const assigned = [];
1031
578
  for (const risk of risks) assigned.push({
1032
579
  ...risk,
1033
- id: risk.id ?? nextId(assigned, "RISK")
580
+ id: risk.id ?? require_prd_operations.nextId(assigned, "RISK")
1034
581
  });
1035
582
  prd.risks = assigned;
1036
583
  updated = assigned.map((risk) => risk.id);
@@ -1039,7 +586,7 @@ function updatePrdSection(prd, input, today) {
1039
586
  const assigned = [];
1040
587
  for (const item of items) assigned.push({
1041
588
  ...item,
1042
- id: item.id ?? nextId(assigned, "DEP")
589
+ id: item.id ?? require_prd_operations.nextId(assigned, "DEP")
1043
590
  });
1044
591
  prd.dependencies = assigned;
1045
592
  updated = assigned.map((item) => item.id);
@@ -1070,7 +617,7 @@ function updatePrdSection(prd, input, today) {
1070
617
  const { storyIds: linked, ...rest } = item;
1071
618
  assigned.push({
1072
619
  ...rest,
1073
- id: item.id ?? nextId([...prd.edgeCases, ...assigned], "EC"),
620
+ id: item.id ?? require_prd_operations.nextId([...prd.edgeCases, ...assigned], "EC"),
1074
621
  ...linked?.length ? { storyIds: linked } : {}
1075
622
  });
1076
623
  }
@@ -1085,7 +632,7 @@ function updatePrdSection(prd, input, today) {
1085
632
  Object.assign(prd[key], value);
1086
633
  updated = Object.keys(value);
1087
634
  }
1088
- appendChangeLog(prd, `Updated ${input.section}`, today);
635
+ require_prd_operations.appendChangeLog(prd, `Updated ${input.section}`, today);
1089
636
  return {
1090
637
  section: input.section,
1091
638
  updated
@@ -1099,7 +646,7 @@ function addDecision(prd, input, today) {
1099
646
  previous.status = "superseded";
1100
647
  superseded = previous.id;
1101
648
  }
1102
- const id = nextId(prd.decisionLog, "DEC");
649
+ const id = require_prd_operations.nextId(prd.decisionLog, "DEC");
1103
650
  prd.decisionLog.push({
1104
651
  id,
1105
652
  date: today,
@@ -1109,7 +656,7 @@ function addDecision(prd, input, today) {
1109
656
  ...input.owner ? { owner: input.owner } : {},
1110
657
  ...input.topic ? { topic: input.topic } : {}
1111
658
  });
1112
- appendChangeLog(prd, superseded ? `Recorded ${id} (supersedes ${superseded})` : `Recorded ${id}`, today);
659
+ require_prd_operations.appendChangeLog(prd, superseded ? `Recorded ${id} (supersedes ${superseded})` : `Recorded ${id}`, today);
1113
660
  return {
1114
661
  decision_id: id,
1115
662
  superseded,
@@ -1157,7 +704,7 @@ function resolveOpenQuestion(prd, input, today) {
1157
704
  topic: `open-question:${question.id}`,
1158
705
  status: "accepted"
1159
706
  }, today).decision_id;
1160
- else appendChangeLog(prd, `Resolved ${question.id}: ${question.question}`, today);
707
+ else require_prd_operations.appendChangeLog(prd, `Resolved ${question.id}: ${question.question}`, today);
1161
708
  return {
1162
709
  remaining_questions: prd.openQuestions.length,
1163
710
  decision_id: decisionId
@@ -1169,7 +716,7 @@ function decideEdgeCase(prd, input, today) {
1169
716
  if (!edgeCase) throw new Error(`Edge case "${input.edgeCaseId}" not found.`);
1170
717
  edgeCase.expectedBehavior = input.expectedBehavior.trim();
1171
718
  edgeCase.status = "decided";
1172
- appendChangeLog(prd, `Decided ${edgeCase.id}: ${edgeCase.case}`, today);
719
+ require_prd_operations.appendChangeLog(prd, `Decided ${edgeCase.id}: ${edgeCase.case}`, today);
1173
720
  return {
1174
721
  edge_case_id: edgeCase.id,
1175
722
  open_edge_cases: prd.edgeCases.filter((candidate) => candidate.status === "open").length
@@ -1188,7 +735,7 @@ function addGlossaryTerm(prd, input, today) {
1188
735
  definition: input.definition,
1189
736
  avoid: input.avoid
1190
737
  });
1191
- appendChangeLog(prd, `${existing ? "Redefined" : "Defined"} glossary term "${term}"`, today);
738
+ require_prd_operations.appendChangeLog(prd, `${existing ? "Redefined" : "Defined"} glossary term "${term}"`, today);
1192
739
  return {
1193
740
  term,
1194
741
  replaced: Boolean(existing),
@@ -1204,7 +751,7 @@ function updatePhase(prd, input, today) {
1204
751
  }
1205
752
  if (input.description !== void 0) phase.description = input.description;
1206
753
  if (input.color !== void 0) phase.color = input.color;
1207
- appendChangeLog(prd, `Updated phase ${phase.id}`, today);
754
+ require_prd_operations.appendChangeLog(prd, `Updated phase ${phase.id}`, today);
1208
755
  return phasesPayload(prd);
1209
756
  }
1210
757
  /** Deletes a phase; its stories stay in the PRD without a phase. */
@@ -1212,7 +759,7 @@ function deletePhase(prd, input, today) {
1212
759
  const phase = findPhase(prd, input.phaseId);
1213
760
  prd.customPhases = prd.customPhases.filter((other) => other.id !== phase.id);
1214
761
  renumberPhases(prd.customPhases);
1215
- appendChangeLog(prd, `Deleted phase ${phase.id} (${phase.name})`, today);
762
+ require_prd_operations.appendChangeLog(prd, `Deleted phase ${phase.id} (${phase.name})`, today);
1216
763
  return phasesPayload(prd);
1217
764
  }
1218
765
  function reorderPhases(prd, input, today) {
@@ -1221,7 +768,7 @@ function reorderPhases(prd, input, today) {
1221
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"}.`);
1222
769
  prd.customPhases = input.phaseIds.map((id) => findPhase(prd, id));
1223
770
  renumberPhases(prd.customPhases);
1224
- appendChangeLog(prd, `Reordered phases: ${input.phaseIds.join(", ")}`, today);
771
+ require_prd_operations.appendChangeLog(prd, `Reordered phases: ${input.phaseIds.join(", ")}`, today);
1225
772
  return phasesPayload(prd);
1226
773
  }
1227
774
  function findPhase(prd, phaseId) {
@@ -1248,8 +795,7 @@ function phasesPayload(prd) {
1248
795
  function normalizeText(value) {
1249
796
  return value.trim().replace(/\s+/g, " ").toLowerCase();
1250
797
  }
1251
- //#endregion
1252
- //#region src/prd.service.ts
798
+ // src/prd.service.ts
1253
799
  /**
1254
800
  * A write was based on an older revision of the PRD than the one on disk:
1255
801
  * someone else (an agent, Loop, another editor) changed it in between. Read
@@ -1273,11 +819,17 @@ function createPrdService(deps) {
1273
819
  }
1274
820
  var PrdService = class {
1275
821
  deps;
822
+ pendingWrite = Promise.resolve();
1276
823
  constructor(deps) {
1277
824
  this.deps = deps;
1278
825
  }
1279
826
  get prdsDir() {
1280
- 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("/");
1281
833
  }
1282
834
  async list() {
1283
835
  const filenames = await this.listFilenames();
@@ -1292,11 +844,20 @@ var PrdService = class {
1292
844
  progress: prd.progress.overall,
1293
845
  total_stories: prd.progress.total,
1294
846
  completed_stories: prd.progress.completed,
1295
- blocked_stories: prd.progress.blocked
847
+ blocked_stories: prd.progress.blocked,
848
+ ...prd.roadmap ? { roadmap: prd.roadmap } : {}
1296
849
  });
1297
850
  } catch (error) {
1298
851
  warnings.push(`Skipped ${filename}: ${error instanceof Error ? error.message : "unreadable"}`);
1299
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
+ });
1300
861
  return {
1301
862
  prds,
1302
863
  total: prds.length,
@@ -1321,6 +882,7 @@ var PrdService = class {
1321
882
  const today = this.today();
1322
883
  const defaults = input.template ? require_prompts.getTemplate(input.template).defaults : {};
1323
884
  const prd = {
885
+ ...input.roadmap ? { roadmap: require_prompts.PrdRoadmapSchema.parse(input.roadmap) } : {},
1324
886
  introduction: {
1325
887
  title: input.title,
1326
888
  overview: input.overview,
@@ -1424,14 +986,14 @@ var PrdService = class {
1424
986
  async addUserStory(input) {
1425
987
  const filename = this.safeName(input.filename);
1426
988
  const prd = await this.load(filename);
1427
- const storyId = nextStoryId(prd);
989
+ const storyId = require_prd_operations.nextStoryId(prd);
1428
990
  const title = input.title?.trim() || titleFromAction(input.action);
1429
991
  const complexity = input.estimatedComplexity ?? assessComplexity(input.acceptanceCriteria);
1430
992
  const acceptanceCriteria = input.acceptanceCriteria.filter((entry) => entry.trim().length > 0);
1431
993
  prd.userStories.push({
1432
994
  id: storyId,
1433
995
  title,
1434
- userStory: renderUserStory(input),
996
+ userStory: require_prd_operations.renderUserStory(input),
1435
997
  businessValue: input.benefit,
1436
998
  acceptanceCriteria,
1437
999
  status: "not_started",
@@ -1439,19 +1001,19 @@ var PrdService = class {
1439
1001
  estimatedComplexity: complexity,
1440
1002
  dependencies: [],
1441
1003
  ...input.testSeams?.length ? { testSeams: input.testSeams } : {},
1442
- ...input.proofs?.length ? { proofs: validateProofs(acceptanceCriteria, input.proofs) } : {},
1004
+ ...input.proofs?.length ? { proofs: require_prd_operations.validateProofs(acceptanceCriteria, input.proofs) } : {},
1443
1005
  ...input.designNotes?.length ? { designNotes: input.designNotes } : {},
1444
1006
  ...input.securityNotes?.length ? { securityNotes: input.securityNotes } : {}
1445
1007
  });
1446
- if (input.dependencies?.length) findStory(prd, storyId).dependencies = validateDependencies(prd, storyId, input.dependencies);
1447
- if (input.attachmentIds?.length) findStory(prd, storyId).attachmentIds = validateAttachmentIds(prd, input.attachmentIds);
1448
- 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, {
1449
1011
  filename,
1450
1012
  storyId,
1451
1013
  phaseId: input.phaseId
1452
1014
  }, this.today());
1453
- recomputeProgress(prd);
1454
- appendChangeLog(prd, `Added ${storyId} (${title})`, this.today());
1015
+ require_prd_operations.recomputeProgress(prd);
1016
+ require_prd_operations.appendChangeLog(prd, `Added ${storyId} (${title})`, this.today());
1455
1017
  await this.save(filename, prd);
1456
1018
  return {
1457
1019
  story_id: storyId,
@@ -1461,26 +1023,26 @@ var PrdService = class {
1461
1023
  };
1462
1024
  }
1463
1025
  async updateUserStory(input) {
1464
- 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);
1465
1027
  }
1466
1028
  async deleteUserStory(input) {
1467
1029
  const filename = this.safeName(input.filename);
1468
1030
  const prd = await this.load(filename);
1469
- const result = deleteStory(prd, input.storyId, this.today());
1031
+ const result = require_prd_operations.deleteStory(prd, input.storyId, this.today());
1470
1032
  await this.save(filename, prd);
1471
1033
  return result;
1472
1034
  }
1473
1035
  async createCustomPhase(input) {
1474
1036
  const filename = this.safeName(input.filename);
1475
1037
  const prd = await this.load(filename);
1476
- const result = createPhase(prd, input, this.today());
1038
+ const result = require_prd_operations.createPhase(prd, input, this.today());
1477
1039
  await this.save(filename, prd);
1478
1040
  return result;
1479
1041
  }
1480
1042
  async assignStoryToPhase(input) {
1481
1043
  const filename = this.safeName(input.filename);
1482
1044
  const prd = await this.load(filename);
1483
- const result = assignStoryToPhase(prd, input, this.today());
1045
+ const result = require_prd_operations.assignStoryToPhase(prd, input, this.today());
1484
1046
  await this.save(filename, prd);
1485
1047
  return result;
1486
1048
  }
@@ -1489,10 +1051,10 @@ var PrdService = class {
1489
1051
  const current = await this.load(filename);
1490
1052
  const currentRevision = current.metadata.revision ?? 0;
1491
1053
  if (input.expectedRevision !== void 0 && input.expectedRevision !== currentRevision) throw new PrdRevisionConflictError(filename, input.expectedRevision, currentRevision);
1492
- assertCanEnterStatus(current, findStory(current, input.storyId), input.status);
1054
+ this.assertStoryStatusUpdate(current, input);
1493
1055
  if (input.recordDeviations?.length) {
1494
1056
  if (input.status !== "completed") throw new Error("Deviations are recorded only when a story is completed.");
1495
- assertLoggedDeviations(findStory(current, input.storyId), input.recordDeviations);
1057
+ assertLoggedDeviations(require_prd_operations.findStory(current, input.storyId), input.recordDeviations);
1496
1058
  }
1497
1059
  let verification = null;
1498
1060
  if (input.status === "completed") {
@@ -1505,8 +1067,7 @@ var PrdService = class {
1505
1067
  };
1506
1068
  }
1507
1069
  const prd = await this.load(filename);
1508
- const story = findStory(prd, input.storyId);
1509
- assertCanEnterStatus(prd, story, input.status);
1070
+ const story = this.assertStoryStatusUpdate(prd, input);
1510
1071
  const previousStatus = story.status;
1511
1072
  if (verification) {
1512
1073
  story.verification = {
@@ -1521,10 +1082,13 @@ var PrdService = class {
1521
1082
  delete story.completedAt;
1522
1083
  }
1523
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;
1524
1088
  const recordedDecisions = input.recordDeviations?.length ? recordDeviations(prd, story, input.recordDeviations, this.today()) : [];
1525
1089
  if (input.notes) story.notes = input.notes;
1526
- recomputeProgress(prd);
1527
- 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());
1528
1092
  await this.save(filename, prd);
1529
1093
  return {
1530
1094
  story_id: story.id,
@@ -1549,8 +1113,7 @@ var PrdService = class {
1549
1113
  async getImplementationPrompts(filename) {
1550
1114
  const name = this.safeName(filename);
1551
1115
  const prd = await this.load(name);
1552
- const prompts = [];
1553
- 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)] : [];
1554
1117
  return {
1555
1118
  prompts,
1556
1119
  total: prompts.length
@@ -1628,32 +1191,51 @@ var PrdService = class {
1628
1191
  return this.mutate(input.filename, (prd) => reorderPhases(prd, input, this.today()));
1629
1192
  }
1630
1193
  async getNextStory(filename) {
1631
- return pickNextStory(await this.load(this.safeName(filename)));
1194
+ return require_prd_operations.pickNextStory(await this.load(this.safeName(filename)));
1632
1195
  }
1633
1196
  async getStory(input) {
1634
1197
  const filename = this.safeName(input.filename);
1635
- 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);
1636
1200
  }
1637
1201
  async addStoryLog(input) {
1638
- const filename = this.safeName(input.filename);
1639
- const prd = await this.load(filename);
1640
- const result = appendStoryLog(prd, input.storyId, {
1641
- at: this.deps.now().toISOString(),
1642
- whatsNew: input.whatsNew,
1643
- technicalNotes: input.technicalNotes,
1644
- ...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;
1645
1214
  });
1646
- appendChangeLog(prd, `Logged work on ${result.story_id}`, this.today());
1647
- await this.save(filename, prd);
1648
- 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;
1649
1230
  }
1650
1231
  /** Files must already be in the PRD's folder, `.prds/<prd name>/`. */
1651
1232
  async addAttachment(input) {
1652
1233
  const filename = this.safeName(input.filename);
1653
1234
  if (input.path) {
1654
- const folder = require_prompts.attachmentsFolder(filename);
1655
- const path = require_prompts.assertSafeRelativePath(input.path, "attachment path");
1656
- 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.`);
1657
1239
  }
1658
1240
  return this.mutate(filename, (prd) => addAttachment(prd, {
1659
1241
  ...input,
@@ -1703,7 +1285,15 @@ var PrdService = class {
1703
1285
  }
1704
1286
  return normalizePrd(parsed, this.today());
1705
1287
  }
1706
- 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) {
1707
1297
  const today = this.today();
1708
1298
  const path = (0, node_path.join)(this.prdsDir, filename);
1709
1299
  const loadedRevision = prd.metadata.revision ?? 0;
@@ -1725,7 +1315,7 @@ var PrdService = class {
1725
1315
  }
1726
1316
  }
1727
1317
  safeName(filename) {
1728
- return require_prompts.assertSafeFileName(filename, "PRD file name");
1318
+ return require_attachment_paths.assertSafeFileName(filename, "PRD file name");
1729
1319
  }
1730
1320
  today() {
1731
1321
  return this.deps.now().toISOString().slice(0, 10);
@@ -1745,6 +1335,7 @@ function normalizePrd(input, today) {
1745
1335
  const highestQuestion = openQuestions.reduce((max, question) => Math.max(max, Number(/^Q(\d+)$/.exec(question.id)?.[1] ?? 0)), 0);
1746
1336
  return {
1747
1337
  ...prd,
1338
+ roadmap: require_prompts.PrdRoadmapSchema.passthrough().optional().parse(prd.roadmap),
1748
1339
  introduction: {
1749
1340
  title: prd.introduction?.title ?? "Untitled PRD",
1750
1341
  overview: prd.introduction?.overview ?? "",
@@ -1803,13 +1394,13 @@ function normalizePrd(input, today) {
1803
1394
  targetMetrics: prd.measurementPlan?.targetMetrics ?? [],
1804
1395
  guardrailMetrics: prd.measurementPlan?.guardrailMetrics ?? []
1805
1396
  },
1806
- edgeCases: normalizeEdgeCases(prd.edgeCases),
1397
+ edgeCases: require_prd_operations.normalizeEdgeCases(prd.edgeCases),
1807
1398
  securityConsiderations: Array.isArray(prd.securityConsiderations) ? prd.securityConsiderations.filter((item) => typeof item === "string") : [],
1808
1399
  notApplicable: normalizeNotApplicable(prd.notApplicable),
1809
1400
  designGuidance: Array.isArray(prd.designGuidance) ? prd.designGuidance.filter((item) => typeof item === "string") : [],
1810
1401
  decisionLog: prd.decisionLog ?? [],
1811
1402
  glossary: prd.glossary ?? [],
1812
- attachments: require_prompts.normalizeAttachments(prd.attachments),
1403
+ attachments: require_attachment_paths.normalizeAttachments(prd.attachments),
1813
1404
  agentTaskPackets: prd.agentTaskPackets ?? [],
1814
1405
  changeLog: prd.changeLog ?? [],
1815
1406
  metadata: {
@@ -1848,7 +1439,6 @@ function assessComplexity(criteria) {
1848
1439
  if (count <= 8) return "L";
1849
1440
  return "XL";
1850
1441
  }
1851
- //#endregion
1852
1442
  exports.AddAttachmentInputSchema = require_prompts.AddAttachmentInputSchema;
1853
1443
  exports.AddAttachmentOutputSchema = require_prompts.AddAttachmentOutputSchema;
1854
1444
  exports.AddDecisionInputSchema = require_prompts.AddDecisionInputSchema;
@@ -1900,7 +1490,10 @@ exports.NOT_APPLICABLE_TOPICS = NOT_APPLICABLE_TOPICS;
1900
1490
  exports.NotApplicableTopicSchema = require_prompts.NotApplicableTopicSchema;
1901
1491
  exports.PRD_TEMPLATES = require_prompts.PRD_TEMPLATES;
1902
1492
  exports.PhasesOutputSchema = require_prompts.PhasesOutputSchema;
1493
+ exports.PrdCriticalitySchema = require_prompts.PrdCriticalitySchema;
1903
1494
  exports.PrdRevisionConflictError = PrdRevisionConflictError;
1495
+ exports.PrdRoadmapSchema = require_prompts.PrdRoadmapSchema;
1496
+ exports.PrdRoadmapUpdateSchema = require_prompts.PrdRoadmapUpdateSchema;
1904
1497
  exports.PrdSectionValueSchemas = require_prompts.PrdSectionValueSchemas;
1905
1498
  exports.PrdService = PrdService;
1906
1499
  exports.PrdSummarySchema = require_prompts.PrdSummarySchema;
@@ -1926,36 +1519,36 @@ exports.UpdateStoryStatusInputSchema = require_prompts.UpdateStoryStatusInputSch
1926
1519
  exports.UpdateStoryStatusOutputSchema = require_prompts.UpdateStoryStatusOutputSchema;
1927
1520
  exports.UpdateUserStoryInputSchema = require_prompts.UpdateUserStoryInputSchema;
1928
1521
  exports.UpdateUserStoryOutputSchema = require_prompts.UpdateUserStoryOutputSchema;
1929
- exports.appendChangeLog = appendChangeLog;
1930
- exports.appendStoryLog = appendStoryLog;
1522
+ exports.appendChangeLog = require_prd_operations.appendChangeLog;
1523
+ exports.appendStoryLog = require_prd_operations.appendStoryLog;
1931
1524
  exports.architectPrdPrompt = require_prompts.architectPrdPrompt;
1932
- exports.assertCanEnterStatus = assertCanEnterStatus;
1933
- exports.assignStoryToPhase = assignStoryToPhase;
1934
- exports.attachmentProjectPath = require_prompts.attachmentProjectPath;
1935
- exports.attachmentsFolder = require_prompts.attachmentsFolder;
1936
- 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;
1937
1530
  exports.checkPlan = checkPlan;
1938
- exports.createPhase = createPhase;
1531
+ exports.createPhase = require_prd_operations.createPhase;
1939
1532
  exports.createPrdService = createPrdService;
1940
- exports.deleteStory = deleteStory;
1941
- exports.findAttachment = findAttachment;
1942
- exports.findStory = findStory;
1533
+ exports.deleteStory = require_prd_operations.deleteStory;
1534
+ exports.findAttachment = require_prd_operations.findAttachment;
1535
+ exports.findStory = require_prd_operations.findStory;
1943
1536
  exports.formatPrdMarkdown = formatPrdMarkdown;
1944
1537
  exports.getTemplate = require_prompts.getTemplate;
1945
1538
  exports.implementStoryPrompt = require_prompts.implementStoryPrompt;
1946
- exports.incompleteDependencies = incompleteDependencies;
1539
+ exports.incompleteDependencies = require_prd_operations.incompleteDependencies;
1947
1540
  exports.isNotApplicable = isNotApplicable;
1948
- exports.nextId = nextId;
1949
- exports.nextStoryId = nextStoryId;
1541
+ exports.nextId = require_prd_operations.nextId;
1542
+ exports.nextStoryId = require_prd_operations.nextStoryId;
1950
1543
  exports.normalizePrd = normalizePrd;
1951
- exports.pickNextStory = pickNextStory;
1952
- exports.recomputeProgress = recomputeProgress;
1953
- exports.renderUserStory = renderUserStory;
1954
- 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;
1955
1548
  exports.reviewStoryPrompt = require_prompts.reviewStoryPrompt;
1956
1549
  exports.shapePrdPrompt = require_prompts.shapePrdPrompt;
1957
- exports.splitUserStory = splitUserStory;
1958
- exports.updateStory = updateStory;
1959
- exports.validateAttachmentIds = validateAttachmentIds;
1960
- exports.validateDependencies = validateDependencies;
1961
- exports.validateProofs = validateProofs;
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;