@auto-engineer/server-implementer 0.4.6 → 0.4.8

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.
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env node
2
+ import { type CommandHandler, type Command, type Event } from '@auto-engineer/message-bus';
3
+ import { generateTextWithAI, getAvailableProviders } from '@auto-engineer/ai-gateway';
4
+ import path from 'path';
5
+ import { existsSync } from 'fs';
6
+ import { readFile, writeFile } from 'fs/promises';
7
+ import fg from 'fast-glob';
8
+ import createDebug from 'debug';
9
+
10
+ const debug = createDebug('server-impl:slice');
11
+ const debugHandler = createDebug('server-impl:slice:handler');
12
+ const debugProcess = createDebug('server-impl:slice:process');
13
+ const debugResult = createDebug('server-impl:slice:result');
14
+
15
+ // System prompt for AI implementation
16
+ const SYSTEM_PROMPT = `
17
+ You are a software engineer implementing missing logic in a sliced event-driven TypeScript backend. Each slice contains partially scaffolded code, and your task is to complete the logic following implementation instructions embedded in each file.
18
+
19
+ Project Characteristics:
20
+ - Architecture: sliced event-sourced CQRS (Command, Query, Reaction slices)
21
+ - Language: TypeScript with type-graphql and Emmett
22
+ - Each slice has scaffolded files with implementation instructions clearly marked with comments (e.g., '## IMPLEMENTATION INSTRUCTIONS ##') or TODOs.
23
+ - Tests (e.g., *.specs.ts) must pass.
24
+ - Type errors are not allowed.
25
+
26
+ Your Goal:
27
+ - Read the implementation instructions from the provided file.
28
+ - Generate only the code needed to fulfill the instructions, nothing extra and provide back the whole file without the instructions.
29
+ - Maintain immutability and adhere to functional best practices.
30
+ - Use only the types and domain constructs already present in the slice.
31
+ - Do not remove existing imports or types that are still referenced or required in the file.
32
+ - Return the entire updated file, not just the modified parts and remove any TODO comments or instructions after implementing the logic
33
+
34
+ Key rules:
35
+ - Never modify code outside the TODO or instruction areas.
36
+ - Ensure the code is production-ready and type-safe.
37
+ - Follow the slice type conventions:
38
+ - **Command slice**: validate command, inspect state, emit events, never mutate state. Uses graphql mutations.
39
+ - **Reaction slice**: respond to events with commands.
40
+ - **Query slice**: maintain projections based on events, do not emit or throw. Uses graphql queries.
41
+ - All code must be TypeScript compliant and follow functional patterns.
42
+ - If a test exists, make it pass.
43
+ - Keep implementations minimal and idiomatic.
44
+
45
+ Avoid:
46
+ - Adding new dependencies.
47
+ - Refactoring unrelated code.
48
+ - Changing the structure of already scaffolded files unless instructed.
49
+
50
+ You will receive:
51
+ - The path of the file to implement.
52
+ - The current contents of the file, with instruction comments.
53
+ - Other relevant files from the same slice (e.g., types, test, state, etc.).
54
+
55
+ You must:
56
+ - Return the entire updated file (no commentary and remove all implementation instructions).
57
+ - Ensure the output is valid TypeScript.
58
+ `;
59
+
60
+ export type ImplementSliceCommand = Command<
61
+ 'ImplementSlice',
62
+ {
63
+ sliceDirectory: string;
64
+ flowName: string;
65
+ context?: {
66
+ previousOutputs?: string;
67
+ attemptNumber?: number;
68
+ };
69
+ }
70
+ >;
71
+
72
+ export type SliceImplementedEvent = Event<
73
+ 'SliceImplemented',
74
+ {
75
+ sliceDirectory: string;
76
+ flowName: string;
77
+ filesImplemented: string[];
78
+ }
79
+ >;
80
+
81
+ export type SliceImplementationFailedEvent = Event<
82
+ 'SliceImplementationFailed',
83
+ {
84
+ sliceDirectory: string;
85
+ flowName: string;
86
+ error: string;
87
+ }
88
+ >;
89
+
90
+ // Helper function to extract code block from AI response
91
+ function extractCodeBlock(text: string): string {
92
+ return text
93
+ .replace(/```(?:ts|typescript)?/g, '')
94
+ .replace(/```/g, '')
95
+ .trim();
96
+ }
97
+
98
+ // Load all TypeScript files from the slice directory
99
+ async function loadContextFiles(sliceDir: string): Promise<Record<string, string>> {
100
+ const files = await fg(['*.ts'], { cwd: sliceDir });
101
+ const context: Record<string, string> = {};
102
+ for (const file of files) {
103
+ const absPath = path.join(sliceDir, file);
104
+ context[file] = await readFile(absPath, 'utf-8');
105
+ }
106
+ return context;
107
+ }
108
+
109
+ // Find files that need implementation
110
+ function findFilesToImplement(contextFiles: Record<string, string>): Array<[string, string]> {
111
+ return Object.entries(contextFiles).filter(
112
+ ([, content]) => content.includes('TODO:') || content.includes('IMPLEMENTATION INSTRUCTIONS'),
113
+ );
114
+ }
115
+
116
+ // Build prompt for initial implementation
117
+ function buildInitialPrompt(targetFile: string, context: Record<string, string>): string {
118
+ return `
119
+ ${SYSTEM_PROMPT}
120
+
121
+ ---
122
+ 📄 Target file to implement: ${targetFile}
123
+
124
+ ${context[targetFile]}
125
+
126
+ ---
127
+ 🧠 Other files in the same slice:
128
+ ${Object.entries(context)
129
+ .filter(([name]) => name !== targetFile)
130
+ .map(([name, content]) => `// File: ${name}\n${content}`)
131
+ .join('\n\n')}
132
+
133
+ ---
134
+ Return only the whole updated file of ${targetFile}. Do not remove existing imports or types that are still referenced or required in the file. The file returned has to be production ready.
135
+ `.trim();
136
+ }
137
+
138
+ // Build prompt for retry with context
139
+ function buildRetryPrompt(targetFile: string, context: Record<string, string>, previousOutputs: string): string {
140
+ return `
141
+ ${SYSTEM_PROMPT}
142
+
143
+ ---
144
+ The previous implementation needs adjustment based on this feedback:
145
+
146
+ ${previousOutputs}
147
+
148
+ 📄 File to update: ${targetFile}
149
+
150
+ ${context[targetFile]}
151
+
152
+ 🧠 Other files in the same slice:
153
+ ${Object.entries(context)
154
+ .filter(([name]) => name !== targetFile)
155
+ .map(([name, content]) => `// File: ${name}\n${content}`)
156
+ .join('\n\n')}
157
+
158
+ ---
159
+ Return only the corrected full contents of ${targetFile}, no commentary, no markdown.
160
+ `.trim();
161
+ }
162
+
163
+ // Main implementation function
164
+ async function implementSlice(
165
+ sliceDir: string,
166
+ flowName: string,
167
+ context?: { previousOutputs?: string; attemptNumber?: number },
168
+ ): Promise<{ success: boolean; filesImplemented: string[]; error?: string }> {
169
+ const availableProviders = getAvailableProviders();
170
+
171
+ if (availableProviders.length === 0) {
172
+ throw new Error(
173
+ 'No AI providers configured. Please set one of: OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, or XAI_API_KEY',
174
+ );
175
+ }
176
+
177
+ const AI_PROVIDER = availableProviders[0];
178
+ const sliceName = path.basename(sliceDir);
179
+
180
+ debugProcess(`Implementing slice: ${sliceName} for flow: ${flowName}`);
181
+
182
+ try {
183
+ // Load all context files
184
+ const contextFiles = await loadContextFiles(sliceDir);
185
+ const filesToImplement = findFilesToImplement(contextFiles);
186
+ const implementedFiles: string[] = [];
187
+
188
+ if (filesToImplement.length === 0) {
189
+ debugProcess('No files with TODO or IMPLEMENTATION INSTRUCTIONS found');
190
+ return { success: true, filesImplemented: [] };
191
+ }
192
+
193
+ // Implement each file that needs it
194
+ for (const [targetFile] of filesToImplement) {
195
+ debugProcess(`Implementing ${targetFile}`);
196
+
197
+ let prompt: string;
198
+ if (context !== undefined && context.previousOutputs !== undefined && context.previousOutputs.length > 0) {
199
+ // Use retry prompt if we have previous context
200
+ prompt = buildRetryPrompt(targetFile, contextFiles, context.previousOutputs);
201
+ debugProcess(`Using retry prompt for attempt #${context.attemptNumber ?? 2}`);
202
+ } else {
203
+ // Use initial prompt for first attempt
204
+ prompt = buildInitialPrompt(targetFile, contextFiles);
205
+ }
206
+
207
+ // Generate implementation with AI
208
+ const aiOutput = await generateTextWithAI(prompt, AI_PROVIDER);
209
+ const cleanedCode = extractCodeBlock(aiOutput);
210
+
211
+ // Write the implemented file
212
+ const filePath = path.join(sliceDir, targetFile);
213
+ await writeFile(filePath, cleanedCode, 'utf-8');
214
+
215
+ debugProcess(`Successfully implemented ${targetFile}`);
216
+ implementedFiles.push(targetFile);
217
+
218
+ // Update context for next file
219
+ contextFiles[targetFile] = cleanedCode;
220
+ }
221
+
222
+ return { success: true, filesImplemented: implementedFiles };
223
+ } catch (error) {
224
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
225
+ debugProcess(`Implementation failed: ${errorMessage}`);
226
+ return { success: false, filesImplemented: [], error: errorMessage };
227
+ }
228
+ }
229
+
230
+ function logCommandDebugInfo(command: ImplementSliceCommand): void {
231
+ const { sliceDirectory, flowName, context } = command.data;
232
+ debug('Handling ImplementSliceCommand');
233
+ debug(' Slice directory: %s', sliceDirectory);
234
+ debug(' Flow name: %s', flowName);
235
+ debug(' Context provided: %s', context ? 'yes' : 'no');
236
+ if (context) {
237
+ debug(' Attempt number: %d', context.attemptNumber ?? 1);
238
+ }
239
+ debug(' Request ID: %s', command.requestId);
240
+ debug(' Correlation ID: %s', command.correlationId ?? 'none');
241
+ }
242
+
243
+ function createFailedEvent(command: ImplementSliceCommand, error: string): SliceImplementationFailedEvent {
244
+ return {
245
+ type: 'SliceImplementationFailed',
246
+ data: {
247
+ sliceDirectory: command.data.sliceDirectory,
248
+ flowName: command.data.flowName,
249
+ error,
250
+ },
251
+ timestamp: new Date(),
252
+ requestId: command.requestId,
253
+ correlationId: command.correlationId,
254
+ };
255
+ }
256
+
257
+ function createSuccessEvent(command: ImplementSliceCommand, filesImplemented: string[]): SliceImplementedEvent {
258
+ return {
259
+ type: 'SliceImplemented',
260
+ data: {
261
+ sliceDirectory: command.data.sliceDirectory,
262
+ flowName: command.data.flowName,
263
+ filesImplemented,
264
+ },
265
+ timestamp: new Date(),
266
+ requestId: command.requestId,
267
+ correlationId: command.correlationId,
268
+ };
269
+ }
270
+
271
+ function logRetryContext(context: { previousOutputs?: string; attemptNumber?: number } | undefined): void {
272
+ if (context !== undefined && context.previousOutputs !== undefined && context.previousOutputs.length > 0) {
273
+ debugProcess('Retrying with context from previous attempt #%d', context.attemptNumber ?? 1);
274
+ debugProcess('Previous outputs: %s', context.previousOutputs.substring(0, 500));
275
+ }
276
+ }
277
+
278
+ export async function handleImplementSliceCommand(
279
+ command: ImplementSliceCommand,
280
+ ): Promise<SliceImplementedEvent | SliceImplementationFailedEvent> {
281
+ const { sliceDirectory, flowName, context } = command.data;
282
+
283
+ logCommandDebugInfo(command);
284
+
285
+ try {
286
+ const sliceRoot = path.resolve(sliceDirectory);
287
+ debugHandler('Resolved paths:');
288
+ debugHandler(' Slice root: %s', sliceRoot);
289
+
290
+ if (!existsSync(sliceRoot)) {
291
+ debugHandler('ERROR: Slice directory not found at %s', sliceRoot);
292
+ return createFailedEvent(command, `Slice directory not found at: ${sliceRoot}`);
293
+ }
294
+
295
+ debugProcess('Starting slice implementation for: %s', sliceRoot);
296
+ logRetryContext(context);
297
+
298
+ const result = await implementSlice(sliceRoot, flowName, context);
299
+
300
+ if (!result.success) {
301
+ return createFailedEvent(command, result.error ?? 'Implementation failed');
302
+ }
303
+
304
+ debugResult('Process succeeded');
305
+ debugResult('Files implemented: %d', result.filesImplemented.length);
306
+ debugResult('Files: %s', result.filesImplemented.join(', '));
307
+ debugResult('Returning success event: SliceImplemented');
308
+
309
+ return createSuccessEvent(command, result.filesImplemented);
310
+ } catch (error) {
311
+ debug('ERROR: Exception caught: %O', error);
312
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
313
+ return createFailedEvent(command, errorMessage);
314
+ }
315
+ }
316
+
317
+ export const implementSliceCommandHandler: CommandHandler<ImplementSliceCommand> = {
318
+ name: 'ImplementSlice',
319
+ handle: async (command: ImplementSliceCommand): Promise<void> => {
320
+ debug('CommandHandler executing for ImplementSlice');
321
+ const result = await handleImplementSliceCommand(command);
322
+
323
+ if (result.type === 'SliceImplemented') {
324
+ debug('Command handler completed: success');
325
+ console.log(`✅ Slice implementation completed successfully`);
326
+ console.log(` Flow: ${result.data.flowName}`);
327
+ console.log(` Files implemented: ${result.data.filesImplemented.length}`);
328
+ } else {
329
+ debug('Command handler completed: failure - %s', result.data.error);
330
+ console.error(`❌ Slice implementation failed: ${result.data.error}`);
331
+ process.exit(1);
332
+ }
333
+ },
334
+ };
package/src/index.ts CHANGED
@@ -5,3 +5,11 @@ export {
5
5
  type ServerImplementedEvent,
6
6
  type ServerImplementationFailedEvent,
7
7
  } from './commands/implement-server';
8
+
9
+ export {
10
+ implementSliceCommandHandler,
11
+ handleImplementSliceCommand,
12
+ type ImplementSliceCommand,
13
+ type SliceImplementedEvent,
14
+ type SliceImplementationFailedEvent,
15
+ } from './commands/implement-slice';
@@ -1,11 +0,0 @@
1
- import fg from 'fast-glob';
2
- import { runSlice } from './runSlice';
3
- import path from 'path';
4
- export async function runAllSlices(flowDir) {
5
- const flowName = path.basename(flowDir);
6
- const sliceDirs = await fg(`${flowDir}/**/*/`, { onlyDirectories: true });
7
- for (const sliceDir of sliceDirs) {
8
- await runSlice(sliceDir, flowName);
9
- }
10
- console.log('✅ All slices processed');
11
- }
@@ -1,16 +0,0 @@
1
- import fg from 'fast-glob';
2
- import path from 'path';
3
- import { runAllSlices } from './runAllSlices';
4
- export async function runFlows(baseDir) {
5
- const flowDirs = await fg('*', {
6
- cwd: baseDir,
7
- onlyDirectories: true,
8
- absolute: true,
9
- });
10
- console.log(`🚀 Found ${flowDirs.length} flows`);
11
- for (const flowDir of flowDirs) {
12
- console.log(`📂 Processing flow: ${path.basename(flowDir)}`);
13
- await runAllSlices(flowDir);
14
- }
15
- console.log('✅ All flows processed');
16
- }