@makerkit/prd 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs ADDED
@@ -0,0 +1,1791 @@
1
+ import { $ as PrdSummarySchema, A as ExportPrdMarkdownInputSchema, B as GetProjectStatusInputSchema, C as DecideEdgeCaseInputSchema, D as DeletePrdOutputSchema, E as DeletePrdInputSchema, F as GetImprovementSuggestionsOutputSchema, G as ListPrdsOutputSchema, H as GetStoryInputSchema, I as GetNextStoryInputSchema, J as MarkNotApplicableInputSchema, K as ListTemplatesInputSchema, L as GetNextStoryOutputSchema, M as GetImplementationPromptsInputSchema, N as GetImplementationPromptsOutputSchema, O as DeleteUserStoryInputSchema, P as GetImprovementSuggestionsInputSchema, Q as PrdSectionValueSchemas, R as GetPrdInputSchema, S as CustomPhaseSchema, St as getTemplate, T as DeletePhaseInputSchema, U as GetStoryOutputSchema, V as GetProjectStatusOutputSchema, W as ListPrdsInputSchema, X as NotApplicableTopicSchema, Y as MarkNotApplicableOutputSchema, Z as PhasesOutputSchema, _ as CheckPlanOutputSchema, _t as UpdateStoryStatusOutputSchema, a as AddAttachmentOutputSchema, at as StoryAttachmentSchema, b as CreatePrdInputSchema, bt as PRD_TEMPLATES, c as AddGlossaryTermInputSchema, ct as StoryPrioritySchema, d as AddStoryLogOutputSchema, dt as UpdateAttachmentInputSchema, et as RemoveAttachmentInputSchema, f as AddUserStoryInputSchema, ft as UpdateAttachmentOutputSchema, g as CheckPlanInputSchema, gt as UpdateStoryStatusInputSchema, h as AssignStoryToPhaseOutputSchema, ht as UpdatePrdSectionOutputSchema, i as AddAttachmentInputSchema, it as ResolveOpenQuestionOutputSchema, j as ExportPrdMarkdownOutputSchema, k as DeleteUserStoryOutputSchema, l as AddGlossaryTermOutputSchema, lt as StoryStatusSchema, m as AssignStoryToPhaseInputSchema, mt as UpdatePrdSectionInputSchema, n as reviewStoryPrompt, nt as ReorderPhasesInputSchema, o as AddDecisionInputSchema, ot as StoryComplexitySchema, p as AddUserStoryOutputSchema, pt as UpdatePhaseInputSchema, q as ListTemplatesOutputSchema, r as shapePrdPrompt, rt as ResolveOpenQuestionInputSchema, s as AddDecisionOutputSchema, st as StoryLogEntrySchema, t as implementStoryPrompt, tt as RemoveAttachmentOutputSchema, u as AddStoryLogInputSchema, ut as StoryVerificationSchema, v as CreateCustomPhaseInputSchema, vt as UpdateUserStoryInputSchema, w as DecideEdgeCaseOutputSchema, x as CreatePrdOutputSchema, xt as TEMPLATE_IDS, y as CreateCustomPhaseOutputSchema, yt as UpdateUserStoryOutputSchema, z as GetPrdOutputSchema } from "./prompts-Bber0S1Z.mjs";
2
+ import { join } from "node:path";
3
+ //#region src/safe-file-name.ts
4
+ /**
5
+ * Accept only a bare file name. Anything that could escape the intended
6
+ * directory (path separators, parent references, hidden files) is rejected
7
+ * before the filesystem is touched.
8
+ */
9
+ function assertSafeFileName(value, label = "file name") {
10
+ const name = value.trim();
11
+ if (name.length === 0 || name.includes("..") || name.includes("/") || name.includes("\\") || name.startsWith(".")) throw new Error(`Invalid ${label} "${value}"`);
12
+ return name;
13
+ }
14
+ /**
15
+ * Accept only a relative path that stays inside the directory it is joined
16
+ * to: no absolute paths, no `..`, no backslashes, no empty or hidden segments.
17
+ * This is a check on the text only; code that serves the file must still
18
+ * resolve symlinks before reading it.
19
+ */
20
+ function assertSafeRelativePath(value, label = "path") {
21
+ const path = value.trim();
22
+ const segments = path.split("/");
23
+ if (path.length === 0 || path.includes("\\") || /^[a-zA-Z]:/.test(path) || segments.some((segment) => segment.length === 0 || segment.startsWith("."))) throw new Error(`Invalid ${label} "${value}"`);
24
+ return path;
25
+ }
26
+ //#endregion
27
+ //#region src/attachment-paths.ts
28
+ /**
29
+ * The folder for a PRD's files, relative to `.prds`: the PRD file name
30
+ * without `.json`, so `notes.json` keeps its files in `.prds/notes/`.
31
+ */
32
+ function attachmentsFolder(filename) {
33
+ return filename.replace(/\.json$/, "");
34
+ }
35
+ /** An attachment's file relative to the project root, e.g. `.prds/notes/a.png`. */
36
+ function attachmentProjectPath(filename, path) {
37
+ return `.prds/${attachmentsFolder(filename)}/${path}`;
38
+ }
39
+ /** Attachments as an agent needs them: file paths from the project root. */
40
+ function resolveAttachments(filename, attachments) {
41
+ return attachments.map(({ path, ...attachment }) => ({
42
+ ...attachment,
43
+ ...path ? { path: attachmentProjectPath(filename, path) } : {}
44
+ }));
45
+ }
46
+ /**
47
+ * Attachments as stored, with hand-edited entries that would break readers
48
+ * or point outside the PRD folder dropped: each needs a string id and title
49
+ * and either a safe relative path or an http(s) url.
50
+ */
51
+ function normalizeAttachments(value) {
52
+ if (!Array.isArray(value)) return [];
53
+ return value.flatMap((entry) => {
54
+ if (typeof entry !== "object" || entry === null) return [];
55
+ const { id, title, path, url, note } = entry;
56
+ if (typeof id !== "string" || typeof title !== "string") return [];
57
+ const base = {
58
+ id,
59
+ title,
60
+ ...typeof note === "string" && note ? { note } : {}
61
+ };
62
+ if (typeof path === "string" && url === void 0 && isSafePath(path)) return [{
63
+ ...base,
64
+ path
65
+ }];
66
+ if (typeof url === "string" && path === void 0 && /^https?:\/\//i.test(url)) return [{
67
+ ...base,
68
+ url
69
+ }];
70
+ return [];
71
+ });
72
+ }
73
+ function isSafePath(path) {
74
+ try {
75
+ return assertSafeRelativePath(path) === path;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+ //#endregion
81
+ //#region src/edge-cases.ts
82
+ /**
83
+ * Edge cases as stored, with hand-edited entries that would break readers
84
+ * dropped: each needs a string id and case; status defaults to "open".
85
+ */
86
+ function normalizeEdgeCases(value) {
87
+ if (!Array.isArray(value)) return [];
88
+ return value.flatMap((entry) => {
89
+ if (typeof entry !== "object" || entry === null) return [];
90
+ const { id, case: caseText, expectedBehavior, status, storyIds } = entry;
91
+ if (typeof id !== "string" || typeof caseText !== "string" || !caseText) return [];
92
+ const ids = Array.isArray(storyIds) ? storyIds.filter((storyId) => typeof storyId === "string") : [];
93
+ return [{
94
+ id,
95
+ case: caseText,
96
+ expectedBehavior: typeof expectedBehavior === "string" ? expectedBehavior : "",
97
+ status: status === "decided" ? "decided" : "open",
98
+ ...ids.length > 0 ? { storyIds: ids } : {}
99
+ }];
100
+ });
101
+ }
102
+ /** The edge cases that apply to a story: those linked to it, and those linked to no story. */
103
+ function edgeCasesForStory(prd, storyId) {
104
+ return prd.edgeCases.filter((edgeCase) => !edgeCase.storyIds?.length || edgeCase.storyIds.includes(storyId));
105
+ }
106
+ /** Accepted decisions whose topic starts with `design`, e.g. `design:navigation`. */
107
+ function designDecisions(prd) {
108
+ return prd.decisionLog.filter((entry) => entry.status === "accepted" && entry.topic?.startsWith("design"));
109
+ }
110
+ //#endregion
111
+ //#region src/prd-operations.ts
112
+ /**
113
+ * Pure PRD transforms.
114
+ *
115
+ * Everything here takes an already-loaded `StructuredPRD`, mutates it, and
116
+ * returns the tool payload. No filesystem, no clock, no deps — the service is
117
+ * left with load → transform → save, and every rule below is unit-testable
118
+ * without a harness.
119
+ */
120
+ /**
121
+ * Issues the next story id and advances the high-water mark.
122
+ *
123
+ * Deliberately not `max(existing) + 1`: delete the highest-numbered story and
124
+ * that hands its id straight to the next one, so a story id quoted in a commit
125
+ * or a decision-log topic would silently come to mean something else.
126
+ */
127
+ function nextId(items, prefix) {
128
+ const highest = items.reduce((max, item) => {
129
+ const match = new RegExp(`^${prefix}(\\d+)$`).exec(item.id);
130
+ return match ? Math.max(max, Number(match[1])) : max;
131
+ }, 0);
132
+ return `${prefix}${String(highest + 1).padStart(3, "0")}`;
133
+ }
134
+ function nextStoryId(prd) {
135
+ const highestPresent = prd.userStories.reduce((max, story) => {
136
+ const match = /^US(\d+)$/.exec(story.id);
137
+ return match ? Math.max(max, Number(match[1])) : max;
138
+ }, 0);
139
+ const next = Math.max(prd.metadata.lastStoryNumber ?? 0, highestPresent) + 1;
140
+ prd.metadata.lastStoryNumber = next;
141
+ return `US${String(next).padStart(3, "0")}`;
142
+ }
143
+ function recomputeProgress(prd) {
144
+ const total = prd.userStories.length;
145
+ const completed = prd.userStories.filter((story) => story.status === "completed").length;
146
+ prd.progress = {
147
+ completed,
148
+ blocked: prd.userStories.filter((story) => story.status === "blocked").length,
149
+ total,
150
+ overall: total > 0 ? Math.round(completed / total * 100) : 0
151
+ };
152
+ }
153
+ function appendChangeLog(prd, entry, today) {
154
+ prd.changeLog.push(`${today}: ${entry}`);
155
+ }
156
+ function findStory(prd, storyId) {
157
+ const story = prd.userStories.find((candidate) => candidate.id === storyId);
158
+ if (!story) {
159
+ const known = prd.userStories.map((candidate) => candidate.id).join(", ");
160
+ throw new Error(`Story ${storyId} not found.` + (known ? ` Known stories: ${known}.` : " This PRD has no stories yet."));
161
+ }
162
+ return story;
163
+ }
164
+ const USER_STORY_SENTENCE = /^As an?\s+(.+?),\s*I want to\s+(.+?)\s+so that\s+(.+)$/i;
165
+ /** Splits the rendered sentence back into its parts so one can be patched. */
166
+ /** The parts of an "As a X, I want to Y so that Z" story, or undefined. */
167
+ function splitUserStory(sentence) {
168
+ const match = USER_STORY_SENTENCE.exec(sentence.trim());
169
+ if (!match) return;
170
+ return {
171
+ userType: match[1],
172
+ action: match[2],
173
+ benefit: match[3]
174
+ };
175
+ }
176
+ function renderUserStory(parts) {
177
+ return `As a ${parts.userType}, I want to ${parts.action} so that ${parts.benefit}`;
178
+ }
179
+ function updateStory(prd, input, today) {
180
+ const story = findStory(prd, input.storyId);
181
+ const updated = [];
182
+ if (input.userType !== void 0 || input.action !== void 0 || input.benefit !== void 0) {
183
+ const current = splitUserStory(story.userStory);
184
+ 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.`);
185
+ story.userStory = renderUserStory({
186
+ userType: input.userType ?? current.userType,
187
+ action: input.action ?? current.action,
188
+ benefit: input.benefit ?? current.benefit
189
+ });
190
+ updated.push("userStory");
191
+ if (input.benefit !== void 0 && input.businessValue === void 0) {
192
+ story.businessValue = input.benefit;
193
+ updated.push("businessValue");
194
+ }
195
+ }
196
+ if (input.title !== void 0) {
197
+ story.title = input.title;
198
+ updated.push("title");
199
+ }
200
+ if (input.testSeams !== void 0) {
201
+ story.testSeams = input.testSeams;
202
+ updated.push("testSeams");
203
+ }
204
+ if (input.designNotes !== void 0) {
205
+ story.designNotes = withoutBlanks(input.designNotes);
206
+ updated.push("designNotes");
207
+ }
208
+ if (input.securityNotes !== void 0) {
209
+ story.securityNotes = withoutBlanks(input.securityNotes);
210
+ updated.push("securityNotes");
211
+ }
212
+ if (input.businessValue !== void 0) {
213
+ story.businessValue = input.businessValue;
214
+ updated.push("businessValue");
215
+ }
216
+ if (input.acceptanceCriteria !== void 0) {
217
+ story.acceptanceCriteria = input.acceptanceCriteria.filter((entry) => entry.trim().length > 0);
218
+ updated.push("acceptanceCriteria");
219
+ }
220
+ if (input.priority !== void 0) {
221
+ story.priority = input.priority;
222
+ updated.push("priority");
223
+ }
224
+ if (input.estimatedComplexity !== void 0) {
225
+ story.estimatedComplexity = input.estimatedComplexity;
226
+ updated.push("estimatedComplexity");
227
+ }
228
+ if (input.dependencies !== void 0) {
229
+ story.dependencies = validateDependencies(prd, story.id, input.dependencies);
230
+ updated.push("dependencies");
231
+ }
232
+ if (input.notes !== void 0) {
233
+ story.notes = input.notes;
234
+ updated.push("notes");
235
+ }
236
+ if (input.attachmentIds !== void 0) {
237
+ story.attachmentIds = validateAttachmentIds(prd, input.attachmentIds);
238
+ updated.push("attachmentIds");
239
+ }
240
+ if (input.phaseId !== void 0) {
241
+ assignStoryToPhase(prd, {
242
+ filename: input.filename,
243
+ storyId: story.id,
244
+ phaseId: input.phaseId
245
+ }, today);
246
+ updated.push("phase");
247
+ }
248
+ 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.`);
249
+ appendChangeLog(prd, `Updated ${story.id} (${updated.join(", ")})`, today);
250
+ return {
251
+ story_id: story.id,
252
+ title: story.title,
253
+ updated_fields: [...new Set(updated)],
254
+ story
255
+ };
256
+ }
257
+ function findAttachment(prd, attachmentId) {
258
+ const attachment = prd.attachments.find((candidate) => candidate.id === attachmentId);
259
+ if (!attachment) throw new Error(`Attachment "${attachmentId}" not found.`);
260
+ return attachment;
261
+ }
262
+ /** Attachment ids must name attachments in the PRD. */
263
+ function validateAttachmentIds(prd, ids) {
264
+ for (const id of ids) findAttachment(prd, id);
265
+ return [...new Set(ids)];
266
+ }
267
+ /**
268
+ * Dependencies must name real stories, never the story itself, and never form
269
+ * a cycle — an unsatisfiable order is worse than no order at all.
270
+ */
271
+ function validateDependencies(prd, storyId, dependencies) {
272
+ const unique = [...new Set(dependencies.filter((id) => id.trim().length > 0))];
273
+ for (const id of unique) {
274
+ if (id === storyId) throw new Error(`Story ${storyId} cannot depend on itself.`);
275
+ findStory(prd, id);
276
+ }
277
+ const cycle = findCycle(new Map(prd.userStories.map((story) => [story.id, story.id === storyId ? unique : story.dependencies])), storyId);
278
+ if (cycle) throw new Error(`Dependency cycle: ${cycle.join(" -> ")}. Remove one of these links.`);
279
+ return unique;
280
+ }
281
+ function findCycle(edges, from) {
282
+ const visiting = /* @__PURE__ */ new Set();
283
+ const done = /* @__PURE__ */ new Set();
284
+ const walk = (id, trail) => {
285
+ if (done.has(id)) return void 0;
286
+ if (visiting.has(id)) return [...trail, id];
287
+ visiting.add(id);
288
+ for (const next of edges.get(id) ?? []) {
289
+ const found = walk(next, [...trail, id]);
290
+ if (found) return found;
291
+ }
292
+ visiting.delete(id);
293
+ done.add(id);
294
+ };
295
+ return walk(from, []);
296
+ }
297
+ function deleteStory(prd, storyId, today) {
298
+ const story = findStory(prd, storyId);
299
+ prd.userStories = prd.userStories.filter((candidate) => candidate.id !== storyId);
300
+ const dependencyReferencesRemoved = [];
301
+ for (const candidate of prd.userStories) if (candidate.dependencies.includes(storyId)) {
302
+ candidate.dependencies = candidate.dependencies.filter((id) => id !== storyId);
303
+ dependencyReferencesRemoved.push(candidate.id);
304
+ }
305
+ const phasesUpdated = [];
306
+ for (const phase of prd.customPhases) if (phase.userStoryIds.includes(storyId)) {
307
+ phase.userStoryIds = phase.userStoryIds.filter((id) => id !== storyId);
308
+ phasesUpdated.push(phase.id);
309
+ }
310
+ prd.edgeCases = prd.edgeCases.flatMap((edgeCase) => {
311
+ if (!edgeCase.storyIds?.includes(storyId)) return [edgeCase];
312
+ const storyIds = edgeCase.storyIds.filter((id) => id !== storyId);
313
+ return storyIds.length > 0 ? [{
314
+ ...edgeCase,
315
+ storyIds
316
+ }] : [];
317
+ });
318
+ for (const question of prd.openQuestions) if (question.storyIds?.includes(storyId)) {
319
+ const storyIds = question.storyIds.filter((id) => id !== storyId);
320
+ if (storyIds.length > 0) question.storyIds = storyIds;
321
+ else delete question.storyIds;
322
+ }
323
+ for (const entry of prd.decisionLog) if (entry.topic?.startsWith(`story:${storyId}:`) && entry.status === "accepted") entry.status = "superseded";
324
+ recomputeProgress(prd);
325
+ appendChangeLog(prd, `Deleted ${storyId} (${story.title})`, today);
326
+ return {
327
+ story_id: storyId,
328
+ title: story.title,
329
+ total_stories: prd.userStories.length,
330
+ progress: prd.progress.overall,
331
+ dependency_references_removed: dependencyReferencesRemoved,
332
+ phases_updated: phasesUpdated
333
+ };
334
+ }
335
+ function createPhase(prd, input, today) {
336
+ const name = input.name.trim();
337
+ if (prd.customPhases.some((phase) => phase.name.toLowerCase() === name.toLowerCase())) throw new Error(`A phase named "${name}" already exists.`);
338
+ const phase = {
339
+ id: nextId(prd.customPhases, "PHASE"),
340
+ name,
341
+ description: input.description,
342
+ color: input.color,
343
+ order: prd.customPhases.length,
344
+ userStoryIds: []
345
+ };
346
+ prd.customPhases.push(phase);
347
+ appendChangeLog(prd, `Created phase ${phase.id} (${name})`, today);
348
+ return {
349
+ phase: {
350
+ id: phase.id,
351
+ name: phase.name,
352
+ description: phase.description,
353
+ color: phase.color,
354
+ order: phase.order,
355
+ user_story_ids: phase.userStoryIds
356
+ },
357
+ total_phases: prd.customPhases.length
358
+ };
359
+ }
360
+ function assignStoryToPhase(prd, input, today) {
361
+ findStory(prd, input.storyId);
362
+ const target = input.phaseId === null ? void 0 : prd.customPhases.find((phase) => phase.id === input.phaseId);
363
+ if (input.phaseId !== null && !target) {
364
+ const known = prd.customPhases.map((phase) => phase.id).join(", ");
365
+ throw new Error(`Phase "${input.phaseId}" not found.` + (known ? ` Known phases: ${known}.` : " This PRD has no phases yet."));
366
+ }
367
+ const previous = prd.customPhases.find((phase) => phase.userStoryIds.includes(input.storyId));
368
+ for (const phase of prd.customPhases) phase.userStoryIds = phase.userStoryIds.filter((id) => id !== input.storyId);
369
+ target?.userStoryIds.push(input.storyId);
370
+ appendChangeLog(prd, target ? `Assigned ${input.storyId} to ${target.id} (${target.name})` : `Removed ${input.storyId} from all phases`, today);
371
+ return {
372
+ story_id: input.storyId,
373
+ phase_id: target?.id ?? null,
374
+ phase_name: target?.name ?? null,
375
+ moved_from: previous && previous.id !== target?.id ? previous.id : null
376
+ };
377
+ }
378
+ /** Statuses that mean work on the story has started or finished. */
379
+ const WORK_STATUSES = [
380
+ "in_progress",
381
+ "review",
382
+ "completed"
383
+ ];
384
+ const PRIORITY_ORDER = {
385
+ P0: 0,
386
+ P1: 1,
387
+ P2: 2,
388
+ P3: 3
389
+ };
390
+ /** Dependencies of `story` that are not completed yet. */
391
+ function incompleteDependencies(prd, story) {
392
+ return story.dependencies.filter((id) => {
393
+ return prd.userStories.find((candidate) => candidate.id === id)?.status !== "completed";
394
+ });
395
+ }
396
+ /**
397
+ * A story cannot be worked on, reviewed or completed before the stories it
398
+ * depends on are completed. `not_started`, `research` and `blocked` stay
399
+ * available so a story can still be planned or parked.
400
+ */
401
+ function assertCanEnterStatus(prd, story, status) {
402
+ if (!WORK_STATUSES.includes(status)) return;
403
+ const waitingOn = incompleteDependencies(prd, story);
404
+ 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.`);
405
+ }
406
+ /** Position of the story's phase; stories without a phase come last. */
407
+ function phaseRank(prd, storyId) {
408
+ const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(storyId));
409
+ return phase ? phase.order : Number.MAX_SAFE_INTEGER;
410
+ }
411
+ /**
412
+ * The next story to start: not started, every dependency completed, ordered
413
+ * by phase, then priority, then position in the PRD.
414
+ */
415
+ function pickNextStory(prd) {
416
+ const notStarted = prd.userStories.filter((story) => story.status === "not_started");
417
+ 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));
418
+ const waiting = notStarted.map((story) => ({
419
+ id: story.id,
420
+ title: story.title,
421
+ waiting_on: incompleteDependencies(prd, story)
422
+ })).filter((entry) => entry.waiting_on.length > 0);
423
+ return {
424
+ story: ready[0] ?? null,
425
+ ready_count: ready.length,
426
+ in_progress: prd.userStories.filter((story) => story.status === "in_progress").map((story) => story.id),
427
+ waiting
428
+ };
429
+ }
430
+ /**
431
+ * Everything an agent needs to work on one story without loading the whole
432
+ * PRD: the story, the scope boundaries, its dependencies with their hand-off
433
+ * logs, and the log of the most recently completed story.
434
+ */
435
+ /** `filename` is the PRD's file name, used to give attachment paths. */
436
+ function buildStoryContext(prd, storyId, filename) {
437
+ const story = findStory(prd, storyId);
438
+ const linked = new Set(story.attachmentIds ?? []);
439
+ const phase = prd.customPhases.find((candidate) => candidate.userStoryIds.includes(story.id)) ?? null;
440
+ 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;
441
+ return {
442
+ prd: {
443
+ title: prd.introduction.title,
444
+ overview: prd.introduction.overview,
445
+ non_goals: prd.nonGoals,
446
+ out_of_scope: prd.outOfScope,
447
+ global_acceptance_criteria: prd.acceptanceCriteria.global,
448
+ attachments: resolveAttachments(filename, prd.attachments)
449
+ },
450
+ story,
451
+ attachments: resolveAttachments(filename, prd.attachments.filter((attachment) => linked.has(attachment.id))),
452
+ phase: phase ? {
453
+ id: phase.id,
454
+ name: phase.name
455
+ } : null,
456
+ edge_cases: edgeCasesForStory(prd, story.id),
457
+ open_questions: prd.openQuestions.filter((question) => question.storyIds?.includes(story.id)),
458
+ security: {
459
+ permissions: prd.technicalContracts.permissions,
460
+ compliance: prd.technicalRequirements.complianceRequirements,
461
+ considerations: prd.securityConsiderations,
462
+ story_notes: story.securityNotes ?? []
463
+ },
464
+ not_applicable: prd.notApplicable,
465
+ design: {
466
+ guidance: prd.designGuidance,
467
+ story_notes: story.designNotes ?? [],
468
+ decisions: designDecisions(prd).map(({ id, decision, rationale }) => ({
469
+ id,
470
+ decision,
471
+ rationale
472
+ }))
473
+ },
474
+ dependencies: story.dependencies.map((id) => {
475
+ const dependency = prd.userStories.find((candidate) => candidate.id === id);
476
+ return {
477
+ id,
478
+ title: dependency?.title ?? null,
479
+ status: dependency?.status ?? null,
480
+ log: dependency?.log ?? []
481
+ };
482
+ }),
483
+ previous_story: lastCompleted ? {
484
+ id: lastCompleted.id,
485
+ title: lastCompleted.title,
486
+ log: lastCompleted.log ?? []
487
+ } : null
488
+ };
489
+ }
490
+ function appendStoryLog(prd, storyId, entry) {
491
+ const story = findStory(prd, storyId);
492
+ story.log = [...story.log ?? [], entry];
493
+ return {
494
+ story_id: story.id,
495
+ entries: story.log.length
496
+ };
497
+ }
498
+ function withoutBlanks(entries) {
499
+ return entries.map((entry) => entry.trim()).filter(Boolean);
500
+ }
501
+ //#endregion
502
+ //#region src/applicability.ts
503
+ /**
504
+ * Parts of a PRD that can be marked "not applicable" (e.g. no rollout plan
505
+ * for an internal tool), so the plan check stops asking for them and agents
506
+ * do not invent them. The core (overview, problem, solution, scope, stories)
507
+ * always applies.
508
+ */
509
+ const NOT_APPLICABLE_TOPICS = [
510
+ "dataModel",
511
+ "outsideServices",
512
+ "security",
513
+ "design",
514
+ "qualityBar",
515
+ "edgeCases",
516
+ "rollout",
517
+ "measurement",
518
+ "glossary",
519
+ "risks"
520
+ ];
521
+ function isNotApplicable(prd, topic) {
522
+ return prd.notApplicable[topic] !== void 0;
523
+ }
524
+ /** Stored values, with unknown topics and non-string reasons dropped. */
525
+ function normalizeNotApplicable(value) {
526
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
527
+ const topics = new Set(NOT_APPLICABLE_TOPICS);
528
+ return Object.fromEntries(Object.entries(value).filter(([topic, reason]) => topics.has(topic) && typeof reason === "string"));
529
+ }
530
+ function setNotApplicable(prd, input, today) {
531
+ if (input.notApplicable) prd.notApplicable = {
532
+ ...prd.notApplicable,
533
+ [input.topic]: input.reason?.trim() ?? ""
534
+ };
535
+ else {
536
+ const { [input.topic]: _removed, ...rest } = prd.notApplicable;
537
+ prd.notApplicable = rest;
538
+ }
539
+ appendChangeLog(prd, input.notApplicable ? `Marked ${input.topic} not applicable` : `Marked ${input.topic} applicable`, today);
540
+ return {
541
+ topic: input.topic,
542
+ not_applicable: input.notApplicable,
543
+ reason: prd.notApplicable[input.topic] ?? null
544
+ };
545
+ }
546
+ //#endregion
547
+ //#region src/open-questions.ts
548
+ /**
549
+ * Open questions as stored. Older files hold plain strings; they become
550
+ * questions with ids in list order. Entries without question text are dropped.
551
+ */
552
+ function normalizeOpenQuestions(value) {
553
+ if (!Array.isArray(value)) return [];
554
+ const questions = [];
555
+ for (const entry of value) {
556
+ if (typeof entry === "string") {
557
+ if (entry.trim()) questions.push({
558
+ id: "",
559
+ question: entry
560
+ });
561
+ continue;
562
+ }
563
+ if (typeof entry !== "object" || entry === null) continue;
564
+ const { id, question, why, options, recommended, storyIds } = entry;
565
+ if (typeof question !== "string" || !question.trim()) continue;
566
+ const strings = (list) => Array.isArray(list) ? list.filter((item) => typeof item === "string" && item.length > 0) : [];
567
+ questions.push({
568
+ id: typeof id === "string" ? id : "",
569
+ question,
570
+ ...typeof why === "string" && why ? { why } : {},
571
+ ...strings(options).length ? { options: strings(options) } : {},
572
+ ...typeof recommended === "string" && recommended ? { recommended } : {},
573
+ ...strings(storyIds).length ? { storyIds: strings(storyIds) } : {}
574
+ });
575
+ }
576
+ let highest = questions.reduce((max, question) => {
577
+ const match = /^Q(\d+)$/.exec(question.id);
578
+ return match ? Math.max(max, Number(match[1])) : max;
579
+ }, 0);
580
+ return questions.map((question) => question.id ? question : {
581
+ ...question,
582
+ id: formatQuestionId(++highest)
583
+ });
584
+ }
585
+ function formatQuestionId(number) {
586
+ return `Q${String(number).padStart(3, "0")}`;
587
+ }
588
+ /**
589
+ * The next question id. Answered questions are quoted in decisions, so an id
590
+ * is never handed out twice: the high-water mark is kept in metadata.
591
+ */
592
+ function nextQuestionId(prd, extra = []) {
593
+ const present = [...prd.openQuestions, ...extra].reduce((max, question) => {
594
+ const match = /^Q(\d+)$/.exec(question.id);
595
+ return match ? Math.max(max, Number(match[1])) : max;
596
+ }, 0);
597
+ const next = Math.max(prd.metadata.lastQuestionNumber ?? 0, present) + 1;
598
+ prd.metadata.lastQuestionNumber = next;
599
+ return formatQuestionId(next);
600
+ }
601
+ /** Open questions that block a story that is not completed yet. */
602
+ function blockingQuestions(prd) {
603
+ const unfinished = new Set(prd.userStories.filter((story) => story.status !== "completed").map((story) => story.id));
604
+ return prd.openQuestions.filter((question) => question.storyIds?.some((id) => unfinished.has(id)));
605
+ }
606
+ //#endregion
607
+ //#region src/attachments.ts
608
+ /**
609
+ * Adds an attachment and links it to the given stories. The caller checks
610
+ * that a `path` exists on disk; this only validates the PRD.
611
+ */
612
+ function addAttachment(prd, input, today) {
613
+ if (Boolean(input.path) === Boolean(input.url)) throw new Error("Give either path or url for an attachment, not both.");
614
+ if (input.url && !/^https?:\/\//i.test(input.url)) throw new Error("An attachment url must start with http:// or https://.");
615
+ const path = input.path ? assertSafeRelativePath(input.path, "attachment path") : void 0;
616
+ const stories = (input.storyIds ?? []).map((id) => findStory(prd, id));
617
+ const id = nextAttachmentId(prd);
618
+ prd.attachments.push({
619
+ id,
620
+ title: input.title,
621
+ ...path ? { path } : { url: input.url },
622
+ ...input.note ? { note: input.note } : {}
623
+ });
624
+ for (const story of stories) story.attachmentIds = [.../* @__PURE__ */ new Set([...story.attachmentIds ?? [], id])];
625
+ appendChangeLog(prd, `Added attachment ${id} (${input.title})`, today);
626
+ return {
627
+ attachment_id: id,
628
+ path: path ? attachmentProjectPath(input.filename, path) : null,
629
+ stories_updated: stories.map((story) => story.id),
630
+ total_attachments: prd.attachments.length
631
+ };
632
+ }
633
+ /**
634
+ * Issues the next attachment id and advances the high-water mark, like story
635
+ * ids. Ids still linked from stories count too: a writer that predates
636
+ * attachments drops the list and the counter but keeps the stories' links,
637
+ * and those must never come to mean a different file.
638
+ */
639
+ function nextAttachmentId(prd) {
640
+ const numbers = [...prd.attachments.map((attachment) => attachment.id), ...prd.userStories.flatMap((story) => story.attachmentIds ?? [])].map((id) => Number(/^ATT(\d+)$/.exec(id)?.[1] ?? 0));
641
+ const next = Math.max(prd.metadata.lastAttachmentNumber ?? 0, 0, ...numbers) + 1;
642
+ prd.metadata.lastAttachmentNumber = next;
643
+ return `ATT${String(next).padStart(3, "0")}`;
644
+ }
645
+ /**
646
+ * Removes an attachment and every story's link to it. The file itself stays
647
+ * on disk.
648
+ */
649
+ function removeAttachment(prd, attachmentId, today) {
650
+ const attachment = findAttachment(prd, attachmentId);
651
+ prd.attachments = prd.attachments.filter((candidate) => candidate.id !== attachment.id);
652
+ const storiesUpdated = [];
653
+ for (const story of prd.userStories) if (story.attachmentIds?.includes(attachment.id)) {
654
+ story.attachmentIds = story.attachmentIds.filter((id) => id !== attachment.id);
655
+ storiesUpdated.push(story.id);
656
+ }
657
+ appendChangeLog(prd, `Removed attachment ${attachment.id} (${attachment.title})`, today);
658
+ return {
659
+ attachment_id: attachment.id,
660
+ stories_updated: storiesUpdated,
661
+ total_attachments: prd.attachments.length
662
+ };
663
+ }
664
+ /**
665
+ * Changes an attachment's title or note, and which stories use it: with
666
+ * storyIds, links are added and removed so exactly those stories use it.
667
+ */
668
+ function updateAttachment(prd, input, today) {
669
+ const attachment = findAttachment(prd, input.attachmentId);
670
+ if (input.title !== void 0) attachment.title = input.title;
671
+ if (input.note !== void 0) {
672
+ if (input.note.trim()) attachment.note = input.note;
673
+ else delete attachment.note;
674
+ }
675
+ const storiesUpdated = [];
676
+ if (input.storyIds !== void 0) {
677
+ const wanted = new Set(input.storyIds.map((id) => findStory(prd, id).id));
678
+ for (const story of prd.userStories) {
679
+ const linked = story.attachmentIds?.includes(attachment.id) ?? false;
680
+ if (wanted.has(story.id) && !linked) {
681
+ story.attachmentIds = [...story.attachmentIds ?? [], attachment.id];
682
+ storiesUpdated.push(story.id);
683
+ } else if (!wanted.has(story.id) && linked) {
684
+ story.attachmentIds = story.attachmentIds.filter((id) => id !== attachment.id);
685
+ storiesUpdated.push(story.id);
686
+ }
687
+ }
688
+ }
689
+ appendChangeLog(prd, `Updated attachment ${attachment.id} (${attachment.title})`, today);
690
+ return {
691
+ attachment_id: attachment.id,
692
+ stories_updated: storiesUpdated
693
+ };
694
+ }
695
+ //#endregion
696
+ //#region src/markdown.ts
697
+ const STATUS_LABELS = {
698
+ not_started: "[not started]",
699
+ research: "[research]",
700
+ in_progress: "[in progress]",
701
+ review: "[review]",
702
+ completed: "[completed]",
703
+ blocked: "[blocked]"
704
+ };
705
+ /**
706
+ * Pass the PRD file name to link attachment files relative to `.prds/`, where
707
+ * the markdown export is written.
708
+ */
709
+ function formatPrdMarkdown(prd, filename) {
710
+ const lines = [];
711
+ lines.push(`# ${prd.introduction.title}`, "");
712
+ lines.push("## Introduction", "", prd.introduction.overview, "");
713
+ lines.push(`**Last Updated:** ${prd.introduction.lastUpdated}`);
714
+ lines.push(`**Version:** ${prd.metadata.version}`, "");
715
+ lines.push("## Problem Statement", "", prd.problemStatement.problem, "");
716
+ lines.push("### Market Opportunity", prd.problemStatement.marketOpportunity, "");
717
+ lines.push("### Target Users");
718
+ lines.push(...bullets(prd.problemStatement.targetUsers));
719
+ lines.push("", "## Solution Overview", "", prd.solutionOverview.description, "");
720
+ lines.push("### Key Features", ...bullets(prd.solutionOverview.keyFeatures));
721
+ lines.push("", "### Success Metrics");
722
+ lines.push(...bullets(prd.solutionOverview.successMetrics));
723
+ lines.push("", "## Scope Guardrails", "");
724
+ lines.push("### Non-Goals", ...bullets(prd.nonGoals, "None specified"));
725
+ lines.push("", "### Out of Scope", ...bullets(prd.outOfScope, "None specified"));
726
+ lines.push("", "### Assumptions", ...bullets(prd.assumptions, "None specified"));
727
+ lines.push("", "### Open Questions", ...bullets(prd.openQuestions.map((question) => `${question.id}: ${question.question}` + (question.storyIds?.length ? ` (blocks ${question.storyIds.join(", ")})` : "") + (question.recommended ? ` Recommended: ${question.recommended}` : "")), "None"));
728
+ if (prd.edgeCases.length > 0) {
729
+ lines.push("", "## Edge Cases");
730
+ for (const edgeCase of prd.edgeCases) {
731
+ const stories = edgeCase.storyIds?.length ? ` (${edgeCase.storyIds.join(", ")})` : "";
732
+ const behaviour = edgeCase.status === "decided" ? edgeCase.expectedBehavior : "OPEN: ask, do not assume";
733
+ lines.push(`- ${edgeCase.case}${stories} -> ${behaviour}`);
734
+ }
735
+ }
736
+ const security = [
737
+ ...prd.technicalContracts.permissions.map((item) => `Permission: ${item}`),
738
+ ...prd.technicalRequirements.complianceRequirements.map((item) => `Data: ${item}`),
739
+ ...prd.securityConsiderations
740
+ ];
741
+ if (security.length > 0) lines.push("", "## Security", ...bullets(security));
742
+ const notApplicable = Object.entries(prd.notApplicable);
743
+ if (notApplicable.length > 0) lines.push("", "## Not Applicable", ...notApplicable.map(([topic, reason]) => `- ${topic}${reason ? `: ${reason}` : ""}`));
744
+ if (prd.designGuidance.length > 0) lines.push("", "## Design Guidance", ...bullets(prd.designGuidance));
745
+ if (prd.risks.length > 0) {
746
+ lines.push("", "## Risks");
747
+ for (const risk of prd.risks) lines.push(`- [${risk.severity}] ${risk.description} | Mitigation: ${risk.mitigation} | Owner: ${risk.owner}`);
748
+ }
749
+ if (prd.dependencies.length > 0) {
750
+ lines.push("", "## Dependencies");
751
+ for (const dependency of prd.dependencies) {
752
+ const mode = dependency.blocking ? "blocking" : "non-blocking";
753
+ lines.push(`- ${dependency.name} (${mode}) - ${dependency.description}`);
754
+ }
755
+ }
756
+ if (prd.attachments.length > 0) {
757
+ lines.push("", "## Attachments");
758
+ for (const attachment of prd.attachments) lines.push(formatAttachment(attachment, filename));
759
+ }
760
+ lines.push("", "## User Stories", "");
761
+ for (const priority of [
762
+ "P0",
763
+ "P1",
764
+ "P2",
765
+ "P3"
766
+ ]) {
767
+ const stories = prd.userStories.filter((s) => s.priority === priority);
768
+ if (stories.length === 0) continue;
769
+ lines.push(`### Priority ${priority}`, "");
770
+ for (const story of stories) lines.push(...formatStory(story));
771
+ }
772
+ lines.push("", "## Progress", "");
773
+ lines.push(`**Overall:** ${prd.progress.overall}% (${prd.progress.completed}/${prd.progress.total} stories)`);
774
+ if (prd.progress.blocked > 0) lines.push(`**Blocked:** ${prd.progress.blocked} stories need attention`);
775
+ if (prd.rolloutPlan.rolloutPhases.length > 0) lines.push("", "## Rollout Plan", ...bullets(prd.rolloutPlan.rolloutPhases));
776
+ if (prd.measurementPlan.targetMetrics.length > 0) lines.push("", "## Measurement Plan", ...bullets(prd.measurementPlan.targetMetrics));
777
+ lines.push("", "---", "", `*Approver: ${prd.metadata.approver || "TBD"}*`, "");
778
+ return lines.join("\n");
779
+ }
780
+ function formatStory(story) {
781
+ const lines = [
782
+ `#### ${story.id}: ${story.title} ${STATUS_LABELS[story.status]} [${story.estimatedComplexity}]`,
783
+ "",
784
+ `**User Story:** ${story.userStory}`,
785
+ "",
786
+ `**Business Value:** ${story.businessValue}`,
787
+ "",
788
+ "**Acceptance Criteria:**",
789
+ ...bullets(story.acceptanceCriteria)
790
+ ];
791
+ if (story.dependencies.length > 0) lines.push("", `**Dependencies:** ${story.dependencies.join(", ")}`);
792
+ if (story.attachmentIds?.length) lines.push("", `**Attachments:** ${story.attachmentIds.join(", ")}`);
793
+ if (story.designNotes?.length) lines.push("", "**Design Notes:**", ...bullets(story.designNotes));
794
+ if (story.securityNotes?.length) lines.push("", "**Security Notes:**", ...bullets(story.securityNotes));
795
+ if (story.verification) lines.push("", `**Verified:** ${story.verification.verifiedAt} (${story.verification.checks.join(", ")})`);
796
+ lines.push("");
797
+ return lines;
798
+ }
799
+ function formatAttachment(attachment, filename) {
800
+ const title = oneLine(attachment.title).replace(/[[\]]/g, "\\$&");
801
+ const target = attachment.url ? linkTarget(attachment.url) : filename ? linkTarget(encodeURI(`${attachmentsFolder(filename)}/${attachment.path}`)) : void 0;
802
+ const label = target ? `[${title}](${target})` : `${title} (${attachment.path})`;
803
+ const note = attachment.note ? ` - ${oneLine(attachment.note)}` : "";
804
+ return `- ${attachment.id}: ${label}${note}`;
805
+ }
806
+ /** Keeps a list item on one line, so text cannot start a new block. */
807
+ function oneLine(value) {
808
+ return value.replace(/\s+/g, " ").trim();
809
+ }
810
+ /** Parentheses and spaces would end a markdown link target early. */
811
+ function linkTarget(value) {
812
+ return value.replace(/\s/g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29");
813
+ }
814
+ function bullets(items, emptyLabel) {
815
+ if (items.length === 0) return emptyLabel ? [`- ${emptyLabel}`] : [];
816
+ return items.map((item) => `- ${item}`);
817
+ }
818
+ //#endregion
819
+ //#region src/plan-check.ts
820
+ /** The not-applicable topic each "missing" check is about. */
821
+ const CHECK_TOPICS = {
822
+ "edge-cases": "edgeCases",
823
+ "design-guidance": "design",
824
+ security: "security",
825
+ permissions: "security",
826
+ "global-acceptance-criteria": "qualityBar",
827
+ "target-metrics": "measurement",
828
+ rollout: "rollout",
829
+ "data-models": "dataModel"
830
+ };
831
+ /** Above this many stories, grouping them into phases is recommended. */
832
+ const PHASE_THRESHOLD = 5;
833
+ function checkPlan(prd) {
834
+ const items = [];
835
+ const stories = prd.userStories;
836
+ if (stories.length === 0) items.push({
837
+ id: "stories",
838
+ section: "userStories",
839
+ message: "Add user stories to define specific functionality",
840
+ severity: "required"
841
+ });
842
+ const withoutCriteria = stories.filter((story) => story.acceptanceCriteria.length === 0);
843
+ if (withoutCriteria.length > 0) items.push({
844
+ id: "stories-without-criteria",
845
+ section: "userStories",
846
+ message: `${withoutCriteria.length} stories have no acceptance criteria`,
847
+ severity: "required",
848
+ storyIds: withoutCriteria.map((story) => story.id)
849
+ });
850
+ if (stories.length > 0 && prd.edgeCases.length === 0) items.push({
851
+ id: "edge-cases",
852
+ section: "edgeCases",
853
+ message: "List what can go wrong (bad input, partial success, retries, permissions, limits, time zones) and what should happen",
854
+ severity: "required"
855
+ });
856
+ const openEdgeCases = prd.edgeCases.filter((edgeCase) => edgeCase.status === "open");
857
+ if (openEdgeCases.length > 0) items.push({
858
+ id: "open-edge-cases",
859
+ section: "edgeCases",
860
+ message: `${openEdgeCases.length} edge cases are still open; decide what should happen`,
861
+ severity: "required",
862
+ storyIds: [...new Set(openEdgeCases.flatMap((edgeCase) => edgeCase.storyIds ?? []))]
863
+ });
864
+ if (stories.length > 0 && prd.designGuidance.length === 0) items.push({
865
+ id: "design-guidance",
866
+ section: "designGuidance",
867
+ message: "Add design guidance: the components, layout and tone stories should follow, and how empty and error states look",
868
+ severity: "recommended"
869
+ });
870
+ if (stories.length > 0 && prd.technicalContracts.permissions.length === 0 && (prd.technicalContracts.dataModels.length > 0 || prd.technicalRequirements.integrationNeeds.length > 0)) items.push({
871
+ id: "permissions",
872
+ section: "technicalContracts",
873
+ message: "Say who can see and change what (roles, ownership, other tenants) in technicalContracts.permissions",
874
+ severity: "required"
875
+ });
876
+ if (stories.length > 0 && prd.securityConsiderations.length === 0) items.push({
877
+ id: "security",
878
+ section: "securityConsiderations",
879
+ message: "Add security considerations: think like an attacker (inputs, access to other users' data, secrets, abuse, rate limits) and state the rules that prevent it",
880
+ severity: "recommended"
881
+ });
882
+ if (prd.nonGoals.length === 0 && prd.outOfScope.length === 0) items.push({
883
+ id: "scope",
884
+ section: "nonGoals",
885
+ message: "Define both non-goals and out-of-scope items to reduce implementation drift",
886
+ severity: "required"
887
+ });
888
+ else if (prd.nonGoals.length === 0 || prd.outOfScope.length === 0) items.push({
889
+ id: "scope",
890
+ section: prd.nonGoals.length === 0 ? "nonGoals" : "outOfScope",
891
+ message: "Define both non-goals and out-of-scope items to reduce implementation drift",
892
+ severity: "recommended"
893
+ });
894
+ if (prd.solutionOverview.successMetrics.length === 0) items.push({
895
+ id: "success-metrics",
896
+ section: "solutionOverview",
897
+ message: "Define success metrics to measure progress",
898
+ severity: "recommended"
899
+ });
900
+ if (prd.acceptanceCriteria.global.length === 0) items.push({
901
+ id: "global-acceptance-criteria",
902
+ section: "acceptanceCriteria",
903
+ message: "Add global acceptance criteria for quality standards",
904
+ severity: "recommended"
905
+ });
906
+ const blocking = blockingQuestions(prd);
907
+ const others = prd.openQuestions.filter((question) => !blocking.includes(question));
908
+ if (blocking.length > 0) items.push({
909
+ id: "blocking-questions",
910
+ section: "openQuestions",
911
+ message: `${blocking.length} open questions block stories; answer them before those stories are built`,
912
+ severity: "required",
913
+ storyIds: [...new Set(blocking.flatMap((question) => question.storyIds ?? []))]
914
+ });
915
+ if (others.length > 0) items.push({
916
+ id: "open-questions",
917
+ section: "openQuestions",
918
+ message: `${others.length} open questions remain unresolved`,
919
+ severity: "recommended"
920
+ });
921
+ if (prd.measurementPlan.targetMetrics.length === 0) items.push({
922
+ id: "target-metrics",
923
+ section: "measurementPlan",
924
+ message: "Define target metrics in measurementPlan to validate delivery impact",
925
+ severity: "recommended"
926
+ });
927
+ if (prd.rolloutPlan.rolloutPhases.length === 0) items.push({
928
+ id: "rollout",
929
+ section: "rolloutPlan",
930
+ message: "Add rollout phases and rollback conditions",
931
+ severity: "recommended"
932
+ });
933
+ if (stories.length > 0 && prd.technicalContracts.dataModels.length === 0) items.push({
934
+ id: "data-models",
935
+ section: "technicalContracts",
936
+ message: "Describe the main entities and how they relate in technicalContracts.dataModels",
937
+ severity: "recommended"
938
+ });
939
+ const vague = stories.filter((story) => story.acceptanceCriteria.length > 0 && story.acceptanceCriteria.length < 2);
940
+ if (vague.length > 0) items.push({
941
+ id: "vague-stories",
942
+ section: "userStories",
943
+ message: `${vague.length} stories need more detailed acceptance criteria`,
944
+ severity: "recommended",
945
+ storyIds: vague.map((story) => story.id)
946
+ });
947
+ const withoutSeams = stories.filter((story) => story.status !== "completed" && !story.testSeams?.length);
948
+ if (withoutSeams.length > 0) items.push({
949
+ id: "test-seams",
950
+ section: "userStories",
951
+ message: `${withoutSeams.length} stories do not say where they are tested (testSeams)`,
952
+ severity: "recommended",
953
+ storyIds: withoutSeams.map((story) => story.id)
954
+ });
955
+ const phased = new Set(prd.customPhases.flatMap((phase) => phase.userStoryIds));
956
+ const unphased = stories.filter((story) => !phased.has(story.id));
957
+ if (stories.length > PHASE_THRESHOLD && unphased.length > 0) items.push({
958
+ id: "phases",
959
+ section: "customPhases",
960
+ message: `${unphased.length} stories are not in a phase; group them into phases in build order`,
961
+ severity: "recommended",
962
+ storyIds: unphased.map((story) => story.id)
963
+ });
964
+ const blocked = stories.filter((story) => story.status === "blocked");
965
+ if (blocked.length > 0) items.push({
966
+ id: "blocked-stories",
967
+ section: "userStories",
968
+ message: `${blocked.length} stories are blocked and need attention`,
969
+ severity: "recommended",
970
+ storyIds: blocked.map((story) => story.id)
971
+ });
972
+ const applicable = items.filter((item) => {
973
+ const topic = CHECK_TOPICS[item.id];
974
+ return !topic || !isNotApplicable(prd, topic);
975
+ });
976
+ return {
977
+ ready_to_build: !applicable.some((item) => item.severity === "required"),
978
+ items: applicable
979
+ };
980
+ }
981
+ //#endregion
982
+ //#region src/planning-operations.ts
983
+ /**
984
+ * Pure transforms for shaping a PRD after it was created: sections, decisions,
985
+ * open questions, glossary and phases. Same contract as `prd-operations`:
986
+ * mutate the loaded PRD, return the tool payload.
987
+ */
988
+ /** Sections whose value replaces the whole list. */
989
+ const LIST_SECTIONS = /* @__PURE__ */ new Set([
990
+ "nonGoals",
991
+ "outOfScope",
992
+ "assumptions",
993
+ "designGuidance",
994
+ "securityConsiderations"
995
+ ]);
996
+ function updatePrdSection(prd, input, today) {
997
+ const parsed = PrdSectionValueSchemas[input.section].safeParse(input.value);
998
+ if (!parsed.success) {
999
+ const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "value"}: ${issue.message}`).join("; ");
1000
+ throw new Error(`Invalid value for section "${input.section}": ${issues}`);
1001
+ }
1002
+ const value = parsed.data;
1003
+ let updated;
1004
+ if (input.section === "risks") {
1005
+ const risks = value;
1006
+ const assigned = [];
1007
+ for (const risk of risks) assigned.push({
1008
+ ...risk,
1009
+ id: risk.id ?? nextId(assigned, "RISK")
1010
+ });
1011
+ prd.risks = assigned;
1012
+ updated = assigned.map((risk) => risk.id);
1013
+ } else if (input.section === "dependencies") {
1014
+ const items = value;
1015
+ const assigned = [];
1016
+ for (const item of items) assigned.push({
1017
+ ...item,
1018
+ id: item.id ?? nextId(assigned, "DEP")
1019
+ });
1020
+ prd.dependencies = assigned;
1021
+ updated = assigned.map((item) => item.id);
1022
+ } else if (input.section === "openQuestions") {
1023
+ const items = value;
1024
+ const storyIds = new Set(prd.userStories.map((story) => story.id));
1025
+ const unknown = items.flatMap((item) => typeof item === "string" ? [] : item.storyIds ?? []).filter((id) => !storyIds.has(id));
1026
+ if (unknown.length > 0) throw new Error(`Invalid value for section "openQuestions": unknown stories ${[...new Set(unknown)].join(", ")}`);
1027
+ const assigned = [];
1028
+ for (const item of items) {
1029
+ const { id, storyIds: linked, options, ...rest } = typeof item === "string" ? { question: item } : item;
1030
+ assigned.push({
1031
+ ...rest,
1032
+ id: id ?? nextQuestionId(prd, assigned),
1033
+ ...options?.length ? { options } : {},
1034
+ ...linked?.length ? { storyIds: linked } : {}
1035
+ });
1036
+ }
1037
+ prd.openQuestions = assigned;
1038
+ updated = assigned.map((item) => item.id);
1039
+ } else if (input.section === "edgeCases") {
1040
+ const items = value;
1041
+ const storyIds = new Set(prd.userStories.map((story) => story.id));
1042
+ const unknown = items.flatMap((item) => item.storyIds ?? []).filter((id) => !storyIds.has(id));
1043
+ if (unknown.length > 0) throw new Error(`Invalid value for section "edgeCases": unknown stories ${[...new Set(unknown)].join(", ")}`);
1044
+ const assigned = [];
1045
+ for (const item of items) {
1046
+ const { storyIds: linked, ...rest } = item;
1047
+ assigned.push({
1048
+ ...rest,
1049
+ id: item.id ?? nextId([...prd.edgeCases, ...assigned], "EC"),
1050
+ ...linked?.length ? { storyIds: linked } : {}
1051
+ });
1052
+ }
1053
+ prd.edgeCases = assigned;
1054
+ updated = assigned.map((item) => item.id);
1055
+ } else if (LIST_SECTIONS.has(input.section)) {
1056
+ const key = input.section;
1057
+ prd[key] = value;
1058
+ updated = [key];
1059
+ } else {
1060
+ const key = input.section;
1061
+ Object.assign(prd[key], value);
1062
+ updated = Object.keys(value);
1063
+ }
1064
+ appendChangeLog(prd, `Updated ${input.section}`, today);
1065
+ return {
1066
+ section: input.section,
1067
+ updated
1068
+ };
1069
+ }
1070
+ function addDecision(prd, input, today) {
1071
+ let superseded = null;
1072
+ if (input.supersedes) {
1073
+ const previous = prd.decisionLog.find((entry) => entry.id === input.supersedes);
1074
+ if (!previous) throw new Error(`Decision "${input.supersedes}" not found.`);
1075
+ previous.status = "superseded";
1076
+ superseded = previous.id;
1077
+ }
1078
+ const id = nextId(prd.decisionLog, "DEC");
1079
+ prd.decisionLog.push({
1080
+ id,
1081
+ date: today,
1082
+ decision: input.decision,
1083
+ rationale: input.rationale,
1084
+ status: input.status,
1085
+ ...input.owner ? { owner: input.owner } : {},
1086
+ ...input.topic ? { topic: input.topic } : {}
1087
+ });
1088
+ appendChangeLog(prd, superseded ? `Recorded ${id} (supersedes ${superseded})` : `Recorded ${id}`, today);
1089
+ return {
1090
+ decision_id: id,
1091
+ superseded,
1092
+ total_decisions: prd.decisionLog.length
1093
+ };
1094
+ }
1095
+ function resolveOpenQuestion(prd, input, today) {
1096
+ const wanted = input.question ? normalizeText(input.question) : null;
1097
+ const index = prd.openQuestions.findIndex((question) => input.questionId ? question.id === input.questionId : normalizeText(question.question) === wanted);
1098
+ if (index === -1) throw new Error(`Open question not found: "${input.questionId ?? input.question}". ` + (prd.openQuestions.length ? `Open questions: ${prd.openQuestions.map((q) => `${q.id} "${q.question}"`).join(", ")}.` : "This PRD has no open questions."));
1099
+ const [question] = prd.openQuestions.splice(index, 1);
1100
+ let decisionId = null;
1101
+ if (input.recordDecision) decisionId = addDecision(prd, {
1102
+ filename: input.filename,
1103
+ decision: input.answer,
1104
+ rationale: `Answers ${question.id}: ${question.question}` + (question.why ? ` (${question.why})` : ""),
1105
+ topic: `open-question:${question.id}`,
1106
+ status: "accepted"
1107
+ }, today).decision_id;
1108
+ else appendChangeLog(prd, `Resolved ${question.id}: ${question.question}`, today);
1109
+ return {
1110
+ remaining_questions: prd.openQuestions.length,
1111
+ decision_id: decisionId
1112
+ };
1113
+ }
1114
+ /** Answer an open edge case: it becomes decided with the given behaviour. */
1115
+ function decideEdgeCase(prd, input, today) {
1116
+ const edgeCase = prd.edgeCases.find((candidate) => candidate.id === input.edgeCaseId);
1117
+ if (!edgeCase) throw new Error(`Edge case "${input.edgeCaseId}" not found.`);
1118
+ edgeCase.expectedBehavior = input.expectedBehavior.trim();
1119
+ edgeCase.status = "decided";
1120
+ appendChangeLog(prd, `Decided ${edgeCase.id}: ${edgeCase.case}`, today);
1121
+ return {
1122
+ edge_case_id: edgeCase.id,
1123
+ open_edge_cases: prd.edgeCases.filter((candidate) => candidate.status === "open").length
1124
+ };
1125
+ }
1126
+ /** Adds a term, or replaces the definition of an existing one (any casing). */
1127
+ function addGlossaryTerm(prd, input, today) {
1128
+ const term = input.term.trim();
1129
+ const existing = prd.glossary.find((entry) => entry.term.toLowerCase() === term.toLowerCase());
1130
+ if (existing) {
1131
+ existing.term = term;
1132
+ existing.definition = input.definition;
1133
+ existing.avoid = input.avoid;
1134
+ } else prd.glossary.push({
1135
+ term,
1136
+ definition: input.definition,
1137
+ avoid: input.avoid
1138
+ });
1139
+ appendChangeLog(prd, `${existing ? "Redefined" : "Defined"} glossary term "${term}"`, today);
1140
+ return {
1141
+ term,
1142
+ replaced: Boolean(existing),
1143
+ total_terms: prd.glossary.length
1144
+ };
1145
+ }
1146
+ function updatePhase(prd, input, today) {
1147
+ const phase = findPhase(prd, input.phaseId);
1148
+ if (input.name !== void 0) {
1149
+ const name = input.name.trim();
1150
+ if (prd.customPhases.some((other) => other.id !== phase.id && other.name.toLowerCase() === name.toLowerCase())) throw new Error(`A phase named "${name}" already exists.`);
1151
+ phase.name = name;
1152
+ }
1153
+ if (input.description !== void 0) phase.description = input.description;
1154
+ if (input.color !== void 0) phase.color = input.color;
1155
+ appendChangeLog(prd, `Updated phase ${phase.id}`, today);
1156
+ return phasesPayload(prd);
1157
+ }
1158
+ /** Deletes a phase; its stories stay in the PRD without a phase. */
1159
+ function deletePhase(prd, input, today) {
1160
+ const phase = findPhase(prd, input.phaseId);
1161
+ prd.customPhases = prd.customPhases.filter((other) => other.id !== phase.id);
1162
+ renumberPhases(prd.customPhases);
1163
+ appendChangeLog(prd, `Deleted phase ${phase.id} (${phase.name})`, today);
1164
+ return phasesPayload(prd);
1165
+ }
1166
+ function reorderPhases(prd, input, today) {
1167
+ const known = prd.customPhases.map((phase) => phase.id).sort();
1168
+ const given = [...input.phaseIds].sort();
1169
+ 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"}.`);
1170
+ prd.customPhases = input.phaseIds.map((id) => findPhase(prd, id));
1171
+ renumberPhases(prd.customPhases);
1172
+ appendChangeLog(prd, `Reordered phases: ${input.phaseIds.join(", ")}`, today);
1173
+ return phasesPayload(prd);
1174
+ }
1175
+ function findPhase(prd, phaseId) {
1176
+ const phase = prd.customPhases.find((candidate) => candidate.id === phaseId);
1177
+ if (!phase) {
1178
+ const known = prd.customPhases.map((candidate) => candidate.id).join(", ");
1179
+ throw new Error(`Phase "${phaseId}" not found.` + (known ? ` Known phases: ${known}.` : " This PRD has no phases yet."));
1180
+ }
1181
+ return phase;
1182
+ }
1183
+ function renumberPhases(phases) {
1184
+ phases.forEach((phase, index) => {
1185
+ phase.order = index;
1186
+ });
1187
+ }
1188
+ function phasesPayload(prd) {
1189
+ return { phases: [...prd.customPhases].sort((a, b) => a.order - b.order).map((phase) => ({
1190
+ id: phase.id,
1191
+ name: phase.name,
1192
+ order: phase.order,
1193
+ user_story_ids: phase.userStoryIds
1194
+ })) };
1195
+ }
1196
+ function normalizeText(value) {
1197
+ return value.trim().replace(/\s+/g, " ").toLowerCase();
1198
+ }
1199
+ //#endregion
1200
+ //#region src/prd.service.ts
1201
+ /**
1202
+ * A write was based on an older revision of the PRD than the one on disk:
1203
+ * someone else (an agent, Loop, another editor) changed it in between. Read
1204
+ * the PRD again and retry; never overwrite.
1205
+ */
1206
+ var PrdRevisionConflictError = class extends Error {
1207
+ filename;
1208
+ expectedRevision;
1209
+ currentRevision;
1210
+ code = "PRD_REVISION_CONFLICT";
1211
+ constructor(filename, expectedRevision, currentRevision) {
1212
+ super(`PRD "${filename}" was changed by someone else since it was read (revision ${expectedRevision}, now ${currentRevision}). Read it again and retry.`);
1213
+ this.filename = filename;
1214
+ this.expectedRevision = expectedRevision;
1215
+ this.currentRevision = currentRevision;
1216
+ this.name = "PrdRevisionConflictError";
1217
+ }
1218
+ };
1219
+ function createPrdService(deps) {
1220
+ return new PrdService(deps);
1221
+ }
1222
+ var PrdService = class {
1223
+ deps;
1224
+ constructor(deps) {
1225
+ this.deps = deps;
1226
+ }
1227
+ get prdsDir() {
1228
+ return join(this.deps.rootPath, ".prds");
1229
+ }
1230
+ async list() {
1231
+ const filenames = await this.listFilenames();
1232
+ const prds = [];
1233
+ const warnings = [];
1234
+ for (const filename of filenames) try {
1235
+ const prd = await this.load(filename);
1236
+ prds.push({
1237
+ filename,
1238
+ title: prd.introduction.title,
1239
+ last_updated: prd.metadata.lastUpdated,
1240
+ progress: prd.progress.overall,
1241
+ total_stories: prd.progress.total,
1242
+ completed_stories: prd.progress.completed,
1243
+ blocked_stories: prd.progress.blocked
1244
+ });
1245
+ } catch (error) {
1246
+ warnings.push(`Skipped ${filename}: ${error instanceof Error ? error.message : "unreadable"}`);
1247
+ }
1248
+ return {
1249
+ prds,
1250
+ total: prds.length,
1251
+ prds_dir: this.prdsDir,
1252
+ warnings
1253
+ };
1254
+ }
1255
+ async get(input) {
1256
+ const filename = this.safeName(input.filename);
1257
+ const prd = await this.load(filename);
1258
+ return {
1259
+ filename,
1260
+ path: join(this.prdsDir, filename),
1261
+ prd
1262
+ };
1263
+ }
1264
+ async create(input) {
1265
+ await this.deps.mkdir(this.prdsDir);
1266
+ const filename = `${slugify(input.title)}.json`;
1267
+ const path = join(this.prdsDir, filename);
1268
+ if (await this.deps.fileExists(path)) throw new Error(`A PRD named "${filename}" already exists. Use a different title or delete it first with delete_prd.`);
1269
+ const today = this.today();
1270
+ const defaults = input.template ? getTemplate(input.template).defaults : {};
1271
+ const prd = {
1272
+ introduction: {
1273
+ title: input.title,
1274
+ overview: input.overview,
1275
+ lastUpdated: today
1276
+ },
1277
+ problemStatement: {
1278
+ problem: input.problemStatement,
1279
+ marketOpportunity: input.marketOpportunity,
1280
+ targetUsers: input.targetUsers
1281
+ },
1282
+ solutionOverview: {
1283
+ description: input.solutionDescription,
1284
+ keyFeatures: input.keyFeatures,
1285
+ successMetrics: input.successMetrics
1286
+ },
1287
+ nonGoals: input.nonGoals ?? defaults.nonGoals ?? [],
1288
+ outOfScope: input.outOfScope ?? defaults.outOfScope ?? [],
1289
+ assumptions: input.assumptions ?? [],
1290
+ openQuestions: normalizeOpenQuestions([...input.openQuestions ?? [], ...defaults.openQuestions ?? []]),
1291
+ risks: [],
1292
+ dependencies: [],
1293
+ userStories: [],
1294
+ customPhases: [],
1295
+ storyTraceability: [],
1296
+ technicalRequirements: {
1297
+ constraints: defaults.technicalConstraints ?? [],
1298
+ integrationNeeds: [],
1299
+ complianceRequirements: []
1300
+ },
1301
+ technicalContracts: {
1302
+ apis: [],
1303
+ dataModels: [],
1304
+ permissions: [],
1305
+ integrationBoundaries: []
1306
+ },
1307
+ acceptanceCriteria: {
1308
+ global: defaults.globalAcceptanceCriteria ?? [],
1309
+ qualityStandards: defaults.qualityStandards ?? []
1310
+ },
1311
+ constraints: {
1312
+ timeline: "",
1313
+ resources: [],
1314
+ nonNegotiables: []
1315
+ },
1316
+ rolloutPlan: {
1317
+ featureFlags: [],
1318
+ migrationPlan: [],
1319
+ rolloutPhases: defaults.rolloutPhases ?? [],
1320
+ rollbackConditions: defaults.rollbackConditions ?? []
1321
+ },
1322
+ measurementPlan: {
1323
+ events: [],
1324
+ dashboards: [],
1325
+ baselineMetrics: [],
1326
+ targetMetrics: [],
1327
+ guardrailMetrics: []
1328
+ },
1329
+ edgeCases: [],
1330
+ designGuidance: [],
1331
+ securityConsiderations: [],
1332
+ notApplicable: {},
1333
+ decisionLog: [],
1334
+ glossary: [],
1335
+ attachments: [],
1336
+ agentTaskPackets: [],
1337
+ changeLog: [input.template ? `Initial PRD created from the ${input.template} template` : "Initial PRD created"],
1338
+ metadata: {
1339
+ version: "2.0",
1340
+ created: today,
1341
+ lastUpdated: today,
1342
+ lastValidatedAt: today,
1343
+ approver: ""
1344
+ },
1345
+ progress: {
1346
+ overall: 0,
1347
+ completed: 0,
1348
+ total: 0,
1349
+ blocked: 0
1350
+ }
1351
+ };
1352
+ await this.deps.writeFile(path, JSON.stringify(prd, null, 2));
1353
+ return {
1354
+ status: "success",
1355
+ filename,
1356
+ path
1357
+ };
1358
+ }
1359
+ async delete(input) {
1360
+ const filename = this.safeName(input.filename);
1361
+ try {
1362
+ await this.deps.unlink(join(this.prdsDir, filename));
1363
+ } catch (error) {
1364
+ if (isErrnoCode(error, "ENOENT")) throw new Error(`PRD file "${filename}" not found`);
1365
+ throw error;
1366
+ }
1367
+ return {
1368
+ status: "success",
1369
+ filename
1370
+ };
1371
+ }
1372
+ async addUserStory(input) {
1373
+ const filename = this.safeName(input.filename);
1374
+ const prd = await this.load(filename);
1375
+ const storyId = nextStoryId(prd);
1376
+ const title = input.title?.trim() || titleFromAction(input.action);
1377
+ const complexity = input.estimatedComplexity ?? assessComplexity(input.acceptanceCriteria);
1378
+ prd.userStories.push({
1379
+ id: storyId,
1380
+ title,
1381
+ userStory: renderUserStory(input),
1382
+ businessValue: input.benefit,
1383
+ acceptanceCriteria: input.acceptanceCriteria.filter((entry) => entry.trim().length > 0),
1384
+ status: "not_started",
1385
+ priority: input.priority,
1386
+ estimatedComplexity: complexity,
1387
+ dependencies: [],
1388
+ ...input.testSeams?.length ? { testSeams: input.testSeams } : {},
1389
+ ...input.designNotes?.length ? { designNotes: input.designNotes } : {},
1390
+ ...input.securityNotes?.length ? { securityNotes: input.securityNotes } : {}
1391
+ });
1392
+ if (input.dependencies?.length) findStory(prd, storyId).dependencies = validateDependencies(prd, storyId, input.dependencies);
1393
+ if (input.attachmentIds?.length) findStory(prd, storyId).attachmentIds = validateAttachmentIds(prd, input.attachmentIds);
1394
+ if (input.phaseId) assignStoryToPhase(prd, {
1395
+ filename,
1396
+ storyId,
1397
+ phaseId: input.phaseId
1398
+ }, this.today());
1399
+ recomputeProgress(prd);
1400
+ appendChangeLog(prd, `Added ${storyId} (${title})`, this.today());
1401
+ await this.save(filename, prd);
1402
+ return {
1403
+ story_id: storyId,
1404
+ title,
1405
+ complexity,
1406
+ total_stories: prd.userStories.length
1407
+ };
1408
+ }
1409
+ async updateUserStory(input) {
1410
+ return this.mutate(input.filename, (prd) => updateStory(prd, input, this.today()), input.expectedRevision);
1411
+ }
1412
+ async deleteUserStory(input) {
1413
+ const filename = this.safeName(input.filename);
1414
+ const prd = await this.load(filename);
1415
+ const result = deleteStory(prd, input.storyId, this.today());
1416
+ await this.save(filename, prd);
1417
+ return result;
1418
+ }
1419
+ async createCustomPhase(input) {
1420
+ const filename = this.safeName(input.filename);
1421
+ const prd = await this.load(filename);
1422
+ const result = createPhase(prd, input, this.today());
1423
+ await this.save(filename, prd);
1424
+ return result;
1425
+ }
1426
+ async assignStoryToPhase(input) {
1427
+ const filename = this.safeName(input.filename);
1428
+ const prd = await this.load(filename);
1429
+ const result = assignStoryToPhase(prd, input, this.today());
1430
+ await this.save(filename, prd);
1431
+ return result;
1432
+ }
1433
+ async updateStoryStatus(input) {
1434
+ const filename = this.safeName(input.filename);
1435
+ const current = await this.load(filename);
1436
+ const currentRevision = current.metadata.revision ?? 0;
1437
+ if (input.expectedRevision !== void 0 && input.expectedRevision !== currentRevision) throw new PrdRevisionConflictError(filename, input.expectedRevision, currentRevision);
1438
+ assertCanEnterStatus(current, findStory(current, input.storyId), input.status);
1439
+ let verification = null;
1440
+ if (input.status === "completed") {
1441
+ const result = await this.deps.verifyCompletion();
1442
+ if (!result.passed) throw new Error(buildVerificationFailure(input.storyId, result));
1443
+ verification = {
1444
+ verified_at: this.deps.now().toISOString(),
1445
+ checks: result.checks,
1446
+ passed: true
1447
+ };
1448
+ }
1449
+ const prd = await this.load(filename);
1450
+ const story = findStory(prd, input.storyId);
1451
+ assertCanEnterStatus(prd, story, input.status);
1452
+ const previousStatus = story.status;
1453
+ if (verification) {
1454
+ story.verification = {
1455
+ verifiedAt: verification.verified_at,
1456
+ checks: verification.checks,
1457
+ passed: true
1458
+ };
1459
+ story.completedAt = this.today();
1460
+ prd.metadata.lastValidatedAt = this.today();
1461
+ } else {
1462
+ delete story.verification;
1463
+ delete story.completedAt;
1464
+ }
1465
+ story.status = input.status;
1466
+ if (input.notes) story.notes = input.notes;
1467
+ recomputeProgress(prd);
1468
+ appendChangeLog(prd, `${story.id} ${previousStatus} -> ${story.status}`, this.today());
1469
+ await this.save(filename, prd);
1470
+ return {
1471
+ story_id: story.id,
1472
+ title: story.title,
1473
+ status: story.status,
1474
+ progress: prd.progress.overall,
1475
+ verification
1476
+ };
1477
+ }
1478
+ async exportMarkdown(input) {
1479
+ const filename = this.safeName(input.filename);
1480
+ const prd = await this.load(filename);
1481
+ const markdownFile = filename.replace(/\.json$/, ".md");
1482
+ const path = join(this.prdsDir, markdownFile);
1483
+ await this.deps.writeFile(path, formatPrdMarkdown(prd, filename));
1484
+ return {
1485
+ markdown_file: markdownFile,
1486
+ path
1487
+ };
1488
+ }
1489
+ async getImplementationPrompts(filename) {
1490
+ const name = this.safeName(filename);
1491
+ const prd = await this.load(name);
1492
+ const prompts = [];
1493
+ 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));
1494
+ return {
1495
+ prompts,
1496
+ total: prompts.length
1497
+ };
1498
+ }
1499
+ async getImprovementSuggestions(filename) {
1500
+ const suggestions = (await this.checkPlan(filename)).items.map((item) => item.message);
1501
+ return {
1502
+ suggestions,
1503
+ total: suggestions.length
1504
+ };
1505
+ }
1506
+ listTemplates() {
1507
+ return { templates: PRD_TEMPLATES.map((template) => ({
1508
+ id: template.id,
1509
+ name: template.name,
1510
+ description: template.description,
1511
+ when_to_use: template.whenToUse
1512
+ })) };
1513
+ }
1514
+ async checkPlan(filename) {
1515
+ return checkPlan(await this.load(this.safeName(filename)));
1516
+ }
1517
+ async getProjectStatus(filename) {
1518
+ const prd = await this.load(this.safeName(filename));
1519
+ const blockers = prd.userStories.filter((s) => s.status === "blocked");
1520
+ const inProgress = prd.userStories.filter((s) => s.status === "in_progress");
1521
+ const nextPending = prd.userStories.filter((s) => s.status === "not_started").slice(0, 3);
1522
+ const highRisks = prd.risks.filter((risk) => risk.severity === "high");
1523
+ return {
1524
+ progress: prd.progress.overall,
1525
+ summary: `${prd.progress.completed}/${prd.progress.total} stories completed (${prd.progress.overall}%). Open questions: ${prd.openQuestions.length}. High risks: ${highRisks.length}.`,
1526
+ next_steps: [...inProgress.map((s) => `Continue: ${s.title}`), ...nextPending.map((s) => `Start: ${s.title}`)],
1527
+ blockers: blockers.map((s) => ({
1528
+ id: s.id,
1529
+ title: s.title,
1530
+ notes: s.notes ?? null
1531
+ })),
1532
+ open_questions: prd.openQuestions.map((question) => question.question),
1533
+ high_risks: highRisks.map(({ id, description, mitigation, owner }) => ({
1534
+ id,
1535
+ description,
1536
+ mitigation,
1537
+ owner
1538
+ }))
1539
+ };
1540
+ }
1541
+ updatePrdSection(input) {
1542
+ return this.mutate(input.filename, (prd) => updatePrdSection(prd, input, this.today()), input.expectedRevision);
1543
+ }
1544
+ /** Mark a part of the PRD (not) applicable, e.g. no rollout for an internal tool. */
1545
+ markNotApplicable(input) {
1546
+ return this.mutate(input.filename, (prd) => setNotApplicable(prd, input, this.today()), input.expectedRevision);
1547
+ }
1548
+ addDecision(input) {
1549
+ return this.mutate(input.filename, (prd) => addDecision(prd, input, this.today()));
1550
+ }
1551
+ resolveOpenQuestion(input) {
1552
+ return this.mutate(input.filename, (prd) => resolveOpenQuestion(prd, input, this.today()), input.expectedRevision);
1553
+ }
1554
+ decideEdgeCase(input) {
1555
+ return this.mutate(input.filename, (prd) => decideEdgeCase(prd, input, this.today()), input.expectedRevision);
1556
+ }
1557
+ addGlossaryTerm(input) {
1558
+ return this.mutate(input.filename, (prd) => addGlossaryTerm(prd, input, this.today()));
1559
+ }
1560
+ updatePhase(input) {
1561
+ return this.mutate(input.filename, (prd) => updatePhase(prd, input, this.today()));
1562
+ }
1563
+ deletePhase(input) {
1564
+ return this.mutate(input.filename, (prd) => deletePhase(prd, input, this.today()));
1565
+ }
1566
+ reorderPhases(input) {
1567
+ return this.mutate(input.filename, (prd) => reorderPhases(prd, input, this.today()));
1568
+ }
1569
+ async getNextStory(filename) {
1570
+ return pickNextStory(await this.load(this.safeName(filename)));
1571
+ }
1572
+ async getStory(input) {
1573
+ const filename = this.safeName(input.filename);
1574
+ return buildStoryContext(await this.load(filename), input.storyId, filename);
1575
+ }
1576
+ async addStoryLog(input) {
1577
+ const filename = this.safeName(input.filename);
1578
+ const prd = await this.load(filename);
1579
+ const result = appendStoryLog(prd, input.storyId, {
1580
+ at: this.deps.now().toISOString(),
1581
+ whatsNew: input.whatsNew,
1582
+ technicalNotes: input.technicalNotes,
1583
+ ...input.deviations?.length && { deviations: input.deviations }
1584
+ });
1585
+ appendChangeLog(prd, `Logged work on ${result.story_id}`, this.today());
1586
+ await this.save(filename, prd);
1587
+ return result;
1588
+ }
1589
+ /** Files must already be in the PRD's folder, `.prds/<prd name>/`. */
1590
+ async addAttachment(input) {
1591
+ const filename = this.safeName(input.filename);
1592
+ if (input.path) {
1593
+ const folder = attachmentsFolder(filename);
1594
+ const path = assertSafeRelativePath(input.path, "attachment path");
1595
+ 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.`);
1596
+ }
1597
+ return this.mutate(filename, (prd) => addAttachment(prd, {
1598
+ ...input,
1599
+ filename
1600
+ }, this.today()), input.expectedRevision);
1601
+ }
1602
+ /** Changes an attachment's title, note or the stories that use it. */
1603
+ updateAttachment(input) {
1604
+ return this.mutate(input.filename, (prd) => updateAttachment(prd, input, this.today()), input.expectedRevision);
1605
+ }
1606
+ /** Removes the attachment from the PRD and its stories; the file stays. */
1607
+ async removeAttachment(input) {
1608
+ return this.mutate(input.filename, (prd) => removeAttachment(prd, input.attachmentId, this.today()), input.expectedRevision);
1609
+ }
1610
+ /** Load → transform → save for operations that only touch the PRD. */
1611
+ /**
1612
+ * Load, change and save a PRD. With `expectedRevision` (the revision the
1613
+ * caller's change is based on, e.g. what a person saw before editing), the
1614
+ * change is rejected when the PRD has moved on since.
1615
+ */
1616
+ async mutate(filename, transform, expectedRevision) {
1617
+ const name = this.safeName(filename);
1618
+ const prd = await this.load(name);
1619
+ const currentRevision = prd.metadata.revision ?? 0;
1620
+ if (expectedRevision !== void 0 && expectedRevision !== currentRevision) throw new PrdRevisionConflictError(name, expectedRevision, currentRevision);
1621
+ const result = transform(prd);
1622
+ await this.save(name, prd);
1623
+ return result;
1624
+ }
1625
+ /**
1626
+ * Load and normalise a PRD. The file name is validated here, at the
1627
+ * filesystem boundary, so every caller (including the dev tool) is covered.
1628
+ */
1629
+ async load(filename) {
1630
+ const name = this.safeName(filename);
1631
+ let raw;
1632
+ try {
1633
+ raw = await this.deps.readFile(join(this.prdsDir, name));
1634
+ } catch {
1635
+ throw new Error(`PRD file "${name}" not found`);
1636
+ }
1637
+ let parsed;
1638
+ try {
1639
+ parsed = JSON.parse(raw);
1640
+ } catch {
1641
+ throw new Error(`PRD file "${name}" is not valid JSON`);
1642
+ }
1643
+ return normalizePrd(parsed, this.today());
1644
+ }
1645
+ async save(filename, prd) {
1646
+ const today = this.today();
1647
+ const path = join(this.prdsDir, filename);
1648
+ const loadedRevision = prd.metadata.revision ?? 0;
1649
+ if (await this.deps.fileExists(path)) {
1650
+ const onDisk = await this.load(filename);
1651
+ if ((onDisk.metadata.revision ?? 0) !== loadedRevision) throw new PrdRevisionConflictError(filename, loadedRevision, onDisk.metadata.revision ?? 0);
1652
+ }
1653
+ prd.metadata.revision = loadedRevision + 1;
1654
+ prd.metadata.lastUpdated = today;
1655
+ prd.introduction.lastUpdated = today;
1656
+ await this.deps.writeFile(path, JSON.stringify(prd, null, 2));
1657
+ }
1658
+ async listFilenames() {
1659
+ await this.deps.mkdir(this.prdsDir);
1660
+ try {
1661
+ return (await this.deps.readdir(this.prdsDir)).filter((file) => file.endsWith(".json")).sort();
1662
+ } catch {
1663
+ return [];
1664
+ }
1665
+ }
1666
+ safeName(filename) {
1667
+ return assertSafeFileName(filename, "PRD file name");
1668
+ }
1669
+ today() {
1670
+ return this.deps.now().toISOString().slice(0, 10);
1671
+ }
1672
+ };
1673
+ function buildVerificationFailure(storyId, result) {
1674
+ const sample = result.diagnostics.slice(0, 5).map((d) => `${d.file}${d.line ? `:${d.line}` : ""} ${d.message}`).join("; ");
1675
+ const reasons = [sample ? `First diagnostics: ${sample}.` : "", ...result.messages].filter(Boolean).join(" ");
1676
+ return `Cannot mark ${storyId} as completed: verification failed (${result.errors} errors, ${result.warnings} warnings across ${result.checks.join(", ") || "no checks"}). ` + (reasons ? `${reasons} ` : "") + "Fix the issues, run the project checks, then retry.";
1677
+ }
1678
+ function isErrnoCode(error, code) {
1679
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
1680
+ }
1681
+ function normalizePrd(input, today) {
1682
+ const prd = isPlainObject(input) ? input : {};
1683
+ const openQuestions = normalizeOpenQuestions(prd.openQuestions);
1684
+ const highestQuestion = openQuestions.reduce((max, question) => Math.max(max, Number(/^Q(\d+)$/.exec(question.id)?.[1] ?? 0)), 0);
1685
+ return {
1686
+ ...prd,
1687
+ introduction: {
1688
+ title: prd.introduction?.title ?? "Untitled PRD",
1689
+ overview: prd.introduction?.overview ?? "",
1690
+ lastUpdated: prd.introduction?.lastUpdated ?? today
1691
+ },
1692
+ problemStatement: {
1693
+ problem: prd.problemStatement?.problem ?? "",
1694
+ marketOpportunity: prd.problemStatement?.marketOpportunity ?? "",
1695
+ targetUsers: prd.problemStatement?.targetUsers ?? []
1696
+ },
1697
+ solutionOverview: {
1698
+ description: prd.solutionOverview?.description ?? "",
1699
+ keyFeatures: prd.solutionOverview?.keyFeatures ?? [],
1700
+ successMetrics: prd.solutionOverview?.successMetrics ?? []
1701
+ },
1702
+ nonGoals: prd.nonGoals ?? [],
1703
+ outOfScope: prd.outOfScope ?? [],
1704
+ assumptions: prd.assumptions ?? [],
1705
+ openQuestions,
1706
+ risks: prd.risks ?? [],
1707
+ dependencies: prd.dependencies ?? [],
1708
+ userStories: prd.userStories ?? [],
1709
+ customPhases: prd.customPhases ?? [],
1710
+ storyTraceability: prd.storyTraceability ?? [],
1711
+ technicalRequirements: {
1712
+ constraints: prd.technicalRequirements?.constraints ?? [],
1713
+ integrationNeeds: prd.technicalRequirements?.integrationNeeds ?? [],
1714
+ complianceRequirements: prd.technicalRequirements?.complianceRequirements ?? []
1715
+ },
1716
+ technicalContracts: {
1717
+ apis: prd.technicalContracts?.apis ?? [],
1718
+ dataModels: prd.technicalContracts?.dataModels ?? [],
1719
+ permissions: prd.technicalContracts?.permissions ?? [],
1720
+ integrationBoundaries: prd.technicalContracts?.integrationBoundaries ?? []
1721
+ },
1722
+ acceptanceCriteria: {
1723
+ global: prd.acceptanceCriteria?.global ?? [],
1724
+ qualityStandards: prd.acceptanceCriteria?.qualityStandards ?? []
1725
+ },
1726
+ constraints: {
1727
+ timeline: prd.constraints?.timeline ?? "",
1728
+ budget: prd.constraints?.budget,
1729
+ resources: prd.constraints?.resources ?? [],
1730
+ nonNegotiables: prd.constraints?.nonNegotiables ?? []
1731
+ },
1732
+ rolloutPlan: {
1733
+ featureFlags: prd.rolloutPlan?.featureFlags ?? [],
1734
+ migrationPlan: prd.rolloutPlan?.migrationPlan ?? [],
1735
+ rolloutPhases: prd.rolloutPlan?.rolloutPhases ?? [],
1736
+ rollbackConditions: prd.rolloutPlan?.rollbackConditions ?? []
1737
+ },
1738
+ measurementPlan: {
1739
+ events: prd.measurementPlan?.events ?? [],
1740
+ dashboards: prd.measurementPlan?.dashboards ?? [],
1741
+ baselineMetrics: prd.measurementPlan?.baselineMetrics ?? [],
1742
+ targetMetrics: prd.measurementPlan?.targetMetrics ?? [],
1743
+ guardrailMetrics: prd.measurementPlan?.guardrailMetrics ?? []
1744
+ },
1745
+ edgeCases: normalizeEdgeCases(prd.edgeCases),
1746
+ securityConsiderations: Array.isArray(prd.securityConsiderations) ? prd.securityConsiderations.filter((item) => typeof item === "string") : [],
1747
+ notApplicable: normalizeNotApplicable(prd.notApplicable),
1748
+ designGuidance: Array.isArray(prd.designGuidance) ? prd.designGuidance.filter((item) => typeof item === "string") : [],
1749
+ decisionLog: prd.decisionLog ?? [],
1750
+ glossary: prd.glossary ?? [],
1751
+ attachments: normalizeAttachments(prd.attachments),
1752
+ agentTaskPackets: prd.agentTaskPackets ?? [],
1753
+ changeLog: prd.changeLog ?? [],
1754
+ metadata: {
1755
+ version: prd.metadata?.version ?? "2.0",
1756
+ created: prd.metadata?.created ?? today,
1757
+ lastUpdated: prd.metadata?.lastUpdated ?? today,
1758
+ lastValidatedAt: prd.metadata?.lastValidatedAt ?? today,
1759
+ approver: prd.metadata?.approver ?? "",
1760
+ lastStoryNumber: prd.metadata?.lastStoryNumber,
1761
+ lastAttachmentNumber: prd.metadata?.lastAttachmentNumber,
1762
+ lastQuestionNumber: Math.max(prd.metadata?.lastQuestionNumber ?? 0, highestQuestion) || void 0,
1763
+ revision: prd.metadata?.revision
1764
+ },
1765
+ progress: {
1766
+ overall: prd.progress?.overall ?? 0,
1767
+ completed: prd.progress?.completed ?? 0,
1768
+ total: prd.progress?.total ?? 0,
1769
+ blocked: prd.progress?.blocked ?? 0
1770
+ }
1771
+ };
1772
+ }
1773
+ function isPlainObject(value) {
1774
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1775
+ }
1776
+ function slugify(value) {
1777
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "untitled-prd";
1778
+ }
1779
+ function titleFromAction(action) {
1780
+ return action.trim().toLowerCase().split(/\s+/).slice(0, 4).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1781
+ }
1782
+ function assessComplexity(criteria) {
1783
+ const count = criteria.length;
1784
+ if (count <= 2) return "XS";
1785
+ if (count <= 3) return "S";
1786
+ if (count <= 5) return "M";
1787
+ if (count <= 8) return "L";
1788
+ return "XL";
1789
+ }
1790
+ //#endregion
1791
+ 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, 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 };