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