@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,427 +1,8 @@
1
- import { $ as PrdSectionValueSchemas, A as DeleteUserStoryOutputSchema, B as GetPrdOutputSchema, C as CustomPhaseSchema, Ct as getTemplate, D as DeletePrdInputSchema, Dt as resolveAttachments, E as DeletePhaseInputSchema, Et as normalizeAttachments, F as GetImprovementSuggestionsInputSchema, G as ListPrdsInputSchema, H as GetProjectStatusOutputSchema, I as GetImprovementSuggestionsOutputSchema, J as ListTemplatesOutputSchema, K as ListPrdsOutputSchema, L as GetNextStoryInputSchema, M as ExportPrdMarkdownOutputSchema, N as GetImplementationPromptsInputSchema, O as DeletePrdOutputSchema, Ot as assertSafeFileName, P as GetImplementationPromptsOutputSchema, Q as PhasesOutputSchema, R as GetNextStoryOutputSchema, S as CreatePrdOutputSchema, St as TEMPLATE_IDS, T as DecideEdgeCaseOutputSchema, Tt as attachmentsFolder, U as GetStoryInputSchema, V as GetProjectStatusInputSchema, W as GetStoryOutputSchema, X as MarkNotApplicableOutputSchema, Y as MarkNotApplicableInputSchema, Z as NotApplicableTopicSchema, _ as CheckPlanInputSchema, _t as UpdateStoryStatusInputSchema, a as AddAttachmentInputSchema, at as ResolveOpenQuestionOutputSchema, b as CreateCustomPhaseOutputSchema, bt as UpdateUserStoryOutputSchema, c as AddDecisionOutputSchema, ct as StoryLogEntrySchema, d as AddStoryLogInputSchema, dt as StoryVerificationSchema, et as PrdSummarySchema, f as AddStoryLogOutputSchema, ft as UpdateAttachmentInputSchema, g as AssignStoryToPhaseOutputSchema, gt as UpdatePrdSectionOutputSchema, h as AssignStoryToPhaseInputSchema, ht as UpdatePrdSectionInputSchema, i as shapePrdPrompt, it as ResolveOpenQuestionInputSchema, j as ExportPrdMarkdownInputSchema, k as DeleteUserStoryInputSchema, kt as assertSafeRelativePath, l as AddGlossaryTermInputSchema, lt as StoryPrioritySchema, m as AddUserStoryOutputSchema, mt as UpdatePhaseInputSchema, n as implementStoryPrompt, nt as RemoveAttachmentOutputSchema, o as AddAttachmentOutputSchema, ot as StoryAttachmentSchema, p as AddUserStoryInputSchema, pt as UpdateAttachmentOutputSchema, q as ListTemplatesInputSchema, r as reviewStoryPrompt, rt as ReorderPhasesInputSchema, s as AddDecisionInputSchema, st as StoryComplexitySchema, t as architectPrdPrompt, tt as RemoveAttachmentInputSchema, u as AddGlossaryTermOutputSchema, ut as StoryStatusSchema, v as CheckPlanOutputSchema, vt as UpdateStoryStatusOutputSchema, w as DecideEdgeCaseInputSchema, wt as attachmentProjectPath, x as CreatePrdInputSchema, xt as PRD_TEMPLATES, y as CreateCustomPhaseInputSchema, yt as UpdateUserStoryInputSchema, z as GetPrdInputSchema } from "./prompts-B0VejF7q.mjs";
2
- import { join } from "node:path";
3
- //#region src/edge-cases.ts
4
- /**
5
- * Edge cases as stored, with hand-edited entries that would break readers
6
- * dropped: each needs a string id and case; status defaults to "open".
7
- */
8
- function normalizeEdgeCases(value) {
9
- if (!Array.isArray(value)) return [];
10
- return value.flatMap((entry) => {
11
- if (typeof entry !== "object" || entry === null) return [];
12
- const { id, case: caseText, expectedBehavior, status, storyIds } = entry;
13
- if (typeof id !== "string" || typeof caseText !== "string" || !caseText) return [];
14
- const ids = Array.isArray(storyIds) ? storyIds.filter((storyId) => typeof storyId === "string") : [];
15
- return [{
16
- id,
17
- case: caseText,
18
- expectedBehavior: typeof expectedBehavior === "string" ? expectedBehavior : "",
19
- status: status === "decided" ? "decided" : "open",
20
- ...ids.length > 0 ? { storyIds: ids } : {}
21
- }];
22
- });
23
- }
24
- /** The edge cases that apply to a story: those linked to it, and those linked to no story. */
25
- function edgeCasesForStory(prd, storyId) {
26
- return prd.edgeCases.filter((edgeCase) => !edgeCase.storyIds?.length || edgeCase.storyIds.includes(storyId));
27
- }
28
- /** Accepted decisions whose topic starts with `design`, e.g. `design:navigation`. */
29
- function designDecisions(prd) {
30
- return prd.decisionLog.filter((entry) => entry.status === "accepted" && entry.topic?.startsWith("design"));
31
- }
32
- //#endregion
33
- //#region src/prd-operations.ts
34
- /**
35
- * Pure PRD transforms.
36
- *
37
- * Everything here takes an already-loaded `StructuredPRD`, mutates it, and
38
- * returns the tool payload. No filesystem, no clock, no deps — the service is
39
- * left with load → transform → save, and every rule below is unit-testable
40
- * without a harness.
41
- */
42
- /**
43
- * Issues the next story id and advances the high-water mark.
44
- *
45
- * Deliberately not `max(existing) + 1`: delete the highest-numbered story and
46
- * that hands its id straight to the next one, so a story id quoted in a commit
47
- * or a decision-log topic would silently come to mean something else.
48
- */
49
- function nextId(items, prefix) {
50
- const highest = items.reduce((max, item) => {
51
- const match = new RegExp(`^${prefix}(\\d+)$`).exec(item.id);
52
- return match ? Math.max(max, Number(match[1])) : max;
53
- }, 0);
54
- return `${prefix}${String(highest + 1).padStart(3, "0")}`;
55
- }
56
- function nextStoryId(prd) {
57
- const highestPresent = prd.userStories.reduce((max, story) => {
58
- const match = /^US(\d+)$/.exec(story.id);
59
- return match ? Math.max(max, Number(match[1])) : max;
60
- }, 0);
61
- const next = Math.max(prd.metadata.lastStoryNumber ?? 0, highestPresent) + 1;
62
- prd.metadata.lastStoryNumber = next;
63
- return `US${String(next).padStart(3, "0")}`;
64
- }
65
- function recomputeProgress(prd) {
66
- const total = prd.userStories.length;
67
- const completed = prd.userStories.filter((story) => story.status === "completed").length;
68
- prd.progress = {
69
- completed,
70
- blocked: prd.userStories.filter((story) => story.status === "blocked").length,
71
- total,
72
- overall: total > 0 ? Math.round(completed / total * 100) : 0
73
- };
74
- }
75
- function appendChangeLog(prd, entry, today) {
76
- prd.changeLog.push(`${today}: ${entry}`);
77
- }
78
- function findStory(prd, storyId) {
79
- const story = prd.userStories.find((candidate) => candidate.id === storyId);
80
- if (!story) {
81
- const known = prd.userStories.map((candidate) => candidate.id).join(", ");
82
- throw new Error(`Story ${storyId} not found.` + (known ? ` Known stories: ${known}.` : " This PRD has no stories yet."));
83
- }
84
- return story;
85
- }
86
- const USER_STORY_SENTENCE = /^As an?\s+(.+?),\s*I want to\s+(.+?)\s+so that\s+(.+)$/i;
87
- /** Splits the rendered sentence back into its parts so one can be patched. */
88
- /** The parts of an "As a X, I want to Y so that Z" story, or undefined. */
89
- function splitUserStory(sentence) {
90
- const match = USER_STORY_SENTENCE.exec(sentence.trim());
91
- if (!match) return;
92
- return {
93
- userType: match[1],
94
- action: match[2],
95
- benefit: match[3]
96
- };
97
- }
98
- function renderUserStory(parts) {
99
- return `As a ${parts.userType}, I want to ${parts.action} so that ${parts.benefit}`;
100
- }
101
- function updateStory(prd, input, today) {
102
- const story = findStory(prd, input.storyId);
103
- const updated = [];
104
- if (input.userType !== void 0 || input.action !== void 0 || input.benefit !== void 0) {
105
- const current = splitUserStory(story.userStory);
106
- 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.`);
107
- story.userStory = renderUserStory({
108
- userType: input.userType ?? current.userType,
109
- action: input.action ?? current.action,
110
- benefit: input.benefit ?? current.benefit
111
- });
112
- updated.push("userStory");
113
- if (input.benefit !== void 0 && input.businessValue === void 0) {
114
- story.businessValue = input.benefit;
115
- updated.push("businessValue");
116
- }
117
- }
118
- if (input.title !== void 0) {
119
- story.title = input.title;
120
- updated.push("title");
121
- }
122
- if (input.testSeams !== void 0) {
123
- story.testSeams = input.testSeams;
124
- updated.push("testSeams");
125
- }
126
- if (input.designNotes !== void 0) {
127
- story.designNotes = withoutBlanks(input.designNotes);
128
- updated.push("designNotes");
129
- }
130
- if (input.securityNotes !== void 0) {
131
- story.securityNotes = withoutBlanks(input.securityNotes);
132
- updated.push("securityNotes");
133
- }
134
- if (input.businessValue !== void 0) {
135
- story.businessValue = input.businessValue;
136
- updated.push("businessValue");
137
- }
138
- if (input.acceptanceCriteria !== void 0) {
139
- story.acceptanceCriteria = input.acceptanceCriteria.filter((entry) => entry.trim().length > 0);
140
- updated.push("acceptanceCriteria");
141
- }
142
- if (input.priority !== void 0) {
143
- story.priority = input.priority;
144
- updated.push("priority");
145
- }
146
- if (input.estimatedComplexity !== void 0) {
147
- story.estimatedComplexity = input.estimatedComplexity;
148
- updated.push("estimatedComplexity");
149
- }
150
- if (input.dependencies !== void 0) {
151
- story.dependencies = validateDependencies(prd, story.id, input.dependencies);
152
- updated.push("dependencies");
153
- }
154
- if (input.notes !== void 0) {
155
- story.notes = input.notes;
156
- updated.push("notes");
157
- }
158
- if (input.attachmentIds !== void 0) {
159
- story.attachmentIds = validateAttachmentIds(prd, input.attachmentIds);
160
- updated.push("attachmentIds");
161
- }
162
- if (input.phaseId !== void 0) {
163
- assignStoryToPhase(prd, {
164
- filename: input.filename,
165
- storyId: story.id,
166
- phaseId: input.phaseId
167
- }, today);
168
- updated.push("phase");
169
- }
170
- 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.`);
171
- appendChangeLog(prd, `Updated ${story.id} (${updated.join(", ")})`, today);
172
- return {
173
- story_id: story.id,
174
- title: story.title,
175
- updated_fields: [...new Set(updated)],
176
- story
177
- };
178
- }
179
- function findAttachment(prd, attachmentId) {
180
- const attachment = prd.attachments.find((candidate) => candidate.id === attachmentId);
181
- if (!attachment) throw new Error(`Attachment "${attachmentId}" not found.`);
182
- return attachment;
183
- }
184
- /** Attachment ids must name attachments in the PRD. */
185
- function validateAttachmentIds(prd, ids) {
186
- for (const id of ids) findAttachment(prd, id);
187
- return [...new Set(ids)];
188
- }
189
- /**
190
- * Dependencies must name real stories, never the story itself, and never form
191
- * a cycle — an unsatisfiable order is worse than no order at all.
192
- */
193
- function validateDependencies(prd, storyId, dependencies) {
194
- const unique = [...new Set(dependencies.filter((id) => id.trim().length > 0))];
195
- for (const id of unique) {
196
- if (id === storyId) throw new Error(`Story ${storyId} cannot depend on itself.`);
197
- findStory(prd, id);
198
- }
199
- const cycle = findCycle(new Map(prd.userStories.map((story) => [story.id, story.id === storyId ? unique : story.dependencies])), storyId);
200
- if (cycle) throw new Error(`Dependency cycle: ${cycle.join(" -> ")}. Remove one of these links.`);
201
- return unique;
202
- }
203
- function findCycle(edges, from) {
204
- const visiting = /* @__PURE__ */ new Set();
205
- const done = /* @__PURE__ */ new Set();
206
- const walk = (id, trail) => {
207
- if (done.has(id)) return void 0;
208
- if (visiting.has(id)) return [...trail, id];
209
- visiting.add(id);
210
- for (const next of edges.get(id) ?? []) {
211
- const found = walk(next, [...trail, id]);
212
- if (found) return found;
213
- }
214
- visiting.delete(id);
215
- done.add(id);
216
- };
217
- return walk(from, []);
218
- }
219
- function deleteStory(prd, storyId, today) {
220
- const story = findStory(prd, storyId);
221
- prd.userStories = prd.userStories.filter((candidate) => candidate.id !== storyId);
222
- const dependencyReferencesRemoved = [];
223
- for (const candidate of prd.userStories) if (candidate.dependencies.includes(storyId)) {
224
- candidate.dependencies = candidate.dependencies.filter((id) => id !== storyId);
225
- dependencyReferencesRemoved.push(candidate.id);
226
- }
227
- const phasesUpdated = [];
228
- for (const phase of prd.customPhases) if (phase.userStoryIds.includes(storyId)) {
229
- phase.userStoryIds = phase.userStoryIds.filter((id) => id !== storyId);
230
- phasesUpdated.push(phase.id);
231
- }
232
- prd.edgeCases = prd.edgeCases.flatMap((edgeCase) => {
233
- if (!edgeCase.storyIds?.includes(storyId)) return [edgeCase];
234
- const storyIds = edgeCase.storyIds.filter((id) => id !== storyId);
235
- return storyIds.length > 0 ? [{
236
- ...edgeCase,
237
- storyIds
238
- }] : [];
239
- });
240
- for (const question of prd.openQuestions) if (question.storyIds?.includes(storyId)) {
241
- const storyIds = question.storyIds.filter((id) => id !== storyId);
242
- if (storyIds.length > 0) question.storyIds = storyIds;
243
- else delete question.storyIds;
244
- }
245
- for (const entry of prd.decisionLog) if (entry.topic?.startsWith(`story:${storyId}:`) && entry.status === "accepted") entry.status = "superseded";
246
- recomputeProgress(prd);
247
- appendChangeLog(prd, `Deleted ${storyId} (${story.title})`, today);
248
- return {
249
- story_id: storyId,
250
- title: story.title,
251
- total_stories: prd.userStories.length,
252
- progress: prd.progress.overall,
253
- dependency_references_removed: dependencyReferencesRemoved,
254
- phases_updated: phasesUpdated
255
- };
256
- }
257
- function createPhase(prd, input, today) {
258
- const name = input.name.trim();
259
- if (prd.customPhases.some((phase) => phase.name.toLowerCase() === name.toLowerCase())) throw new Error(`A phase named "${name}" already exists.`);
260
- const phase = {
261
- id: nextId(prd.customPhases, "PHASE"),
262
- name,
263
- description: input.description,
264
- color: input.color,
265
- order: prd.customPhases.length,
266
- userStoryIds: []
267
- };
268
- prd.customPhases.push(phase);
269
- appendChangeLog(prd, `Created phase ${phase.id} (${name})`, today);
270
- return {
271
- phase: {
272
- id: phase.id,
273
- name: phase.name,
274
- description: phase.description,
275
- color: phase.color,
276
- order: phase.order,
277
- user_story_ids: phase.userStoryIds
278
- },
279
- total_phases: prd.customPhases.length
280
- };
281
- }
282
- function assignStoryToPhase(prd, input, today) {
283
- findStory(prd, input.storyId);
284
- const target = input.phaseId === null ? void 0 : prd.customPhases.find((phase) => phase.id === input.phaseId);
285
- if (input.phaseId !== null && !target) {
286
- const known = prd.customPhases.map((phase) => phase.id).join(", ");
287
- throw new Error(`Phase "${input.phaseId}" not found.` + (known ? ` Known phases: ${known}.` : " This PRD has no phases yet."));
288
- }
289
- const previous = prd.customPhases.find((phase) => phase.userStoryIds.includes(input.storyId));
290
- for (const phase of prd.customPhases) phase.userStoryIds = phase.userStoryIds.filter((id) => id !== input.storyId);
291
- target?.userStoryIds.push(input.storyId);
292
- appendChangeLog(prd, target ? `Assigned ${input.storyId} to ${target.id} (${target.name})` : `Removed ${input.storyId} from all phases`, today);
293
- return {
294
- story_id: input.storyId,
295
- phase_id: target?.id ?? null,
296
- phase_name: target?.name ?? null,
297
- moved_from: previous && previous.id !== target?.id ? previous.id : null
298
- };
299
- }
300
- /** Statuses that mean work on the story has started or finished. */
301
- const WORK_STATUSES = [
302
- "in_progress",
303
- "review",
304
- "completed"
305
- ];
306
- const PRIORITY_ORDER = {
307
- P0: 0,
308
- P1: 1,
309
- P2: 2,
310
- P3: 3
311
- };
312
- /** Dependencies of `story` that are not completed yet. */
313
- function incompleteDependencies(prd, story) {
314
- return story.dependencies.filter((id) => {
315
- return prd.userStories.find((candidate) => candidate.id === id)?.status !== "completed";
316
- });
317
- }
318
- /**
319
- * A story cannot be worked on, reviewed or completed before the stories it
320
- * depends on are completed. `not_started`, `research` and `blocked` stay
321
- * available so a story can still be planned or parked.
322
- */
323
- function assertCanEnterStatus(prd, story, status) {
324
- if (!WORK_STATUSES.includes(status)) return;
325
- const waitingOn = incompleteDependencies(prd, story);
326
- 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.`);
327
- }
328
- /** Position of the story's phase; stories without a phase come last. */
329
- function phaseRank(prd, storyId) {
330
- const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(storyId));
331
- return phase ? phase.order : Number.MAX_SAFE_INTEGER;
332
- }
333
- /**
334
- * The next story to start: not started, every dependency completed, ordered
335
- * by phase, then priority, then position in the PRD.
336
- */
337
- function pickNextStory(prd) {
338
- const notStarted = prd.userStories.filter((story) => story.status === "not_started");
339
- 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));
340
- const waiting = notStarted.map((story) => ({
341
- id: story.id,
342
- title: story.title,
343
- waiting_on: incompleteDependencies(prd, story)
344
- })).filter((entry) => entry.waiting_on.length > 0);
345
- return {
346
- story: ready[0] ?? null,
347
- ready_count: ready.length,
348
- in_progress: prd.userStories.filter((story) => story.status === "in_progress").map((story) => story.id),
349
- waiting
350
- };
351
- }
352
- /**
353
- * Everything an agent needs to work on one story without loading the whole
354
- * PRD: the story, the scope boundaries, its dependencies with their hand-off
355
- * logs, and the log of the most recently completed story.
356
- */
357
- /** `filename` is the PRD's file name, used to give attachment paths. */
358
- function buildStoryContext(prd, storyId, filename) {
359
- const story = findStory(prd, storyId);
360
- const linked = new Set(story.attachmentIds ?? []);
361
- const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(story.id)) ?? null;
362
- 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;
363
- return {
364
- prd: {
365
- title: prd.introduction.title,
366
- overview: prd.introduction.overview,
367
- non_goals: prd.nonGoals,
368
- out_of_scope: prd.outOfScope,
369
- global_acceptance_criteria: prd.acceptanceCriteria.global,
370
- attachments: resolveAttachments(filename, prd.attachments)
371
- },
372
- story,
373
- attachments: resolveAttachments(filename, prd.attachments.filter((attachment) => linked.has(attachment.id))),
374
- phase: phase ? {
375
- id: phase.id,
376
- name: phase.name
377
- } : null,
378
- edge_cases: edgeCasesForStory(prd, story.id),
379
- open_questions: prd.openQuestions.filter((question) => question.storyIds?.includes(story.id)),
380
- security: {
381
- permissions: prd.technicalContracts.permissions,
382
- compliance: prd.technicalRequirements.complianceRequirements,
383
- considerations: prd.securityConsiderations,
384
- story_notes: story.securityNotes ?? []
385
- },
386
- not_applicable: prd.notApplicable,
387
- design: {
388
- guidance: prd.designGuidance,
389
- story_notes: story.designNotes ?? [],
390
- decisions: designDecisions(prd).map(({ id, decision, rationale }) => ({
391
- id,
392
- decision,
393
- rationale
394
- }))
395
- },
396
- dependencies: story.dependencies.map((id) => {
397
- const dependency = prd.userStories.find((candidate) => candidate.id === id);
398
- return {
399
- id,
400
- title: dependency?.title ?? null,
401
- status: dependency?.status ?? null,
402
- log: dependency?.log ?? []
403
- };
404
- }),
405
- previous_story: lastCompleted ? {
406
- id: lastCompleted.id,
407
- title: lastCompleted.title,
408
- log: lastCompleted.log ?? []
409
- } : null
410
- };
411
- }
412
- function appendStoryLog(prd, storyId, entry) {
413
- const story = findStory(prd, storyId);
414
- story.log = [...story.log ?? [], entry];
415
- return {
416
- story_id: story.id,
417
- entries: story.log.length
418
- };
419
- }
420
- function withoutBlanks(entries) {
421
- return entries.map((entry) => entry.trim()).filter(Boolean);
422
- }
423
- //#endregion
424
- //#region src/applicability.ts
1
+ import { _ as updateStory, a as buildStoryContext, b as validateProofs, c as findAttachment, d as nextId, f as nextStoryId, g as splitUserStory, h as renderUserStory, i as assignStoryToPhase, l as findStory, m as recomputeProgress, n as appendStoryLog, o as createPhase, p as pickNextStory, r as assertCanEnterStatus, s as deleteStory, t as appendChangeLog, u as incompleteDependencies, v as validateAttachmentIds, x as normalizeEdgeCases, y as validateDependencies } from "./prd-operations-BvFxo9bg.mjs";
2
+ import { a as assertSafeFileName, i as resolveAttachments, n as attachmentsFolder, o as assertSafeRelativePath, r as normalizeAttachments, t as attachmentProjectPath } from "./attachment-paths-C-SWgoSx.mjs";
3
+ import { $ as PhasesOutputSchema, A as DeleteUserStoryInputSchema, B as GetPrdInputSchema, C as CriterionProofSchema, Ct as UpdateStoryStatusOutputSchema, D as DeletePhaseInputSchema, Dt as TEMPLATE_IDS, E as DecideEdgeCaseOutputSchema, Et as PRD_TEMPLATES, F as GetImplementationPromptsOutputSchema, G as GetStoryOutputSchema, H as GetProjectStatusInputSchema, I as GetImprovementSuggestionsInputSchema, J as ListTemplatesInputSchema, K as ListPrdsInputSchema, L as GetImprovementSuggestionsOutputSchema, M as ExportPrdMarkdownInputSchema, N as ExportPrdMarkdownOutputSchema, O as DeletePrdInputSchema, Ot as getTemplate, P as GetImplementationPromptsInputSchema, Q as NotApplicableTopicSchema, R as GetNextStoryInputSchema, S as CreatePrdOutputSchema, St as UpdateStoryStatusInputSchema, T as DecideEdgeCaseInputSchema, Tt as UpdateUserStoryOutputSchema, U as GetProjectStatusOutputSchema, V as GetPrdOutputSchema, W as GetStoryInputSchema, X as MarkNotApplicableInputSchema, Y as ListTemplatesOutputSchema, Z as MarkNotApplicableOutputSchema, _ as CheckPlanInputSchema, _t as UpdateAttachmentInputSchema, a as AddAttachmentInputSchema, at as ProofKindSchema, b as CreateCustomPhaseOutputSchema, bt as UpdatePrdSectionInputSchema, c as AddDecisionOutputSchema, ct as ReorderPhasesInputSchema, d as AddStoryLogInputSchema, dt as StoryAttachmentSchema, et as PrdCriticalitySchema, f as AddStoryLogOutputSchema, ft as StoryComplexitySchema, g as AssignStoryToPhaseOutputSchema, gt as StoryVerificationSchema, h as AssignStoryToPhaseInputSchema, ht as StoryStatusSchema, i as shapePrdPrompt, it as PrdSummarySchema, j as DeleteUserStoryOutputSchema, k as DeletePrdOutputSchema, l as AddGlossaryTermInputSchema, lt as ResolveOpenQuestionInputSchema, m as AddUserStoryOutputSchema, mt as StoryPrioritySchema, n as implementStoryPrompt, nt as PrdRoadmapUpdateSchema, o as AddAttachmentOutputSchema, ot as RemoveAttachmentInputSchema, p as AddUserStoryInputSchema, pt as StoryLogEntrySchema, q as ListPrdsOutputSchema, r as reviewStoryPrompt, rt as PrdSectionValueSchemas, s as AddDecisionInputSchema, st as RemoveAttachmentOutputSchema, t as architectPrdPrompt, tt as PrdRoadmapSchema, u as AddGlossaryTermOutputSchema, ut as ResolveOpenQuestionOutputSchema, v as CheckPlanOutputSchema, vt as UpdateAttachmentOutputSchema, w as CustomPhaseSchema, wt as UpdateUserStoryInputSchema, x as CreatePrdInputSchema, xt as UpdatePrdSectionOutputSchema, y as CreateCustomPhaseInputSchema, yt as UpdatePhaseInputSchema, z as GetNextStoryOutputSchema } from "./prompts-BlsYD0gf.mjs";
4
+ import { isAbsolute, join, relative, sep } from "node:path";
5
+ // src/applicability.ts
425
6
  /**
426
7
  * Parts of a PRD that can be marked "not applicable" (e.g. no rollout plan
427
8
  * for an internal tool), so the plan check stops asking for them and agents
@@ -465,8 +46,7 @@ function setNotApplicable(prd, input, today) {
465
46
  reason: prd.notApplicable[input.topic] ?? null
466
47
  };
467
48
  }
468
- //#endregion
469
- //#region src/attachments.ts
49
+ // src/attachments.ts
470
50
  /**
471
51
  * Adds an attachment and links it to the given stories. The caller checks
472
52
  * that a `path` exists on disk; this only validates the PRD.
@@ -554,8 +134,7 @@ function updateAttachment(prd, input, today) {
554
134
  stories_updated: storiesUpdated
555
135
  };
556
136
  }
557
- //#endregion
558
- //#region src/markdown.ts
137
+ // src/markdown.ts
559
138
  const STATUS_LABELS = {
560
139
  not_started: "[not started]",
561
140
  research: "[research]",
@@ -639,6 +218,17 @@ function formatPrdMarkdown(prd, filename) {
639
218
  lines.push("", "---", "", `*Approver: ${prd.metadata.approver || "TBD"}*`, "");
640
219
  return lines.join("\n");
641
220
  }
221
+ /** The criterion, followed by how it is proven when the story says. */
222
+ function withProof(story, criterion) {
223
+ const proof = story.proofs?.find((entry) => entry.criterion === criterion);
224
+ if (!proof) return criterion;
225
+ const detail = [
226
+ proof.seam && `\`${proof.seam}\``,
227
+ proof.reason,
228
+ proof.rubric?.length && `rubric: ${proof.rubric.join("; ")}`
229
+ ].filter(Boolean).join(": ");
230
+ return `${criterion} *(proof: ${proof.kind}${detail ? ` — ${detail}` : ""})*`;
231
+ }
642
232
  function formatStory(story) {
643
233
  const lines = [
644
234
  `#### ${story.id}: ${story.title} ${STATUS_LABELS[story.status]} [${story.estimatedComplexity}]`,
@@ -648,7 +238,7 @@ function formatStory(story) {
648
238
  `**Business Value:** ${story.businessValue}`,
649
239
  "",
650
240
  "**Acceptance Criteria:**",
651
- ...bullets(story.acceptanceCriteria)
241
+ ...bullets(story.acceptanceCriteria.map((criterion) => withProof(story, criterion)))
652
242
  ];
653
243
  if (story.dependencies.length > 0) lines.push("", `**Dependencies:** ${story.dependencies.join(", ")}`);
654
244
  if (story.attachmentIds?.length) lines.push("", `**Attachments:** ${story.attachmentIds.join(", ")}`);
@@ -677,8 +267,7 @@ function bullets(items, emptyLabel) {
677
267
  if (items.length === 0) return emptyLabel ? [`- ${emptyLabel}`] : [];
678
268
  return items.map((item) => `- ${item}`);
679
269
  }
680
- //#endregion
681
- //#region src/open-questions.ts
270
+ // src/open-questions.ts
682
271
  /**
683
272
  * Open questions as stored. Older files hold plain strings; they become
684
273
  * questions with ids in list order. Entries without question text are dropped.
@@ -737,8 +326,7 @@ function blockingQuestions(prd) {
737
326
  const unfinished = new Set(prd.userStories.filter((story) => story.status !== "completed").map((story) => story.id));
738
327
  return prd.openQuestions.filter((question) => question.storyIds?.some((id) => unfinished.has(id)));
739
328
  }
740
- //#endregion
741
- //#region src/plan-check.ts
329
+ // src/plan-check.ts
742
330
  /** The not-applicable topic each "missing" check is about. */
743
331
  const CHECK_TOPICS = {
744
332
  "edge-cases": "edgeCases",
@@ -752,6 +340,16 @@ const CHECK_TOPICS = {
752
340
  };
753
341
  /** Above this many stories, grouping them into phases is recommended. */
754
342
  const PHASE_THRESHOLD = 5;
343
+ /**
344
+ * From this many stories, the problem and solution should be written out:
345
+ * stories say what to build, the prose says what is meant. Fewer words than
346
+ * MIN_INTENT_WORDS rarely carries that.
347
+ */
348
+ const INTENT_STORY_THRESHOLD = 3;
349
+ const MIN_INTENT_WORDS = 25;
350
+ function wordCount(text) {
351
+ return text.split(/\s+/).filter(Boolean).length;
352
+ }
755
353
  function checkPlan(prd) {
756
354
  const items = [];
757
355
  const stories = prd.userStories;
@@ -874,6 +472,48 @@ function checkPlan(prd) {
874
472
  severity: "recommended",
875
473
  storyIds: withoutSeams.map((story) => story.id)
876
474
  });
475
+ const unproven = stories.filter((story) => story.status !== "completed" && story.acceptanceCriteria.some((criterion) => !story.proofs?.some((proof) => proof.criterion === criterion)));
476
+ if (unproven.length > 0) items.push({
477
+ id: "unproven-criteria",
478
+ section: "userStories",
479
+ message: `${unproven.length} stories have acceptance criteria with no proof; say how each is shown to work (proofs)`,
480
+ severity: "recommended",
481
+ storyIds: unproven.map((story) => story.id)
482
+ });
483
+ const unjustifiedE2e = stories.filter((story) => story.status !== "completed" && story.proofs?.some((proof) => proof.kind === "e2e" && !proof.reason));
484
+ if (unjustifiedE2e.length > 0) items.push({
485
+ id: "e2e-proofs",
486
+ section: "userStories",
487
+ message: `${unjustifiedE2e.length} stories rely on e2e proofs without saying why a lower seam (service, server action, route) will not do`,
488
+ severity: "recommended",
489
+ storyIds: unjustifiedE2e.map((story) => story.id)
490
+ });
491
+ const mostlyManual = stories.filter((story) => {
492
+ const proofs = story.proofs ?? [];
493
+ const untested = proofs.filter((proof) => proof.kind === "manual" || proof.kind === "post-deploy");
494
+ return story.status !== "completed" && untested.length * 2 > proofs.length;
495
+ });
496
+ if (mostlyManual.length > 0) items.push({
497
+ id: "untested-proofs",
498
+ section: "userStories",
499
+ message: `${mostlyManual.length} stories are mostly proven by hand; split the criteria so the testable parts get a test`,
500
+ severity: "recommended",
501
+ storyIds: mostlyManual.map((story) => story.id)
502
+ });
503
+ if (stories.length >= INTENT_STORY_THRESHOLD) {
504
+ if (wordCount(prd.problemStatement.problem) < MIN_INTENT_WORDS) items.push({
505
+ id: "thin-problem",
506
+ section: "problemStatement",
507
+ message: "Describe the problem in a few sentences: who has it, when, and what it costs them. The stories are checked against it",
508
+ severity: "recommended"
509
+ });
510
+ if (wordCount(prd.solutionOverview.description) < MIN_INTENT_WORDS) items.push({
511
+ id: "thin-solution",
512
+ section: "solutionOverview",
513
+ message: "Describe the finished feature in a few sentences: what a person can do and how it feels. The stories are checked against it",
514
+ severity: "recommended"
515
+ });
516
+ }
877
517
  const phased = new Set(prd.customPhases.flatMap((phase) => phase.userStoryIds));
878
518
  const unphased = stories.filter((story) => !phased.has(story.id));
879
519
  if (stories.length > PHASE_THRESHOLD && unphased.length > 0) items.push({
@@ -900,8 +540,7 @@ function checkPlan(prd) {
900
540
  items: applicable
901
541
  };
902
542
  }
903
- //#endregion
904
- //#region src/planning-operations.ts
543
+ // src/planning-operations.ts
905
544
  /**
906
545
  * Pure transforms for shaping a PRD after it was created: sections, decisions,
907
546
  * open questions, glossary and phases. Same contract as `prd-operations`:
@@ -923,7 +562,16 @@ function updatePrdSection(prd, input, today) {
923
562
  }
924
563
  const value = parsed.data;
925
564
  let updated;
926
- if (input.section === "risks") {
565
+ if (input.section === "roadmap") {
566
+ const patch = value;
567
+ const merged = Object.fromEntries(Object.entries({
568
+ ...prd.roadmap,
569
+ ...patch
570
+ }).filter(([key, value]) => !(Object.hasOwn(patch, key) && value == null)));
571
+ if (Object.keys(merged).length > 0) prd.roadmap = merged;
572
+ else delete prd.roadmap;
573
+ updated = Object.keys(patch);
574
+ } else if (input.section === "risks") {
927
575
  const risks = value;
928
576
  const assigned = [];
929
577
  for (const risk of risks) assigned.push({
@@ -1014,6 +662,34 @@ function addDecision(prd, input, today) {
1014
662
  total_decisions: prd.decisionLog.length
1015
663
  };
1016
664
  }
665
+ /**
666
+ * The decision topic for a story's accepted deviations. Deleting the story
667
+ * supersedes them with its other decisions.
668
+ */
669
+ function deviationTopic(storyId) {
670
+ return `story:${storyId}:deviation`;
671
+ }
672
+ /**
673
+ * Deviations the reviewer accepted become decisions, so the PRD describes
674
+ * what was built rather than only what was planned. Each must be one the
675
+ * story logged; one already recorded is not recorded twice.
676
+ */
677
+ function assertLoggedDeviations(story, deviations) {
678
+ const logged = (story.log ?? []).flatMap((entry) => entry.deviations ?? []);
679
+ 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.`);
680
+ }
681
+ function recordDeviations(prd, story, deviations, today) {
682
+ assertLoggedDeviations(story, deviations);
683
+ const topic = deviationTopic(story.id);
684
+ const recorded = new Set(prd.decisionLog.filter((entry) => entry.topic === topic && entry.status === "accepted").map((entry) => entry.decision));
685
+ return [...new Set(deviations)].filter((deviation) => !recorded.has(deviation)).map((deviation) => addDecision(prd, {
686
+ filename: "",
687
+ decision: deviation,
688
+ rationale: `Departed from the plan while building ${story.id} (${story.title}); accepted at review.`,
689
+ topic,
690
+ status: "accepted"
691
+ }, today).decision_id);
692
+ }
1017
693
  function resolveOpenQuestion(prd, input, today) {
1018
694
  const wanted = input.question ? normalizeText(input.question) : null;
1019
695
  const index = prd.openQuestions.findIndex((question) => input.questionId ? question.id === input.questionId : normalizeText(question.question) === wanted);
@@ -1118,8 +794,7 @@ function phasesPayload(prd) {
1118
794
  function normalizeText(value) {
1119
795
  return value.trim().replace(/\s+/g, " ").toLowerCase();
1120
796
  }
1121
- //#endregion
1122
- //#region src/prd.service.ts
797
+ // src/prd.service.ts
1123
798
  /**
1124
799
  * A write was based on an older revision of the PRD than the one on disk:
1125
800
  * someone else (an agent, Loop, another editor) changed it in between. Read
@@ -1143,11 +818,17 @@ function createPrdService(deps) {
1143
818
  }
1144
819
  var PrdService = class {
1145
820
  deps;
821
+ pendingWrite = Promise.resolve();
1146
822
  constructor(deps) {
1147
823
  this.deps = deps;
1148
824
  }
1149
825
  get prdsDir() {
1150
- return join(this.deps.rootPath, ".prds");
826
+ return this.deps.prdsDir ?? join(this.deps.rootPath, ".prds");
827
+ }
828
+ /** Path for agent-facing instructions, relative to the project when possible. */
829
+ get prdsPath() {
830
+ const path = relative(this.deps.rootPath, this.prdsDir);
831
+ return (isAbsolute(path) || path === ".." || path.startsWith(`..${sep}`) ? this.prdsDir : path || ".").split(sep).join("/");
1151
832
  }
1152
833
  async list() {
1153
834
  const filenames = await this.listFilenames();
@@ -1162,11 +843,20 @@ var PrdService = class {
1162
843
  progress: prd.progress.overall,
1163
844
  total_stories: prd.progress.total,
1164
845
  completed_stories: prd.progress.completed,
1165
- blocked_stories: prd.progress.blocked
846
+ blocked_stories: prd.progress.blocked,
847
+ ...prd.roadmap ? { roadmap: prd.roadmap } : {}
1166
848
  });
1167
849
  } catch (error) {
1168
850
  warnings.push(`Skipped ${filename}: ${error instanceof Error ? error.message : "unreadable"}`);
1169
851
  }
852
+ prds.sort((a, b) => {
853
+ const orderA = a.roadmap?.order ?? 1e400;
854
+ const orderB = b.roadmap?.order ?? 1e400;
855
+ const criticality = PrdCriticalitySchema.options;
856
+ const rankA = a.roadmap?.criticality ? criticality.indexOf(a.roadmap.criticality) : criticality.length;
857
+ const rankB = b.roadmap?.criticality ? criticality.indexOf(b.roadmap.criticality) : criticality.length;
858
+ return orderA === orderB ? rankA - rankB : orderA - orderB;
859
+ });
1170
860
  return {
1171
861
  prds,
1172
862
  total: prds.length,
@@ -1191,6 +881,7 @@ var PrdService = class {
1191
881
  const today = this.today();
1192
882
  const defaults = input.template ? getTemplate(input.template).defaults : {};
1193
883
  const prd = {
884
+ ...input.roadmap ? { roadmap: PrdRoadmapSchema.parse(input.roadmap) } : {},
1194
885
  introduction: {
1195
886
  title: input.title,
1196
887
  overview: input.overview,
@@ -1297,17 +988,19 @@ var PrdService = class {
1297
988
  const storyId = nextStoryId(prd);
1298
989
  const title = input.title?.trim() || titleFromAction(input.action);
1299
990
  const complexity = input.estimatedComplexity ?? assessComplexity(input.acceptanceCriteria);
991
+ const acceptanceCriteria = input.acceptanceCriteria.filter((entry) => entry.trim().length > 0);
1300
992
  prd.userStories.push({
1301
993
  id: storyId,
1302
994
  title,
1303
995
  userStory: renderUserStory(input),
1304
996
  businessValue: input.benefit,
1305
- acceptanceCriteria: input.acceptanceCriteria.filter((entry) => entry.trim().length > 0),
997
+ acceptanceCriteria,
1306
998
  status: "not_started",
1307
999
  priority: input.priority,
1308
1000
  estimatedComplexity: complexity,
1309
1001
  dependencies: [],
1310
1002
  ...input.testSeams?.length ? { testSeams: input.testSeams } : {},
1003
+ ...input.proofs?.length ? { proofs: validateProofs(acceptanceCriteria, input.proofs) } : {},
1311
1004
  ...input.designNotes?.length ? { designNotes: input.designNotes } : {},
1312
1005
  ...input.securityNotes?.length ? { securityNotes: input.securityNotes } : {}
1313
1006
  });
@@ -1357,7 +1050,11 @@ var PrdService = class {
1357
1050
  const current = await this.load(filename);
1358
1051
  const currentRevision = current.metadata.revision ?? 0;
1359
1052
  if (input.expectedRevision !== void 0 && input.expectedRevision !== currentRevision) throw new PrdRevisionConflictError(filename, input.expectedRevision, currentRevision);
1360
- assertCanEnterStatus(current, findStory(current, input.storyId), input.status);
1053
+ this.assertStoryStatusUpdate(current, input);
1054
+ if (input.recordDeviations?.length) {
1055
+ if (input.status !== "completed") throw new Error("Deviations are recorded only when a story is completed.");
1056
+ assertLoggedDeviations(findStory(current, input.storyId), input.recordDeviations);
1057
+ }
1361
1058
  let verification = null;
1362
1059
  if (input.status === "completed") {
1363
1060
  const result = await this.deps.verifyCompletion();
@@ -1369,8 +1066,7 @@ var PrdService = class {
1369
1066
  };
1370
1067
  }
1371
1068
  const prd = await this.load(filename);
1372
- const story = findStory(prd, input.storyId);
1373
- assertCanEnterStatus(prd, story, input.status);
1069
+ const story = this.assertStoryStatusUpdate(prd, input);
1374
1070
  const previousStatus = story.status;
1375
1071
  if (verification) {
1376
1072
  story.verification = {
@@ -1385,6 +1081,10 @@ var PrdService = class {
1385
1081
  delete story.completedAt;
1386
1082
  }
1387
1083
  story.status = input.status;
1084
+ if (input.status === "in_progress" || input.status === "review") {
1085
+ if (input.workerId) story.workerId = input.workerId;
1086
+ } else delete story.workerId;
1087
+ const recordedDecisions = input.recordDeviations?.length ? recordDeviations(prd, story, input.recordDeviations, this.today()) : [];
1388
1088
  if (input.notes) story.notes = input.notes;
1389
1089
  recomputeProgress(prd);
1390
1090
  appendChangeLog(prd, `${story.id} ${previousStatus} -> ${story.status}`, this.today());
@@ -1394,7 +1094,8 @@ var PrdService = class {
1394
1094
  title: story.title,
1395
1095
  status: story.status,
1396
1096
  progress: prd.progress.overall,
1397
- verification
1097
+ verification,
1098
+ recorded_decisions: recordedDecisions
1398
1099
  };
1399
1100
  }
1400
1101
  async exportMarkdown(input) {
@@ -1411,8 +1112,7 @@ var PrdService = class {
1411
1112
  async getImplementationPrompts(filename) {
1412
1113
  const name = this.safeName(filename);
1413
1114
  const prd = await this.load(name);
1414
- const prompts = [];
1415
- for (const story of prd.userStories.filter((s) => s.status === "not_started" && incompleteDependencies(prd, s).length === 0).slice(0, 3)) prompts.push(implementStoryPrompt(name, story.id));
1115
+ const prompts = pickNextStory(prd).story ? [implementStoryPrompt(name)] : [];
1416
1116
  return {
1417
1117
  prompts,
1418
1118
  total: prompts.length
@@ -1494,20 +1194,38 @@ var PrdService = class {
1494
1194
  }
1495
1195
  async getStory(input) {
1496
1196
  const filename = this.safeName(input.filename);
1497
- return buildStoryContext(await this.load(filename), input.storyId, filename);
1197
+ const prd = await this.load(filename);
1198
+ return buildStoryContext(prd, input.storyId, filename, this.prdsPath);
1498
1199
  }
1499
1200
  async addStoryLog(input) {
1500
- const filename = this.safeName(input.filename);
1501
- const prd = await this.load(filename);
1502
- const result = appendStoryLog(prd, input.storyId, {
1503
- at: this.deps.now().toISOString(),
1504
- whatsNew: input.whatsNew,
1505
- technicalNotes: input.technicalNotes,
1506
- ...input.deviations?.length && { deviations: input.deviations }
1201
+ return this.mutate(input.filename, (prd) => {
1202
+ const story = findStory(prd, input.storyId);
1203
+ this.assertStoryOwner(story, input.workerId);
1204
+ if (input.workerId && !story.workerId) throw new Error(`Claim story ${story.id} before logging work.`);
1205
+ const result = appendStoryLog(prd, input.storyId, {
1206
+ at: this.deps.now().toISOString(),
1207
+ whatsNew: input.whatsNew,
1208
+ technicalNotes: input.technicalNotes,
1209
+ ...input.deviations?.length && { deviations: input.deviations }
1210
+ });
1211
+ appendChangeLog(prd, `Logged work on ${result.story_id}`, this.today());
1212
+ return result;
1507
1213
  });
1508
- appendChangeLog(prd, `Logged work on ${result.story_id}`, this.today());
1509
- await this.save(filename, prd);
1510
- return result;
1214
+ }
1215
+ assertStoryOwner(story, workerId) {
1216
+ if (story.workerId && story.workerId !== workerId) throw new Error(`Story ${story.id} is claimed by another worker.`);
1217
+ }
1218
+ assertStoryStatusUpdate(prd, input) {
1219
+ const story = findStory(prd, input.storyId);
1220
+ this.assertStoryOwner(story, input.workerId);
1221
+ assertCanEnterStatus(prd, story, input.status);
1222
+ if (input.workerId && !story.workerId) {
1223
+ const canClaim = input.status === "in_progress" && story.status !== "completed";
1224
+ const canResumeReview = input.status === "review" && story.status === "review";
1225
+ const canReportBlocker = input.status === "blocked" && story.status !== "completed" && Boolean(input.notes?.trim());
1226
+ if (!canClaim && !canResumeReview && !canReportBlocker) throw new Error(`Claim story ${story.id} before changing its status.`);
1227
+ }
1228
+ return story;
1511
1229
  }
1512
1230
  /** Files must already be in the PRD's folder, `.prds/<prd name>/`. */
1513
1231
  async addAttachment(input) {
@@ -1515,7 +1233,8 @@ var PrdService = class {
1515
1233
  if (input.path) {
1516
1234
  const folder = attachmentsFolder(filename);
1517
1235
  const path = assertSafeRelativePath(input.path, "attachment path");
1518
- if (!await this.deps.fileExists(join(this.prdsDir, folder, path))) throw new Error(`File ".prds/${folder}/${path}" not found. Save it in .prds/${folder}/ first.`);
1236
+ const fullPath = join(this.prdsDir, folder, path);
1237
+ if (!await this.deps.fileExists(fullPath)) throw new Error(`File "${fullPath}" not found. Save it in ${this.prdsPath}/${folder}/ first.`);
1519
1238
  }
1520
1239
  return this.mutate(filename, (prd) => addAttachment(prd, {
1521
1240
  ...input,
@@ -1565,7 +1284,15 @@ var PrdService = class {
1565
1284
  }
1566
1285
  return normalizePrd(parsed, this.today());
1567
1286
  }
1568
- async save(filename, prd) {
1287
+ save(filename, prd) {
1288
+ const path = join(this.prdsDir, filename);
1289
+ const write = () => this.saveRevision(filename, prd);
1290
+ if (this.deps.withWriteLock) return this.deps.withWriteLock(path, write);
1291
+ const pending = this.pendingWrite.then(write);
1292
+ this.pendingWrite = pending.catch(() => void 0);
1293
+ return pending;
1294
+ }
1295
+ async saveRevision(filename, prd) {
1569
1296
  const today = this.today();
1570
1297
  const path = join(this.prdsDir, filename);
1571
1298
  const loadedRevision = prd.metadata.revision ?? 0;
@@ -1607,6 +1334,7 @@ function normalizePrd(input, today) {
1607
1334
  const highestQuestion = openQuestions.reduce((max, question) => Math.max(max, Number(/^Q(\d+)$/.exec(question.id)?.[1] ?? 0)), 0);
1608
1335
  return {
1609
1336
  ...prd,
1337
+ roadmap: PrdRoadmapSchema.passthrough().optional().parse(prd.roadmap),
1610
1338
  introduction: {
1611
1339
  title: prd.introduction?.title ?? "Untitled PRD",
1612
1340
  overview: prd.introduction?.overview ?? "",
@@ -1710,5 +1438,4 @@ function assessComplexity(criteria) {
1710
1438
  if (count <= 8) return "L";
1711
1439
  return "XL";
1712
1440
  }
1713
- //#endregion
1714
- export { AddAttachmentInputSchema, AddAttachmentOutputSchema, AddDecisionInputSchema, AddDecisionOutputSchema, AddGlossaryTermInputSchema, AddGlossaryTermOutputSchema, AddStoryLogInputSchema, AddStoryLogOutputSchema, AddUserStoryInputSchema, AddUserStoryOutputSchema, AssignStoryToPhaseInputSchema, AssignStoryToPhaseOutputSchema, CheckPlanInputSchema, CheckPlanOutputSchema, CreateCustomPhaseInputSchema, CreateCustomPhaseOutputSchema, CreatePrdInputSchema, CreatePrdOutputSchema, CustomPhaseSchema, DecideEdgeCaseInputSchema, DecideEdgeCaseOutputSchema, DeletePhaseInputSchema, DeletePrdInputSchema, DeletePrdOutputSchema, DeleteUserStoryInputSchema, DeleteUserStoryOutputSchema, ExportPrdMarkdownInputSchema, ExportPrdMarkdownOutputSchema, GetImplementationPromptsInputSchema, GetImplementationPromptsOutputSchema, GetImprovementSuggestionsInputSchema, GetImprovementSuggestionsOutputSchema, GetNextStoryInputSchema, GetNextStoryOutputSchema, GetPrdInputSchema, GetPrdOutputSchema, GetProjectStatusInputSchema, GetProjectStatusOutputSchema, GetStoryInputSchema, GetStoryOutputSchema, ListPrdsInputSchema, ListPrdsOutputSchema, ListTemplatesInputSchema, ListTemplatesOutputSchema, MarkNotApplicableInputSchema, MarkNotApplicableOutputSchema, NOT_APPLICABLE_TOPICS, NotApplicableTopicSchema, PRD_TEMPLATES, PhasesOutputSchema, PrdRevisionConflictError, PrdSectionValueSchemas, PrdService, PrdSummarySchema, RemoveAttachmentInputSchema, RemoveAttachmentOutputSchema, ReorderPhasesInputSchema, ResolveOpenQuestionInputSchema, ResolveOpenQuestionOutputSchema, StoryAttachmentSchema, StoryComplexitySchema, StoryLogEntrySchema, StoryPrioritySchema, StoryStatusSchema, StoryVerificationSchema, TEMPLATE_IDS, UpdateAttachmentInputSchema, UpdateAttachmentOutputSchema, UpdatePhaseInputSchema, UpdatePrdSectionInputSchema, UpdatePrdSectionOutputSchema, UpdateStoryStatusInputSchema, UpdateStoryStatusOutputSchema, UpdateUserStoryInputSchema, UpdateUserStoryOutputSchema, appendChangeLog, appendStoryLog, architectPrdPrompt, assertCanEnterStatus, assignStoryToPhase, attachmentProjectPath, attachmentsFolder, buildStoryContext, checkPlan, createPhase, createPrdService, deleteStory, findAttachment, findStory, formatPrdMarkdown, getTemplate, implementStoryPrompt, incompleteDependencies, isNotApplicable, nextId, nextStoryId, normalizePrd, pickNextStory, recomputeProgress, renderUserStory, resolveAttachments, reviewStoryPrompt, shapePrdPrompt, splitUserStory, updateStory, validateAttachmentIds, validateDependencies };
1441
+ export { AddAttachmentInputSchema, AddAttachmentOutputSchema, AddDecisionInputSchema, AddDecisionOutputSchema, AddGlossaryTermInputSchema, AddGlossaryTermOutputSchema, AddStoryLogInputSchema, AddStoryLogOutputSchema, AddUserStoryInputSchema, AddUserStoryOutputSchema, AssignStoryToPhaseInputSchema, AssignStoryToPhaseOutputSchema, CheckPlanInputSchema, CheckPlanOutputSchema, CreateCustomPhaseInputSchema, CreateCustomPhaseOutputSchema, CreatePrdInputSchema, CreatePrdOutputSchema, CriterionProofSchema, CustomPhaseSchema, DecideEdgeCaseInputSchema, DecideEdgeCaseOutputSchema, DeletePhaseInputSchema, DeletePrdInputSchema, DeletePrdOutputSchema, DeleteUserStoryInputSchema, DeleteUserStoryOutputSchema, ExportPrdMarkdownInputSchema, ExportPrdMarkdownOutputSchema, GetImplementationPromptsInputSchema, GetImplementationPromptsOutputSchema, GetImprovementSuggestionsInputSchema, GetImprovementSuggestionsOutputSchema, GetNextStoryInputSchema, GetNextStoryOutputSchema, GetPrdInputSchema, GetPrdOutputSchema, GetProjectStatusInputSchema, GetProjectStatusOutputSchema, GetStoryInputSchema, GetStoryOutputSchema, ListPrdsInputSchema, ListPrdsOutputSchema, ListTemplatesInputSchema, ListTemplatesOutputSchema, MarkNotApplicableInputSchema, MarkNotApplicableOutputSchema, NOT_APPLICABLE_TOPICS, NotApplicableTopicSchema, PRD_TEMPLATES, PhasesOutputSchema, PrdCriticalitySchema, PrdRevisionConflictError, PrdRoadmapSchema, PrdRoadmapUpdateSchema, PrdSectionValueSchemas, PrdService, PrdSummarySchema, ProofKindSchema, RemoveAttachmentInputSchema, RemoveAttachmentOutputSchema, ReorderPhasesInputSchema, ResolveOpenQuestionInputSchema, ResolveOpenQuestionOutputSchema, StoryAttachmentSchema, StoryComplexitySchema, StoryLogEntrySchema, StoryPrioritySchema, StoryStatusSchema, StoryVerificationSchema, TEMPLATE_IDS, UpdateAttachmentInputSchema, UpdateAttachmentOutputSchema, UpdatePhaseInputSchema, UpdatePrdSectionInputSchema, UpdatePrdSectionOutputSchema, UpdateStoryStatusInputSchema, UpdateStoryStatusOutputSchema, UpdateUserStoryInputSchema, UpdateUserStoryOutputSchema, appendChangeLog, appendStoryLog, architectPrdPrompt, assertCanEnterStatus, assignStoryToPhase, attachmentProjectPath, attachmentsFolder, buildStoryContext, checkPlan, createPhase, createPrdService, deleteStory, findAttachment, findStory, formatPrdMarkdown, getTemplate, implementStoryPrompt, incompleteDependencies, isNotApplicable, nextId, nextStoryId, normalizePrd, pickNextStory, recomputeProgress, renderUserStory, resolveAttachments, reviewStoryPrompt, shapePrdPrompt, splitUserStory, updateStory, validateAttachmentIds, validateDependencies, validateProofs };