groundswell 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.
Files changed (120) hide show
  1. package/.claude/settings.local.json +9 -0
  2. package/.claude/system_prompts/task-breakdown.md +100 -0
  3. package/PRPs/001-hierarchical-workflow-engine.md +2438 -0
  4. package/PRPs/PRDs/001-hierarchical-workflow-engine.md +543 -0
  5. package/PRPs/PRDs/002-agent-prompt.md +390 -0
  6. package/PRPs/PRDs/003-agent-prompt.md +943 -0
  7. package/PRPs/PRDs/004-agent-prompt.md +1136 -0
  8. package/PRPs/PRDs/tasks-001.json +492 -0
  9. package/PRPs/README.md +83 -0
  10. package/PRPs/templates/prp_base.md +222 -0
  11. package/README.md +218 -0
  12. package/docs/agent.md +422 -0
  13. package/docs/prompt.md +419 -0
  14. package/docs/workflow.md +600 -0
  15. package/examples/README.md +244 -0
  16. package/examples/examples/01-basic-workflow.ts +100 -0
  17. package/examples/examples/02-decorator-options.ts +217 -0
  18. package/examples/examples/03-parent-child.ts +241 -0
  19. package/examples/examples/04-observers-debugger.ts +340 -0
  20. package/examples/examples/05-error-handling.ts +387 -0
  21. package/examples/examples/06-concurrent-tasks.ts +352 -0
  22. package/examples/examples/07-agent-loops.ts +432 -0
  23. package/examples/examples/08-sdk-features.ts +667 -0
  24. package/examples/examples/09-reflection.ts +573 -0
  25. package/examples/examples/10-introspection.ts +550 -0
  26. package/examples/index.ts +143 -0
  27. package/examples/utils/helpers.ts +57 -0
  28. package/llms_full.txt +5890 -0
  29. package/package.json +63 -0
  30. package/plan/P1P2/PRP.md +527 -0
  31. package/plan/P1P2/research/LRU_CACHE_BEST_PRACTICES.md +1929 -0
  32. package/plan/P1P2/research/LRU_CACHE_CODE_PATTERNS.md +857 -0
  33. package/plan/P1P2/research/LRU_CACHE_INTEGRATION_GUIDE.md +738 -0
  34. package/plan/P1P2/research/LRU_CACHE_RESEARCH_INDEX.md +424 -0
  35. package/plan/P1P2/research/REFLECTION_INDEX.md +291 -0
  36. package/plan/P1P2/research/REFLECTION_RESEARCH_REPORT.md +1342 -0
  37. package/plan/P1P2/research/RESEARCH_SUMMARY.md +342 -0
  38. package/plan/P1P2/research/anthropic-sdk.md +174 -0
  39. package/plan/P1P2/research/async-local-storage.md +200 -0
  40. package/plan/P1P2/research/reflection-code-patterns.md +1205 -0
  41. package/plan/P1P2/research/reflection-decision-matrix.md +421 -0
  42. package/plan/P1P2/research/reflection-implementation-guide.md +1341 -0
  43. package/plan/P1P2/research/reflection-integration-guide.md +834 -0
  44. package/plan/P1P2/research/reflection-patterns.md +1468 -0
  45. package/plan/P1P2/research/reflection-quick-reference.md +558 -0
  46. package/plan/P1P2/research/zod-schema.md +152 -0
  47. package/plan/P3P4/PRP.md +1388 -0
  48. package/plan/P3P4/research/caching-lru.md +116 -0
  49. package/plan/P3P4/research/introspection-tools.md +177 -0
  50. package/plan/P3P4/research/reflection-patterns.md +117 -0
  51. package/plan/P4P5/PRP.md +1136 -0
  52. package/plan/P4P5/research/RESEARCH_SUMMARY.md +151 -0
  53. package/plan/architecture/external_deps.md +358 -0
  54. package/plan/architecture/system_context.md +242 -0
  55. package/plan/backlog.json +867 -0
  56. package/plan/research/INTROSPECTION_RESEARCH_SUMMARY.md +378 -0
  57. package/plan/research/README-INTROSPECTION.md +352 -0
  58. package/plan/research/agent-introspection-patterns.md +1085 -0
  59. package/plan/research/introspection-security-guide.md +928 -0
  60. package/plan/research/introspection-tool-examples.md +875 -0
  61. package/scripts/generate-llms-full.ts +206 -0
  62. package/src/__tests__/integration/agent-workflow.test.ts +256 -0
  63. package/src/__tests__/integration/tree-mirroring.test.ts +114 -0
  64. package/src/__tests__/unit/agent.test.ts +169 -0
  65. package/src/__tests__/unit/cache-key.test.ts +182 -0
  66. package/src/__tests__/unit/cache.test.ts +172 -0
  67. package/src/__tests__/unit/context.test.ts +138 -0
  68. package/src/__tests__/unit/decorators.test.ts +100 -0
  69. package/src/__tests__/unit/introspection-tools.test.ts +277 -0
  70. package/src/__tests__/unit/prompt.test.ts +135 -0
  71. package/src/__tests__/unit/reflection.test.ts +210 -0
  72. package/src/__tests__/unit/tree-debugger.test.ts +85 -0
  73. package/src/__tests__/unit/workflow.test.ts +81 -0
  74. package/src/cache/cache-key.ts +244 -0
  75. package/src/cache/cache.ts +236 -0
  76. package/src/cache/index.ts +8 -0
  77. package/src/core/agent.ts +573 -0
  78. package/src/core/context.ts +119 -0
  79. package/src/core/event-tree.ts +260 -0
  80. package/src/core/factory.ts +123 -0
  81. package/src/core/index.ts +17 -0
  82. package/src/core/logger.ts +87 -0
  83. package/src/core/mcp-handler.ts +184 -0
  84. package/src/core/prompt.ts +150 -0
  85. package/src/core/workflow-context.ts +349 -0
  86. package/src/core/workflow.ts +302 -0
  87. package/src/debugger/index.ts +1 -0
  88. package/src/debugger/tree-debugger.ts +210 -0
  89. package/src/decorators/index.ts +3 -0
  90. package/src/decorators/observed-state.ts +95 -0
  91. package/src/decorators/step.ts +139 -0
  92. package/src/decorators/task.ts +96 -0
  93. package/src/examples/index.ts +2 -0
  94. package/src/examples/tdd-orchestrator.ts +65 -0
  95. package/src/examples/test-cycle-workflow.ts +64 -0
  96. package/src/index.ts +140 -0
  97. package/src/reflection/index.ts +5 -0
  98. package/src/reflection/reflection.ts +407 -0
  99. package/src/tools/index.ts +36 -0
  100. package/src/tools/introspection.ts +464 -0
  101. package/src/types/agent.ts +90 -0
  102. package/src/types/decorators.ts +25 -0
  103. package/src/types/error-strategy.ts +13 -0
  104. package/src/types/error.ts +20 -0
  105. package/src/types/events.ts +74 -0
  106. package/src/types/index.ts +55 -0
  107. package/src/types/logging.ts +24 -0
  108. package/src/types/observer.ts +18 -0
  109. package/src/types/prompt.ts +40 -0
  110. package/src/types/reflection.ts +117 -0
  111. package/src/types/sdk-primitives.ts +128 -0
  112. package/src/types/snapshot.ts +14 -0
  113. package/src/types/workflow-context.ts +163 -0
  114. package/src/types/workflow.ts +37 -0
  115. package/src/utils/id.ts +11 -0
  116. package/src/utils/index.ts +3 -0
  117. package/src/utils/observable.ts +77 -0
  118. package/tasks.json +0 -0
  119. package/tsconfig.json +22 -0
  120. package/vitest.config.ts +16 -0
package/docs/prompt.md ADDED
@@ -0,0 +1,419 @@
1
+ # Prompts
2
+
3
+ Prompts are immutable value objects that define what to send to an agent and how to validate the response using Zod schemas.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Basic Usage](#basic-usage)
8
+ - [Configuration](#configuration)
9
+ - [Response Format](#response-format)
10
+ - [Data Injection](#data-injection)
11
+ - [Overrides](#overrides)
12
+ - [Validation](#validation)
13
+ - [API Reference](#api-reference)
14
+
15
+ ## Basic Usage
16
+
17
+ ```typescript
18
+ import { createPrompt } from 'groundswell';
19
+ import { z } from 'zod';
20
+
21
+ const prompt = createPrompt({
22
+ user: 'Analyze this code for bugs',
23
+ data: { code: 'function foo() { return 42; }' },
24
+ responseFormat: z.object({
25
+ bugs: z.array(z.string()),
26
+ severity: z.enum(['low', 'medium', 'high']),
27
+ }),
28
+ });
29
+ ```
30
+
31
+ ## Configuration
32
+
33
+ ### PromptConfig
34
+
35
+ ```typescript
36
+ interface PromptConfig<T> {
37
+ user: string; // Required: user message
38
+ data?: Record<string, unknown>; // Optional: structured data
39
+ responseFormat: z.ZodType<T>; // Required: response schema
40
+ system?: string; // Optional: system prompt override
41
+ tools?: Tool[]; // Optional: tools override
42
+ mcps?: MCPServer[]; // Optional: MCPs override
43
+ skills?: Skill[]; // Optional: skills override
44
+ hooks?: AgentHooks; // Optional: hooks override
45
+ enableReflection?: boolean; // Optional: enable reflection
46
+ }
47
+ ```
48
+
49
+ ### Creating Prompts
50
+
51
+ ```typescript
52
+ // Factory function
53
+ const prompt = createPrompt({
54
+ user: 'Hello',
55
+ responseFormat: z.object({ response: z.string() }),
56
+ });
57
+
58
+ // Class constructor
59
+ const prompt = new Prompt({
60
+ user: 'Hello',
61
+ responseFormat: z.object({ response: z.string() }),
62
+ });
63
+ ```
64
+
65
+ ## Response Format
66
+
67
+ ### Zod Schema Integration
68
+
69
+ The `responseFormat` property accepts any Zod schema. The schema:
70
+ - Defines the expected response type
71
+ - Enables compile-time type inference for `T`
72
+ - Validates API responses at runtime
73
+
74
+ ```typescript
75
+ import { z } from 'zod';
76
+
77
+ // Simple object
78
+ const simpleSchema = z.object({
79
+ answer: z.string(),
80
+ confidence: z.number(),
81
+ });
82
+
83
+ // With constraints
84
+ const strictSchema = z.object({
85
+ answer: z.string().min(10),
86
+ confidence: z.number().min(0).max(1),
87
+ reasoning: z.string().optional(),
88
+ });
89
+
90
+ // With descriptions (used for API hints)
91
+ const describedSchema = z.object({
92
+ summary: z.string().describe('Brief summary in 2-3 sentences'),
93
+ keyPoints: z.array(z.string()).describe('Main takeaways'),
94
+ score: z.number().min(0).max(100).describe('Quality score'),
95
+ });
96
+
97
+ // Enums
98
+ const enumSchema = z.object({
99
+ category: z.enum(['bug', 'feature', 'improvement']),
100
+ priority: z.enum(['low', 'medium', 'high', 'critical']),
101
+ });
102
+
103
+ // Nested objects
104
+ const nestedSchema = z.object({
105
+ analysis: z.object({
106
+ issues: z.array(z.object({
107
+ line: z.number(),
108
+ message: z.string(),
109
+ severity: z.enum(['error', 'warning', 'info']),
110
+ })),
111
+ summary: z.string(),
112
+ }),
113
+ });
114
+ ```
115
+
116
+ ### Type Inference
117
+
118
+ The prompt's response type is inferred from the schema:
119
+
120
+ ```typescript
121
+ const prompt = createPrompt({
122
+ user: 'Analyze',
123
+ responseFormat: z.object({
124
+ bugs: z.array(z.string()),
125
+ score: z.number(),
126
+ }),
127
+ });
128
+
129
+ // prompt is Prompt<{ bugs: string[], score: number }>
130
+
131
+ const result = await agent.prompt(prompt);
132
+ // result is { bugs: string[], score: number }
133
+ ```
134
+
135
+ ## Data Injection
136
+
137
+ ### Data Property
138
+
139
+ Structured data is injected into the user message:
140
+
141
+ ```typescript
142
+ const prompt = createPrompt({
143
+ user: 'Analyze the following code for security issues',
144
+ data: {
145
+ code: 'const x = eval(userInput);',
146
+ language: 'javascript',
147
+ },
148
+ responseFormat: analysisSchema,
149
+ });
150
+ ```
151
+
152
+ The data is formatted as XML-like sections:
153
+
154
+ ```
155
+ Analyze the following code for security issues
156
+
157
+ <code>
158
+ "const x = eval(userInput);"
159
+ </code>
160
+
161
+ <language>
162
+ "javascript"
163
+ </language>
164
+ ```
165
+
166
+ ### withData()
167
+
168
+ Create a new prompt with updated data (immutable):
169
+
170
+ ```typescript
171
+ const basePrompt = createPrompt({
172
+ user: 'Classify this item',
173
+ responseFormat: classificationSchema,
174
+ });
175
+
176
+ // Create variations
177
+ const applePrompt = basePrompt.withData({ item: 'apple' });
178
+ const bananaPrompt = basePrompt.withData({ item: 'banana' });
179
+
180
+ // Data is merged
181
+ const prompt = basePrompt
182
+ .withData({ item: 'apple' })
183
+ .withData({ context: 'grocery store' });
184
+ // Data: { item: 'apple', context: 'grocery store' }
185
+ ```
186
+
187
+ ## Overrides
188
+
189
+ ### System Prompt Override
190
+
191
+ ```typescript
192
+ const prompt = createPrompt({
193
+ user: 'Translate to French',
194
+ system: 'You are a professional translator. Be precise and formal.',
195
+ responseFormat: z.object({ translation: z.string() }),
196
+ });
197
+ ```
198
+
199
+ ### Tools Override
200
+
201
+ ```typescript
202
+ const prompt = createPrompt({
203
+ user: 'Calculate 2 + 2',
204
+ tools: [calculatorTool], // Only these tools available
205
+ responseFormat: z.object({ result: z.number() }),
206
+ });
207
+ ```
208
+
209
+ ### Hooks Override
210
+
211
+ ```typescript
212
+ const prompt = createPrompt({
213
+ user: 'Process data',
214
+ hooks: {
215
+ preToolUse: [async (ctx) => console.log('Using tool:', ctx.toolName)],
216
+ },
217
+ responseFormat: z.object({ processed: z.boolean() }),
218
+ });
219
+ ```
220
+
221
+ ### Reflection Override
222
+
223
+ ```typescript
224
+ const prompt = createPrompt({
225
+ user: 'Complex analysis',
226
+ enableReflection: true, // Enable for this prompt
227
+ responseFormat: analysisSchema,
228
+ });
229
+ ```
230
+
231
+ ## Validation
232
+
233
+ ### validateResponse()
234
+
235
+ Validates data and throws on failure:
236
+
237
+ ```typescript
238
+ try {
239
+ const validated = prompt.validateResponse(parsed);
240
+ // validated is T
241
+ } catch (error) {
242
+ // error is ZodError with detailed validation info
243
+ console.log(error.issues);
244
+ }
245
+ ```
246
+
247
+ ### safeValidateResponse()
248
+
249
+ Non-throwing validation:
250
+
251
+ ```typescript
252
+ const result = prompt.safeValidateResponse(parsed);
253
+
254
+ if (result.success) {
255
+ console.log(result.data); // Type: T
256
+ } else {
257
+ console.log(result.error.issues); // Validation errors
258
+ }
259
+ ```
260
+
261
+ ### Validation Errors
262
+
263
+ ZodError provides detailed error information:
264
+
265
+ ```typescript
266
+ const result = prompt.safeValidateResponse({ score: 'invalid' });
267
+
268
+ if (!result.success) {
269
+ for (const issue of result.error.issues) {
270
+ console.log(`Path: ${issue.path.join('.')}`);
271
+ console.log(`Message: ${issue.message}`);
272
+ console.log(`Code: ${issue.code}`);
273
+ }
274
+ }
275
+ ```
276
+
277
+ ## API Reference
278
+
279
+ ### Prompt Class
280
+
281
+ ```typescript
282
+ class Prompt<T> {
283
+ readonly id: string;
284
+ readonly user: string;
285
+ readonly data: Record<string, unknown>;
286
+ readonly responseFormat: z.ZodType<T>;
287
+ readonly systemOverride?: string;
288
+ readonly toolsOverride?: Tool[];
289
+ readonly mcpsOverride?: MCPServer[];
290
+ readonly skillsOverride?: Skill[];
291
+ readonly hooksOverride?: AgentHooks;
292
+ readonly enableReflection?: boolean;
293
+
294
+ constructor(config: PromptConfig<T>);
295
+
296
+ validateResponse(data: unknown): T;
297
+ safeValidateResponse(data: unknown):
298
+ | { success: true; data: T }
299
+ | { success: false; error: z.ZodError };
300
+ buildUserMessage(): string;
301
+ withData(newData: Record<string, unknown>): Prompt<T>;
302
+ getData(): Record<string, unknown>;
303
+ getResponseFormat(): z.ZodType<T>;
304
+ }
305
+ ```
306
+
307
+ ### Factory Function
308
+
309
+ ```typescript
310
+ function createPrompt<T>(config: PromptConfig<T>): Prompt<T>;
311
+ ```
312
+
313
+ ### Immutability
314
+
315
+ Prompts are frozen on creation:
316
+
317
+ ```typescript
318
+ const prompt = createPrompt({
319
+ user: 'Hello',
320
+ data: { key: 'value' },
321
+ responseFormat: schema,
322
+ });
323
+
324
+ // These throw errors:
325
+ prompt.user = 'Modified'; // Error
326
+ prompt.data.key = 'new'; // Error (data is also frozen)
327
+
328
+ // Use withData() to create variations:
329
+ const newPrompt = prompt.withData({ key: 'new' });
330
+ ```
331
+
332
+ ### Usage with Agents
333
+
334
+ ```typescript
335
+ import { createAgent, createPrompt } from 'groundswell';
336
+ import { z } from 'zod';
337
+
338
+ const agent = createAgent({ enableCache: true });
339
+
340
+ const prompt = createPrompt({
341
+ user: 'Summarize',
342
+ data: { text: longDocument },
343
+ responseFormat: z.object({
344
+ summary: z.string(),
345
+ wordCount: z.number(),
346
+ }),
347
+ });
348
+
349
+ // Simple execution
350
+ const result = await agent.prompt(prompt);
351
+
352
+ // With metadata
353
+ const { data, usage, duration } = await agent.promptWithMetadata(prompt);
354
+
355
+ // With reflection
356
+ const reflected = await agent.reflect(prompt);
357
+ ```
358
+
359
+ ### Common Patterns
360
+
361
+ **Reusable Base Prompts:**
362
+
363
+ ```typescript
364
+ const classifyPrompt = createPrompt({
365
+ user: 'Classify the following item into a category',
366
+ responseFormat: z.object({
367
+ category: z.string(),
368
+ confidence: z.number(),
369
+ }),
370
+ });
371
+
372
+ // Reuse with different items
373
+ for (const item of items) {
374
+ const result = await agent.prompt(classifyPrompt.withData({ item }));
375
+ }
376
+ ```
377
+
378
+ **Schema Libraries:**
379
+
380
+ ```typescript
381
+ // schemas.ts
382
+ export const AnalysisSchema = z.object({
383
+ summary: z.string(),
384
+ issues: z.array(z.object({
385
+ severity: z.enum(['low', 'medium', 'high']),
386
+ description: z.string(),
387
+ })),
388
+ });
389
+
390
+ export const ClassificationSchema = z.object({
391
+ category: z.string(),
392
+ confidence: z.number().min(0).max(1),
393
+ });
394
+
395
+ // usage.ts
396
+ import { AnalysisSchema, ClassificationSchema } from './schemas';
397
+
398
+ const analysisPrompt = createPrompt({
399
+ user: 'Analyze',
400
+ responseFormat: AnalysisSchema,
401
+ });
402
+ ```
403
+
404
+ **Conditional Prompts:**
405
+
406
+ ```typescript
407
+ function createAnalysisPrompt(options: { detailed: boolean }) {
408
+ return createPrompt({
409
+ user: options.detailed
410
+ ? 'Provide a detailed analysis with examples'
411
+ : 'Provide a brief analysis',
412
+ responseFormat: options.detailed
413
+ ? detailedSchema
414
+ : briefSchema,
415
+ });
416
+ }
417
+ ```
418
+
419
+ See [examples/09-reflection.ts](../examples/examples/09-reflection.ts) for prompt validation and reflection patterns.