@makerkit/prd 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.turbo/turbo-build.log +78 -0
  2. package/.turbo/turbo-test.log +19 -0
  3. package/.turbo/turbo-typecheck.log +6 -0
  4. package/README.md +7 -1
  5. package/dist/README.md +71 -0
  6. package/dist/attachment-paths-BAhRGiib.js +112 -0
  7. package/dist/attachment-paths-C-SWgoSx.mjs +77 -0
  8. package/dist/index.d.ts +81 -0
  9. package/{index.js → dist/index.js} +257 -524
  10. package/{index.mjs → dist/index.mjs} +189 -462
  11. package/{mcp.d.ts → dist/mcp.d.ts} +2 -4
  12. package/{mcp.js → dist/mcp.js} +24 -24
  13. package/{mcp.mjs → dist/mcp.mjs} +24 -24
  14. package/{node.d.ts → dist/node.d.ts} +4 -4
  15. package/{node.js → dist/node.js} +28 -4
  16. package/{node.mjs → dist/node.mjs} +30 -6
  17. package/dist/operations.d.ts +141 -0
  18. package/dist/operations.js +22 -0
  19. package/dist/operations.mjs +1 -0
  20. package/dist/package.json +54 -0
  21. package/dist/prd-operations-BvFxo9bg.mjs +459 -0
  22. package/dist/prd-operations-CcahfbOy.js +584 -0
  23. package/dist/prd.service-CTwKZV-3.d.ts +114 -0
  24. package/{prompts-DJQ4FQ11.js → dist/prompts-1qhax_dj.js} +150 -167
  25. package/{prompts-B0VejF7q.mjs → dist/prompts-BlsYD0gf.mjs} +121 -132
  26. package/{prd.service-x5EpOoMv.d.ts → dist/schema-BwTnt0B9.d.ts} +545 -323
  27. package/package.json +26 -2
  28. package/src/__tests__/agent-workflow.test.ts +417 -0
  29. package/src/__tests__/attachments.test.ts +505 -0
  30. package/src/__tests__/node.test.ts +199 -0
  31. package/src/__tests__/plan-check.test.ts +390 -0
  32. package/src/__tests__/planning.test.ts +1137 -0
  33. package/src/__tests__/prd-operations.test.ts +571 -0
  34. package/src/__tests__/prd.service.test.ts +652 -0
  35. package/src/__tests__/prd.tool.test.ts +282 -0
  36. package/src/__tests__/templates.test.ts +145 -0
  37. package/src/applicability.ts +73 -0
  38. package/src/attachment-paths.ts +83 -0
  39. package/src/attachments.ts +166 -0
  40. package/src/edge-cases.ts +61 -0
  41. package/src/index.ts +33 -0
  42. package/src/markdown.ts +297 -0
  43. package/src/mcp/index.ts +875 -0
  44. package/src/mcp/tool-response.ts +85 -0
  45. package/src/node.ts +184 -0
  46. package/src/open-questions.ts +98 -0
  47. package/src/plan-check.ts +385 -0
  48. package/src/planning-operations.ts +524 -0
  49. package/src/prd-operations.ts +769 -0
  50. package/src/prd.service.ts +1165 -0
  51. package/src/prompts.ts +161 -0
  52. package/src/safe-file-name.ts +42 -0
  53. package/src/schema.ts +1090 -0
  54. package/src/templates.ts +173 -0
  55. package/src/testing/fake-mcp-server.ts +81 -0
  56. package/src/types.ts +381 -0
  57. package/tsconfig.json +23 -0
  58. package/tsconfig.lib.json +8 -0
  59. package/tsconfig.spec.json +7 -0
  60. package/tsdown.config.mts +12 -0
  61. package/vitest.config.mts +8 -0
  62. package/index.d.ts +0 -228
  63. /package/{LICENSE → dist/LICENSE} +0 -0
@@ -0,0 +1,85 @@
1
+ import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
2
+
3
+ type TextContent = {
4
+ type: 'text';
5
+ text: string;
6
+ };
7
+
8
+ /**
9
+ * Standard annotation presets. Every registered tool must declare one so MCP
10
+ * clients can gate permissions correctly (e.g. auto-approve read-only tools,
11
+ * always confirm destructive ones).
12
+ */
13
+ export const READ_ONLY_TOOL: ToolAnnotations = {
14
+ readOnlyHint: true,
15
+ destructiveHint: false,
16
+ idempotentHint: true,
17
+ openWorldHint: false,
18
+ };
19
+
20
+ /** Writes files or state but can be re-applied safely and is reversible. */
21
+ export const MUTATING_TOOL: ToolAnnotations = {
22
+ readOnlyHint: false,
23
+ destructiveHint: false,
24
+ idempotentHint: false,
25
+ openWorldHint: false,
26
+ };
27
+
28
+ /** Same as MUTATING_TOOL but repeating the call has no further effect. */
29
+ export const IDEMPOTENT_MUTATING_TOOL: ToolAnnotations = {
30
+ readOnlyHint: false,
31
+ destructiveHint: false,
32
+ idempotentHint: true,
33
+ openWorldHint: false,
34
+ };
35
+
36
+ /** Deletes or irreversibly replaces data. Clients should always confirm. */
37
+ export const DESTRUCTIVE_TOOL: ToolAnnotations = {
38
+ readOnlyHint: false,
39
+ destructiveHint: true,
40
+ idempotentHint: false,
41
+ openWorldHint: false,
42
+ };
43
+
44
+ /** Read-only but reaches the network (e.g. registry lookups). */
45
+ export const READ_ONLY_OPEN_WORLD_TOOL: ToolAnnotations = {
46
+ readOnlyHint: true,
47
+ destructiveHint: false,
48
+ idempotentHint: true,
49
+ openWorldHint: true,
50
+ };
51
+
52
+ export function buildStructuredResponse<T extends Record<string, unknown>>(
53
+ result: T,
54
+ ) {
55
+ return {
56
+ structuredContent: result,
57
+ content: buildTextContent(JSON.stringify(result)),
58
+ };
59
+ }
60
+
61
+ export function buildErrorResponse(tool: string, error: unknown) {
62
+ const message = `${tool} failed: ${toErrorMessage(error)}`;
63
+
64
+ return {
65
+ isError: true as const,
66
+ structuredContent: {
67
+ error: {
68
+ message,
69
+ },
70
+ },
71
+ content: buildTextContent(message),
72
+ };
73
+ }
74
+
75
+ export function toErrorMessage(error: unknown) {
76
+ if (error instanceof Error) {
77
+ return error.message;
78
+ }
79
+
80
+ return 'Unknown error';
81
+ }
82
+
83
+ export function buildTextContent(text: string): TextContent[] {
84
+ return [{ type: 'text', text }];
85
+ }
package/src/node.ts ADDED
@@ -0,0 +1,184 @@
1
+ import { createRepoChecksServices } from '@makerkit/repo-checks/node';
2
+
3
+ import type { PrdDeps, PrdVerificationResult } from './prd.service';
4
+
5
+ import { randomUUID } from 'node:crypto';
6
+ import {
7
+ access,
8
+ mkdir,
9
+ readFile,
10
+ readdir,
11
+ rename,
12
+ rm,
13
+ rmdir,
14
+ unlink,
15
+ writeFile,
16
+ } from 'node:fs/promises';
17
+ import { join, resolve } from 'node:path';
18
+
19
+ /** Check-only scripts that gate marking a story as completed. */
20
+ const DEFAULT_COMPLETION_CHECKS = ['typecheck', 'lint'];
21
+
22
+ /** Output kept from a failing script, so the reason fits in a tool response. */
23
+ const MAX_FAILURE_DETAIL = 300;
24
+
25
+ export interface NodePrdDepsOptions {
26
+ /** Absolute directory or a path relative to the project root. */
27
+ prdsDir?: string;
28
+ /**
29
+ * Decides whether a story may be marked completed. Defaults to running the
30
+ * project's `typecheck` and `lint` scripts (see `createScriptVerifier`).
31
+ */
32
+ verifyCompletion?: PrdDeps['verifyCompletion'];
33
+ }
34
+
35
+ /** PRD dependencies backed by the local filesystem, rooted at `rootPath`. */
36
+ export function createNodePrdDeps(
37
+ rootPath = process.cwd(),
38
+ options: NodePrdDepsOptions = {},
39
+ ): PrdDeps {
40
+ return {
41
+ rootPath,
42
+ prdsDir: options.prdsDir ? resolve(rootPath, options.prdsDir) : undefined,
43
+ readdir(path) {
44
+ return readdir(path);
45
+ },
46
+ readFile(path) {
47
+ return readFile(path, 'utf8');
48
+ },
49
+ async writeFile(path, content) {
50
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
51
+
52
+ try {
53
+ await writeFile(temporaryPath, content, {
54
+ encoding: 'utf8',
55
+ flag: 'wx',
56
+ });
57
+ await rename(temporaryPath, path);
58
+ } finally {
59
+ await rm(temporaryPath, { force: true });
60
+ }
61
+ },
62
+ async mkdir(path) {
63
+ await mkdir(path, { recursive: true });
64
+ },
65
+ unlink(path) {
66
+ return unlink(path);
67
+ },
68
+ fileExists,
69
+ async withWriteLock(path, write) {
70
+ const lockPath = `${path}.lock`;
71
+
72
+ try {
73
+ await mkdir(lockPath);
74
+ } catch (error) {
75
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
76
+ throw new Error(
77
+ `PRD write lock is held at "${lockPath}". Reload the PRD and retry. If a writer crashed, verify that no writer is active before removing the lock directory.`,
78
+ );
79
+ }
80
+
81
+ throw error;
82
+ }
83
+
84
+ try {
85
+ return await write();
86
+ } finally {
87
+ await rmdir(lockPath);
88
+ }
89
+ },
90
+ now() {
91
+ return new Date();
92
+ },
93
+ verifyCompletion:
94
+ options.verifyCompletion ?? createScriptVerifier(rootPath),
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Verifies completion by running the project's package.json scripts with its
100
+ * package manager (via @makerkit/repo-checks), so a failure comes back as
101
+ * file-and-line diagnostics. Scripts the project does not define are skipped,
102
+ * so a repo without e.g. `lint` can still complete stories.
103
+ */
104
+ export function createScriptVerifier(
105
+ rootPath: string,
106
+ scripts: string[] = DEFAULT_COMPLETION_CHECKS,
107
+ ): PrdDeps['verifyCompletion'] {
108
+ return async () => {
109
+ // A project can be just a folder with .prds: nothing to check then
110
+ if (!(await fileExists(join(rootPath, 'package.json')))) {
111
+ return {
112
+ passed: true,
113
+ checks: [],
114
+ errors: 0,
115
+ warnings: 0,
116
+ diagnostics: [],
117
+ messages: ['No package.json: there are no project checks to run.'],
118
+ } satisfies PrdVerificationResult;
119
+ }
120
+
121
+ const checks = createRepoChecksServices(rootPath);
122
+ const { scripts: available } = await checks.scripts.list();
123
+ const defined = new Set(available.map((script) => script.name));
124
+
125
+ const toRun = scripts.filter((script) => defined.has(script));
126
+ const skipped = scripts.filter((script) => !defined.has(script));
127
+
128
+ const messages = skipped.map(
129
+ (script) => `${script}: skipped (no "${script}" script in package.json)`,
130
+ );
131
+
132
+ if (toRun.length === 0) {
133
+ return {
134
+ passed: true,
135
+ checks: [],
136
+ errors: 0,
137
+ warnings: 0,
138
+ diagnostics: [],
139
+ messages,
140
+ } satisfies PrdVerificationResult;
141
+ }
142
+
143
+ const result = await checks.runChecks.run({ scripts: toRun });
144
+
145
+ // Failures the parser found no diagnostics for: report the output tail
146
+ // instead of "0 errors".
147
+ const unexplained = result.checks.filter(
148
+ (check) => check.status !== 'pass' && check.diagnostics.length === 0,
149
+ );
150
+
151
+ for (const check of unexplained) {
152
+ const detail = (check.stderr.trim() || check.stdout.trim()).slice(
153
+ -MAX_FAILURE_DETAIL,
154
+ );
155
+
156
+ messages.push(
157
+ `${check.script}: ${check.status}${detail ? ` (${detail})` : ''}`,
158
+ );
159
+ }
160
+
161
+ return {
162
+ passed: result.overall === 'pass',
163
+ checks: result.scripts_requested,
164
+ errors: result.summary.errors + unexplained.length,
165
+ warnings: result.summary.warnings,
166
+ diagnostics: result.diagnostics.map((diagnostic) => ({
167
+ file: diagnostic.file,
168
+ line: diagnostic.line,
169
+ message: diagnostic.message,
170
+ severity: diagnostic.severity,
171
+ })),
172
+ messages,
173
+ } satisfies PrdVerificationResult;
174
+ };
175
+ }
176
+
177
+ async function fileExists(path: string) {
178
+ try {
179
+ await access(path);
180
+ return true;
181
+ } catch {
182
+ return false;
183
+ }
184
+ }
@@ -0,0 +1,98 @@
1
+ import type { OpenQuestion, StructuredPRD } from './types';
2
+
3
+ /**
4
+ * Open questions as stored. Older files hold plain strings; they become
5
+ * questions with ids in list order. Entries without question text are dropped.
6
+ */
7
+ export function normalizeOpenQuestions(value: unknown): OpenQuestion[] {
8
+ if (!Array.isArray(value)) {
9
+ return [];
10
+ }
11
+
12
+ const questions: OpenQuestion[] = [];
13
+
14
+ for (const entry of value) {
15
+ if (typeof entry === 'string') {
16
+ if (entry.trim()) {
17
+ questions.push({ id: '', question: entry });
18
+ }
19
+
20
+ continue;
21
+ }
22
+
23
+ if (typeof entry !== 'object' || entry === null) {
24
+ continue;
25
+ }
26
+
27
+ const { id, question, why, options, recommended, storyIds } =
28
+ entry as Record<string, unknown>;
29
+
30
+ if (typeof question !== 'string' || !question.trim()) {
31
+ continue;
32
+ }
33
+
34
+ const strings = (list: unknown) =>
35
+ Array.isArray(list)
36
+ ? list.filter(
37
+ (item): item is string =>
38
+ typeof item === 'string' && item.length > 0,
39
+ )
40
+ : [];
41
+
42
+ questions.push({
43
+ id: typeof id === 'string' ? id : '',
44
+ question,
45
+ ...(typeof why === 'string' && why ? { why } : {}),
46
+ ...(strings(options).length ? { options: strings(options) } : {}),
47
+ ...(typeof recommended === 'string' && recommended
48
+ ? { recommended }
49
+ : {}),
50
+ ...(strings(storyIds).length ? { storyIds: strings(storyIds) } : {}),
51
+ });
52
+ }
53
+
54
+ // Legacy strings (and hand-written entries) get ids after the highest one present
55
+ let highest = questions.reduce((max, question) => {
56
+ const match = /^Q(\d+)$/.exec(question.id);
57
+
58
+ return match ? Math.max(max, Number(match[1])) : max;
59
+ }, 0);
60
+
61
+ return questions.map((question) =>
62
+ question.id ? question : { ...question, id: formatQuestionId(++highest) },
63
+ );
64
+ }
65
+
66
+ function formatQuestionId(number: number) {
67
+ return `Q${String(number).padStart(3, '0')}`;
68
+ }
69
+
70
+ /**
71
+ * The next question id. Answered questions are quoted in decisions, so an id
72
+ * is never handed out twice: the high-water mark is kept in metadata.
73
+ */
74
+ export function nextQuestionId(prd: StructuredPRD, extra: OpenQuestion[] = []) {
75
+ const present = [...prd.openQuestions, ...extra].reduce((max, question) => {
76
+ const match = /^Q(\d+)$/.exec(question.id);
77
+
78
+ return match ? Math.max(max, Number(match[1])) : max;
79
+ }, 0);
80
+ const next = Math.max(prd.metadata.lastQuestionNumber ?? 0, present) + 1;
81
+
82
+ prd.metadata.lastQuestionNumber = next;
83
+
84
+ return formatQuestionId(next);
85
+ }
86
+
87
+ /** Open questions that block a story that is not completed yet. */
88
+ export function blockingQuestions(prd: StructuredPRD) {
89
+ const unfinished = new Set(
90
+ prd.userStories
91
+ .filter((story) => story.status !== 'completed')
92
+ .map((story) => story.id),
93
+ );
94
+
95
+ return prd.openQuestions.filter((question) =>
96
+ question.storyIds?.some((id) => unfinished.has(id)),
97
+ );
98
+ }