@makerkit/prd 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.turbo/turbo-build.log +78 -0
  2. package/.turbo/turbo-test.log +19 -0
  3. package/.turbo/turbo-typecheck.log +6 -0
  4. package/README.md +7 -1
  5. package/dist/README.md +71 -0
  6. package/dist/attachment-paths-BAhRGiib.js +112 -0
  7. package/dist/attachment-paths-C-SWgoSx.mjs +77 -0
  8. package/dist/index.d.ts +81 -0
  9. package/{index.js → dist/index.js} +155 -562
  10. package/{index.mjs → dist/index.mjs} +87 -497
  11. package/{mcp.d.ts → dist/mcp.d.ts} +2 -4
  12. package/{mcp.js → dist/mcp.js} +24 -24
  13. package/{mcp.mjs → dist/mcp.mjs} +24 -24
  14. package/{node.d.ts → dist/node.d.ts} +4 -4
  15. package/{node.js → dist/node.js} +28 -4
  16. package/{node.mjs → dist/node.mjs} +30 -6
  17. package/dist/operations.d.ts +141 -0
  18. package/dist/operations.js +22 -0
  19. package/dist/operations.mjs +1 -0
  20. package/dist/package.json +54 -0
  21. package/dist/prd-operations-BvFxo9bg.mjs +459 -0
  22. package/dist/prd-operations-CcahfbOy.js +584 -0
  23. package/dist/prd.service-CTwKZV-3.d.ts +114 -0
  24. package/{prompts-oI_6dxvx.js → dist/prompts-1qhax_dj.js} +113 -164
  25. package/{prompts-CPlFVutB.mjs → dist/prompts-BlsYD0gf.mjs} +96 -129
  26. package/{prd.service-CV0-aQHk.d.ts → dist/schema-BwTnt0B9.d.ts} +424 -336
  27. package/package.json +26 -2
  28. package/src/__tests__/agent-workflow.test.ts +417 -0
  29. package/src/__tests__/attachments.test.ts +505 -0
  30. package/src/__tests__/node.test.ts +199 -0
  31. package/src/__tests__/plan-check.test.ts +390 -0
  32. package/src/__tests__/planning.test.ts +1137 -0
  33. package/src/__tests__/prd-operations.test.ts +571 -0
  34. package/src/__tests__/prd.service.test.ts +652 -0
  35. package/src/__tests__/prd.tool.test.ts +282 -0
  36. package/src/__tests__/templates.test.ts +145 -0
  37. package/src/applicability.ts +73 -0
  38. package/src/attachment-paths.ts +83 -0
  39. package/src/attachments.ts +166 -0
  40. package/src/edge-cases.ts +61 -0
  41. package/src/index.ts +33 -0
  42. package/src/markdown.ts +297 -0
  43. package/src/mcp/index.ts +875 -0
  44. package/src/mcp/tool-response.ts +85 -0
  45. package/src/node.ts +184 -0
  46. package/src/open-questions.ts +98 -0
  47. package/src/plan-check.ts +385 -0
  48. package/src/planning-operations.ts +524 -0
  49. package/src/prd-operations.ts +769 -0
  50. package/src/prd.service.ts +1165 -0
  51. package/src/prompts.ts +161 -0
  52. package/src/safe-file-name.ts +42 -0
  53. package/src/schema.ts +1090 -0
  54. package/src/templates.ts +173 -0
  55. package/src/testing/fake-mcp-server.ts +81 -0
  56. package/src/types.ts +381 -0
  57. package/tsconfig.json +23 -0
  58. package/tsconfig.lib.json +8 -0
  59. package/tsconfig.spec.json +7 -0
  60. package/tsdown.config.mts +12 -0
  61. package/vitest.config.mts +8 -0
  62. package/index.d.ts +0 -233
  63. /package/{LICENSE → dist/LICENSE} +0 -0
@@ -0,0 +1,524 @@
1
+ import { nextQuestionId } from './open-questions';
2
+ import { appendChangeLog, nextId } from './prd-operations';
3
+ import {
4
+ type AddDecisionInput,
5
+ type AddDecisionOutput,
6
+ type AddGlossaryTermInput,
7
+ type AddGlossaryTermOutput,
8
+ type DeletePhaseInput,
9
+ type PhasesOutput,
10
+ PrdSectionValueSchemas,
11
+ type ReorderPhasesInput,
12
+ type DecideEdgeCaseInput,
13
+ type DecideEdgeCaseOutput,
14
+ type ResolveOpenQuestionInput,
15
+ type ResolveOpenQuestionOutput,
16
+ type UpdatePhaseInput,
17
+ type UpdatePrdSectionInput,
18
+ type UpdatePrdSectionOutput,
19
+ } from './schema';
20
+ import type {
21
+ CustomPhase,
22
+ OpenQuestion,
23
+ StructuredPRD,
24
+ UserStory,
25
+ } from './types';
26
+
27
+ /**
28
+ * Pure transforms for shaping a PRD after it was created: sections, decisions,
29
+ * open questions, glossary and phases. Same contract as `prd-operations`:
30
+ * mutate the loaded PRD, return the tool payload.
31
+ */
32
+
33
+ /** Sections whose value replaces the whole list. */
34
+ const LIST_SECTIONS = new Set([
35
+ 'nonGoals',
36
+ 'outOfScope',
37
+ 'assumptions',
38
+ 'designGuidance',
39
+ 'securityConsiderations',
40
+ ]);
41
+
42
+ export function updatePrdSection(
43
+ prd: StructuredPRD,
44
+ input: UpdatePrdSectionInput,
45
+ today: string,
46
+ ): UpdatePrdSectionOutput {
47
+ const parsed = PrdSectionValueSchemas[input.section].safeParse(input.value);
48
+
49
+ if (!parsed.success) {
50
+ const issues = parsed.error.issues
51
+ .map((issue) => `${issue.path.join('.') || 'value'}: ${issue.message}`)
52
+ .join('; ');
53
+
54
+ throw new Error(`Invalid value for section "${input.section}": ${issues}`);
55
+ }
56
+
57
+ const value = parsed.data;
58
+ let updated: string[];
59
+
60
+ if (input.section === 'roadmap') {
61
+ const patch =
62
+ value as (typeof PrdSectionValueSchemas)['roadmap']['_output'];
63
+ const merged = Object.fromEntries(
64
+ Object.entries({ ...prd.roadmap, ...patch }).filter(
65
+ ([key, value]) => !(Object.hasOwn(patch, key) && value == null),
66
+ ),
67
+ );
68
+
69
+ if (Object.keys(merged).length > 0) {
70
+ prd.roadmap = merged;
71
+ } else {
72
+ delete prd.roadmap;
73
+ }
74
+ updated = Object.keys(patch);
75
+ } else if (input.section === 'risks') {
76
+ const risks = value as (typeof PrdSectionValueSchemas)['risks']['_output'];
77
+ const assigned: StructuredPRD['risks'] = [];
78
+
79
+ for (const risk of risks) {
80
+ assigned.push({ ...risk, id: risk.id ?? nextId(assigned, 'RISK') });
81
+ }
82
+
83
+ prd.risks = assigned;
84
+ updated = assigned.map((risk) => risk.id);
85
+ } else if (input.section === 'dependencies') {
86
+ const items =
87
+ value as (typeof PrdSectionValueSchemas)['dependencies']['_output'];
88
+ const assigned: StructuredPRD['dependencies'] = [];
89
+
90
+ for (const item of items) {
91
+ assigned.push({ ...item, id: item.id ?? nextId(assigned, 'DEP') });
92
+ }
93
+
94
+ prd.dependencies = assigned;
95
+ updated = assigned.map((item) => item.id);
96
+ } else if (input.section === 'openQuestions') {
97
+ const items =
98
+ value as (typeof PrdSectionValueSchemas)['openQuestions']['_output'];
99
+ const storyIds = new Set(prd.userStories.map((story) => story.id));
100
+ const unknown = items
101
+ .flatMap((item) =>
102
+ typeof item === 'string' ? [] : (item.storyIds ?? []),
103
+ )
104
+ .filter((id) => !storyIds.has(id));
105
+
106
+ if (unknown.length > 0) {
107
+ throw new Error(
108
+ `Invalid value for section "openQuestions": unknown stories ${[...new Set(unknown)].join(', ')}`,
109
+ );
110
+ }
111
+
112
+ const assigned: StructuredPRD['openQuestions'] = [];
113
+
114
+ for (const item of items) {
115
+ const question = typeof item === 'string' ? { question: item } : item;
116
+ const {
117
+ id,
118
+ storyIds: linked,
119
+ options,
120
+ ...rest
121
+ } = question as typeof question & {
122
+ id?: string;
123
+ storyIds?: string[];
124
+ options?: string[];
125
+ };
126
+
127
+ assigned.push({
128
+ ...rest,
129
+ id: id ?? nextQuestionId(prd, assigned),
130
+ ...(options?.length ? { options } : {}),
131
+ ...(linked?.length ? { storyIds: linked } : {}),
132
+ });
133
+ }
134
+
135
+ prd.openQuestions = assigned;
136
+ updated = assigned.map((item) => item.id);
137
+ } else if (input.section === 'edgeCases') {
138
+ const items =
139
+ value as (typeof PrdSectionValueSchemas)['edgeCases']['_output'];
140
+ const storyIds = new Set(prd.userStories.map((story) => story.id));
141
+ const unknown = items
142
+ .flatMap((item) => item.storyIds ?? [])
143
+ .filter((id) => !storyIds.has(id));
144
+
145
+ if (unknown.length > 0) {
146
+ throw new Error(
147
+ `Invalid value for section "edgeCases": unknown stories ${[...new Set(unknown)].join(', ')}`,
148
+ );
149
+ }
150
+
151
+ const assigned: StructuredPRD['edgeCases'] = [];
152
+
153
+ for (const item of items) {
154
+ const { storyIds: linked, ...rest } = item;
155
+
156
+ assigned.push({
157
+ ...rest,
158
+ id: item.id ?? nextId([...prd.edgeCases, ...assigned], 'EC'),
159
+ ...(linked?.length ? { storyIds: linked } : {}),
160
+ });
161
+ }
162
+
163
+ prd.edgeCases = assigned;
164
+ updated = assigned.map((item) => item.id);
165
+ } else if (LIST_SECTIONS.has(input.section)) {
166
+ const key = input.section as
167
+ | 'nonGoals'
168
+ | 'outOfScope'
169
+ | 'assumptions'
170
+ | 'designGuidance'
171
+ | 'securityConsiderations';
172
+
173
+ prd[key] = value as string[];
174
+ updated = [key];
175
+ } else {
176
+ const key = input.section as Exclude<
177
+ keyof typeof PrdSectionValueSchemas,
178
+ | 'roadmap'
179
+ | 'risks'
180
+ | 'dependencies'
181
+ | 'edgeCases'
182
+ | 'openQuestions'
183
+ | 'nonGoals'
184
+ | 'outOfScope'
185
+ | 'assumptions'
186
+ | 'designGuidance'
187
+ | 'securityConsiderations'
188
+ >;
189
+
190
+ Object.assign(prd[key], value);
191
+ updated = Object.keys(value as object);
192
+ }
193
+
194
+ appendChangeLog(prd, `Updated ${input.section}`, today);
195
+
196
+ return { section: input.section, updated };
197
+ }
198
+
199
+ export function addDecision(
200
+ prd: StructuredPRD,
201
+ input: AddDecisionInput,
202
+ today: string,
203
+ ): AddDecisionOutput {
204
+ let superseded: string | null = null;
205
+
206
+ if (input.supersedes) {
207
+ const previous = prd.decisionLog.find(
208
+ (entry) => entry.id === input.supersedes,
209
+ );
210
+
211
+ if (!previous) {
212
+ throw new Error(`Decision "${input.supersedes}" not found.`);
213
+ }
214
+
215
+ previous.status = 'superseded';
216
+ superseded = previous.id;
217
+ }
218
+
219
+ const id = nextId(prd.decisionLog, 'DEC');
220
+
221
+ prd.decisionLog.push({
222
+ id,
223
+ date: today,
224
+ decision: input.decision,
225
+ rationale: input.rationale,
226
+ status: input.status,
227
+ ...(input.owner ? { owner: input.owner } : {}),
228
+ ...(input.topic ? { topic: input.topic } : {}),
229
+ });
230
+
231
+ appendChangeLog(
232
+ prd,
233
+ superseded ? `Recorded ${id} (supersedes ${superseded})` : `Recorded ${id}`,
234
+ today,
235
+ );
236
+
237
+ return {
238
+ decision_id: id,
239
+ superseded,
240
+ total_decisions: prd.decisionLog.length,
241
+ };
242
+ }
243
+
244
+ /**
245
+ * The decision topic for a story's accepted deviations. Deleting the story
246
+ * supersedes them with its other decisions.
247
+ */
248
+ export function deviationTopic(storyId: string) {
249
+ return `story:${storyId}:deviation`;
250
+ }
251
+
252
+ /**
253
+ * Deviations the reviewer accepted become decisions, so the PRD describes
254
+ * what was built rather than only what was planned. Each must be one the
255
+ * story logged; one already recorded is not recorded twice.
256
+ */
257
+ export function assertLoggedDeviations(story: UserStory, deviations: string[]) {
258
+ const logged = (story.log ?? []).flatMap((entry) => entry.deviations ?? []);
259
+
260
+ for (const deviation of deviations) {
261
+ if (!logged.includes(deviation)) {
262
+ throw new Error(
263
+ `${story.id} did not log the deviation "${deviation}". Copy it exactly from the story log.`,
264
+ );
265
+ }
266
+ }
267
+ }
268
+
269
+ export function recordDeviations(
270
+ prd: StructuredPRD,
271
+ story: UserStory,
272
+ deviations: string[],
273
+ today: string,
274
+ ) {
275
+ assertLoggedDeviations(story, deviations);
276
+
277
+ const topic = deviationTopic(story.id);
278
+ const recorded = new Set(
279
+ prd.decisionLog
280
+ .filter((entry) => entry.topic === topic && entry.status === 'accepted')
281
+ .map((entry) => entry.decision),
282
+ );
283
+
284
+ return [...new Set(deviations)]
285
+ .filter((deviation) => !recorded.has(deviation))
286
+ .map(
287
+ (deviation) =>
288
+ addDecision(
289
+ prd,
290
+ {
291
+ filename: '',
292
+ decision: deviation,
293
+ rationale: `Departed from the plan while building ${story.id} (${story.title}); accepted at review.`,
294
+ topic,
295
+ status: 'accepted',
296
+ },
297
+ today,
298
+ ).decision_id,
299
+ );
300
+ }
301
+
302
+ export function resolveOpenQuestion(
303
+ prd: StructuredPRD,
304
+ input: ResolveOpenQuestionInput,
305
+ today: string,
306
+ ): ResolveOpenQuestionOutput {
307
+ const wanted = input.question ? normalizeText(input.question) : null;
308
+ const index = prd.openQuestions.findIndex((question) =>
309
+ input.questionId
310
+ ? question.id === input.questionId
311
+ : normalizeText(question.question) === wanted,
312
+ );
313
+
314
+ if (index === -1) {
315
+ throw new Error(
316
+ `Open question not found: "${input.questionId ?? input.question}". ` +
317
+ (prd.openQuestions.length
318
+ ? `Open questions: ${prd.openQuestions.map((q) => `${q.id} "${q.question}"`).join(', ')}.`
319
+ : 'This PRD has no open questions.'),
320
+ );
321
+ }
322
+
323
+ const [question] = prd.openQuestions.splice(index, 1) as [OpenQuestion];
324
+
325
+ let decisionId: string | null = null;
326
+
327
+ if (input.recordDecision) {
328
+ decisionId = addDecision(
329
+ prd,
330
+ {
331
+ filename: input.filename,
332
+ decision: input.answer,
333
+ rationale:
334
+ `Answers ${question.id}: ${question.question}` +
335
+ (question.why ? ` (${question.why})` : ''),
336
+ topic: `open-question:${question.id}`,
337
+ status: 'accepted',
338
+ },
339
+ today,
340
+ ).decision_id;
341
+ } else {
342
+ appendChangeLog(
343
+ prd,
344
+ `Resolved ${question.id}: ${question.question}`,
345
+ today,
346
+ );
347
+ }
348
+
349
+ return {
350
+ remaining_questions: prd.openQuestions.length,
351
+ decision_id: decisionId,
352
+ };
353
+ }
354
+
355
+ /** Answer an open edge case: it becomes decided with the given behaviour. */
356
+ export function decideEdgeCase(
357
+ prd: StructuredPRD,
358
+ input: DecideEdgeCaseInput,
359
+ today: string,
360
+ ): DecideEdgeCaseOutput {
361
+ const edgeCase = prd.edgeCases.find(
362
+ (candidate) => candidate.id === input.edgeCaseId,
363
+ );
364
+
365
+ if (!edgeCase) {
366
+ throw new Error(`Edge case "${input.edgeCaseId}" not found.`);
367
+ }
368
+
369
+ edgeCase.expectedBehavior = input.expectedBehavior.trim();
370
+ edgeCase.status = 'decided';
371
+ appendChangeLog(prd, `Decided ${edgeCase.id}: ${edgeCase.case}`, today);
372
+
373
+ return {
374
+ edge_case_id: edgeCase.id,
375
+ open_edge_cases: prd.edgeCases.filter(
376
+ (candidate) => candidate.status === 'open',
377
+ ).length,
378
+ };
379
+ }
380
+
381
+ /** Adds a term, or replaces the definition of an existing one (any casing). */
382
+ export function addGlossaryTerm(
383
+ prd: StructuredPRD,
384
+ input: AddGlossaryTermInput,
385
+ today: string,
386
+ ): AddGlossaryTermOutput {
387
+ const term = input.term.trim();
388
+ const existing = prd.glossary.find(
389
+ (entry) => entry.term.toLowerCase() === term.toLowerCase(),
390
+ );
391
+
392
+ if (existing) {
393
+ existing.term = term;
394
+ existing.definition = input.definition;
395
+ existing.avoid = input.avoid;
396
+ } else {
397
+ prd.glossary.push({
398
+ term,
399
+ definition: input.definition,
400
+ avoid: input.avoid,
401
+ });
402
+ }
403
+
404
+ appendChangeLog(
405
+ prd,
406
+ `${existing ? 'Redefined' : 'Defined'} glossary term "${term}"`,
407
+ today,
408
+ );
409
+
410
+ return {
411
+ term,
412
+ replaced: Boolean(existing),
413
+ total_terms: prd.glossary.length,
414
+ };
415
+ }
416
+
417
+ export function updatePhase(
418
+ prd: StructuredPRD,
419
+ input: UpdatePhaseInput,
420
+ today: string,
421
+ ): PhasesOutput {
422
+ const phase = findPhase(prd, input.phaseId);
423
+
424
+ if (input.name !== undefined) {
425
+ const name = input.name.trim();
426
+ const clash = prd.customPhases.some(
427
+ (other) =>
428
+ other.id !== phase.id &&
429
+ other.name.toLowerCase() === name.toLowerCase(),
430
+ );
431
+
432
+ if (clash) {
433
+ throw new Error(`A phase named "${name}" already exists.`);
434
+ }
435
+
436
+ phase.name = name;
437
+ }
438
+
439
+ if (input.description !== undefined) phase.description = input.description;
440
+ if (input.color !== undefined) phase.color = input.color;
441
+
442
+ appendChangeLog(prd, `Updated phase ${phase.id}`, today);
443
+
444
+ return phasesPayload(prd);
445
+ }
446
+
447
+ /** Deletes a phase; its stories stay in the PRD without a phase. */
448
+ export function deletePhase(
449
+ prd: StructuredPRD,
450
+ input: DeletePhaseInput,
451
+ today: string,
452
+ ): PhasesOutput {
453
+ const phase = findPhase(prd, input.phaseId);
454
+
455
+ prd.customPhases = prd.customPhases.filter((other) => other.id !== phase.id);
456
+ renumberPhases(prd.customPhases);
457
+
458
+ appendChangeLog(prd, `Deleted phase ${phase.id} (${phase.name})`, today);
459
+
460
+ return phasesPayload(prd);
461
+ }
462
+
463
+ export function reorderPhases(
464
+ prd: StructuredPRD,
465
+ input: ReorderPhasesInput,
466
+ today: string,
467
+ ): PhasesOutput {
468
+ const known = prd.customPhases.map((phase) => phase.id).sort();
469
+ const given = [...input.phaseIds].sort();
470
+
471
+ if (
472
+ known.length !== given.length ||
473
+ known.some((id, index) => id !== given[index])
474
+ ) {
475
+ throw new Error(
476
+ `phaseIds must list every phase exactly once. Phases: ${known.join(', ') || 'none'}.`,
477
+ );
478
+ }
479
+
480
+ prd.customPhases = input.phaseIds.map((id) => findPhase(prd, id));
481
+ renumberPhases(prd.customPhases);
482
+
483
+ appendChangeLog(prd, `Reordered phases: ${input.phaseIds.join(', ')}`, today);
484
+
485
+ return phasesPayload(prd);
486
+ }
487
+
488
+ function findPhase(prd: StructuredPRD, phaseId: string): CustomPhase {
489
+ const phase = prd.customPhases.find((candidate) => candidate.id === phaseId);
490
+
491
+ if (!phase) {
492
+ const known = prd.customPhases.map((candidate) => candidate.id).join(', ');
493
+
494
+ throw new Error(
495
+ `Phase "${phaseId}" not found.` +
496
+ (known ? ` Known phases: ${known}.` : ' This PRD has no phases yet.'),
497
+ );
498
+ }
499
+
500
+ return phase;
501
+ }
502
+
503
+ function renumberPhases(phases: CustomPhase[]) {
504
+ phases.forEach((phase, index) => {
505
+ phase.order = index;
506
+ });
507
+ }
508
+
509
+ function phasesPayload(prd: StructuredPRD): PhasesOutput {
510
+ return {
511
+ phases: [...prd.customPhases]
512
+ .sort((a, b) => a.order - b.order)
513
+ .map((phase) => ({
514
+ id: phase.id,
515
+ name: phase.name,
516
+ order: phase.order,
517
+ user_story_ids: phase.userStoryIds,
518
+ })),
519
+ };
520
+ }
521
+
522
+ function normalizeText(value: string) {
523
+ return value.trim().replace(/\s+/g, ' ').toLowerCase();
524
+ }