@auto-engineer/server-implementer 0.4.7 → 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.
@@ -1,5 +1,5 @@
1
1
 
2
- > @auto-engineer/server-implementer@0.4.7 build /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
2
+ > @auto-engineer/server-implementer@0.4.8 build /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
3
3
  > tsc && tsx ../../scripts/fix-esm-imports.ts && chmod +x dist/cli/implement-server.js
4
4
 
5
5
  Fixed ESM imports in dist/
@@ -1,25 +1,19 @@
1
1
 
2
- > @auto-engineer/server-implementer@0.4.7 format /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
2
+ > @auto-engineer/server-implementer@0.4.8 format /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
3
3
  > prettier --write "**/*.{js,ts,json,md,yml,yaml}" --ignore-path ../../.prettierignore
4
4
 
5
5
  CHANGELOG.md 20ms (unchanged)
6
6
  DEBUG.md 3ms (unchanged)
7
- package.json 14ms (unchanged)
8
- src/agent/runAllSlices.js 10ms (unchanged)
9
- src/agent/runAllSlices.ts 26ms (unchanged)
10
- src/agent/runFlows.js 3ms (unchanged)
11
- src/agent/runFlows.ts 5ms (unchanged)
12
- src/agent/runSlice.js 24ms (unchanged)
13
- src/agent/runSlice.ts 22ms (unchanged)
14
- src/agent/runTests.js 5ms (unchanged)
15
- src/agent/runTests.ts 7ms (unchanged)
16
- src/cli/implement-server.ts 2ms (unchanged)
17
- src/cli/index.js 1ms (unchanged)
7
+ package.json 18ms (unchanged)
8
+ src/agent/runAllSlices.ts 32ms (unchanged)
9
+ src/agent/runFlows.ts 11ms (unchanged)
10
+ src/agent/runSlice.ts 37ms (unchanged)
11
+ src/agent/runTests.ts 11ms (unchanged)
12
+ src/cli/implement-server.ts 3ms (unchanged)
18
13
  src/cli/index.ts 2ms (unchanged)
19
- src/commands/implement-server.ts 6ms (unchanged)
14
+ src/commands/implement-server.ts 5ms (unchanged)
15
+ src/commands/implement-slice.ts 12ms (unchanged)
20
16
  src/index.ts 1ms (unchanged)
21
- src/prompts/systemPrompt.js 0ms (unchanged)
22
17
  src/prompts/systemPrompt.ts 1ms (unchanged)
23
- src/utils/extractCodeBlock.js 1ms (unchanged)
24
18
  src/utils/extractCodeBlock.ts 1ms (unchanged)
25
19
  tsconfig.json 1ms (unchanged)
@@ -0,0 +1,14 @@
1
+
2
+ > @auto-engineer/server-implementer@0.4.8 lint:fix /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
3
+ > eslint 'src/**/*.ts' --fix --config ../../eslint.config.ts
4
+
5
+
6
+ /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer/src/commands/implement-slice.ts
7
+ 198:11 error Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly @typescript-eslint/strict-boolean-expressions
8
+ 230:8 error Async function 'handleImplementSliceCommand' has a complexity of 13. Maximum allowed is 10 complexity
9
+ 269:9 error Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly @typescript-eslint/strict-boolean-expressions
10
+ 283:18 error Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly @typescript-eslint/strict-boolean-expressions
11
+
12
+ ✖ 4 problems (4 errors, 0 warnings)
13
+
14
+  ELIFECYCLE  Command failed with exit code 1.
@@ -1,4 +1,4 @@
1
1
 
2
- > @auto-engineer/server-implementer@0.4.7 lint /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
2
+ > @auto-engineer/server-implementer@0.4.8 lint /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
3
3
  > eslint 'src/**/*.ts' --max-warnings 0 --config ../../eslint.config.ts
4
4
 
@@ -1,5 +1,5 @@
1
1
 
2
- > @auto-engineer/server-implementer@0.4.7 test /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
2
+ > @auto-engineer/server-implementer@0.4.8 test /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
3
3
  > vitest run
4
4
 
5
5
 
@@ -1,4 +1,4 @@
1
1
 
2
- > @auto-engineer/server-implementer@0.4.7 type-check /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
2
+ > @auto-engineer/server-implementer@0.4.8 type-check /Users/sam/WebstormProjects/top/auto-engineer/packages/server-implementer
3
3
  > tsc --noEmit
4
4
 
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import { type CommandHandler, type Command, type Event } from '@auto-engineer/message-bus';
3
+ export type ImplementSliceCommand = Command<'ImplementSlice', {
4
+ sliceDirectory: string;
5
+ flowName: string;
6
+ context?: {
7
+ previousOutputs?: string;
8
+ attemptNumber?: number;
9
+ };
10
+ }>;
11
+ export type SliceImplementedEvent = Event<'SliceImplemented', {
12
+ sliceDirectory: string;
13
+ flowName: string;
14
+ filesImplemented: string[];
15
+ }>;
16
+ export type SliceImplementationFailedEvent = Event<'SliceImplementationFailed', {
17
+ sliceDirectory: string;
18
+ flowName: string;
19
+ error: string;
20
+ }>;
21
+ export declare function handleImplementSliceCommand(command: ImplementSliceCommand): Promise<SliceImplementedEvent | SliceImplementationFailedEvent>;
22
+ export declare const implementSliceCommandHandler: CommandHandler<ImplementSliceCommand>;
23
+ //# sourceMappingURL=implement-slice.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"implement-slice.d.ts","sourceRoot":"","sources":["../../src/commands/implement-slice.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,4BAA4B,CAAC;AA0D3F,MAAM,MAAM,qBAAqB,GAAG,OAAO,CACzC,gBAAgB,EAChB;IACE,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE;QACR,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;CACH,CACF,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,KAAK,CACvC,kBAAkB,EAClB;IACE,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B,CACF,CAAC;AAEF,MAAM,MAAM,8BAA8B,GAAG,KAAK,CAChD,2BAA2B,EAC3B;IACE,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACf,CACF,CAAC;AA8LF,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,qBAAqB,GAAG,8BAA8B,CAAC,CAmCjE;AAED,eAAO,MAAM,4BAA4B,EAAE,cAAc,CAAC,qBAAqB,CAiB9E,CAAC"}
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env node
2
+ import { generateTextWithAI, getAvailableProviders } from '@auto-engineer/ai-gateway';
3
+ import path from 'path';
4
+ import { existsSync } from 'fs';
5
+ import { readFile, writeFile } from 'fs/promises';
6
+ import fg from 'fast-glob';
7
+ import createDebug from 'debug';
8
+ const debug = createDebug('server-impl:slice');
9
+ const debugHandler = createDebug('server-impl:slice:handler');
10
+ const debugProcess = createDebug('server-impl:slice:process');
11
+ const debugResult = createDebug('server-impl:slice:result');
12
+ // System prompt for AI implementation
13
+ const SYSTEM_PROMPT = `
14
+ 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.
15
+
16
+ Project Characteristics:
17
+ - Architecture: sliced event-sourced CQRS (Command, Query, Reaction slices)
18
+ - Language: TypeScript with type-graphql and Emmett
19
+ - Each slice has scaffolded files with implementation instructions clearly marked with comments (e.g., '## IMPLEMENTATION INSTRUCTIONS ##') or TODOs.
20
+ - Tests (e.g., *.specs.ts) must pass.
21
+ - Type errors are not allowed.
22
+
23
+ Your Goal:
24
+ - Read the implementation instructions from the provided file.
25
+ - Generate only the code needed to fulfill the instructions, nothing extra and provide back the whole file without the instructions.
26
+ - Maintain immutability and adhere to functional best practices.
27
+ - Use only the types and domain constructs already present in the slice.
28
+ - Do not remove existing imports or types that are still referenced or required in the file.
29
+ - Return the entire updated file, not just the modified parts and remove any TODO comments or instructions after implementing the logic
30
+
31
+ Key rules:
32
+ - Never modify code outside the TODO or instruction areas.
33
+ - Ensure the code is production-ready and type-safe.
34
+ - Follow the slice type conventions:
35
+ - **Command slice**: validate command, inspect state, emit events, never mutate state. Uses graphql mutations.
36
+ - **Reaction slice**: respond to events with commands.
37
+ - **Query slice**: maintain projections based on events, do not emit or throw. Uses graphql queries.
38
+ - All code must be TypeScript compliant and follow functional patterns.
39
+ - If a test exists, make it pass.
40
+ - Keep implementations minimal and idiomatic.
41
+
42
+ Avoid:
43
+ - Adding new dependencies.
44
+ - Refactoring unrelated code.
45
+ - Changing the structure of already scaffolded files unless instructed.
46
+
47
+ You will receive:
48
+ - The path of the file to implement.
49
+ - The current contents of the file, with instruction comments.
50
+ - Other relevant files from the same slice (e.g., types, test, state, etc.).
51
+
52
+ You must:
53
+ - Return the entire updated file (no commentary and remove all implementation instructions).
54
+ - Ensure the output is valid TypeScript.
55
+ `;
56
+ // Helper function to extract code block from AI response
57
+ function extractCodeBlock(text) {
58
+ return text
59
+ .replace(/```(?:ts|typescript)?/g, '')
60
+ .replace(/```/g, '')
61
+ .trim();
62
+ }
63
+ // Load all TypeScript files from the slice directory
64
+ async function loadContextFiles(sliceDir) {
65
+ const files = await fg(['*.ts'], { cwd: sliceDir });
66
+ const context = {};
67
+ for (const file of files) {
68
+ const absPath = path.join(sliceDir, file);
69
+ context[file] = await readFile(absPath, 'utf-8');
70
+ }
71
+ return context;
72
+ }
73
+ // Find files that need implementation
74
+ function findFilesToImplement(contextFiles) {
75
+ return Object.entries(contextFiles).filter(([, content]) => content.includes('TODO:') || content.includes('IMPLEMENTATION INSTRUCTIONS'));
76
+ }
77
+ // Build prompt for initial implementation
78
+ function buildInitialPrompt(targetFile, context) {
79
+ return `
80
+ ${SYSTEM_PROMPT}
81
+
82
+ ---
83
+ 📄 Target file to implement: ${targetFile}
84
+
85
+ ${context[targetFile]}
86
+
87
+ ---
88
+ 🧠 Other files in the same slice:
89
+ ${Object.entries(context)
90
+ .filter(([name]) => name !== targetFile)
91
+ .map(([name, content]) => `// File: ${name}\n${content}`)
92
+ .join('\n\n')}
93
+
94
+ ---
95
+ 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.
96
+ `.trim();
97
+ }
98
+ // Build prompt for retry with context
99
+ function buildRetryPrompt(targetFile, context, previousOutputs) {
100
+ return `
101
+ ${SYSTEM_PROMPT}
102
+
103
+ ---
104
+ The previous implementation needs adjustment based on this feedback:
105
+
106
+ ${previousOutputs}
107
+
108
+ 📄 File to update: ${targetFile}
109
+
110
+ ${context[targetFile]}
111
+
112
+ 🧠 Other files in the same slice:
113
+ ${Object.entries(context)
114
+ .filter(([name]) => name !== targetFile)
115
+ .map(([name, content]) => `// File: ${name}\n${content}`)
116
+ .join('\n\n')}
117
+
118
+ ---
119
+ Return only the corrected full contents of ${targetFile}, no commentary, no markdown.
120
+ `.trim();
121
+ }
122
+ // Main implementation function
123
+ async function implementSlice(sliceDir, flowName, context) {
124
+ const availableProviders = getAvailableProviders();
125
+ if (availableProviders.length === 0) {
126
+ throw new Error('No AI providers configured. Please set one of: OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, or XAI_API_KEY');
127
+ }
128
+ const AI_PROVIDER = availableProviders[0];
129
+ const sliceName = path.basename(sliceDir);
130
+ debugProcess(`Implementing slice: ${sliceName} for flow: ${flowName}`);
131
+ try {
132
+ // Load all context files
133
+ const contextFiles = await loadContextFiles(sliceDir);
134
+ const filesToImplement = findFilesToImplement(contextFiles);
135
+ const implementedFiles = [];
136
+ if (filesToImplement.length === 0) {
137
+ debugProcess('No files with TODO or IMPLEMENTATION INSTRUCTIONS found');
138
+ return { success: true, filesImplemented: [] };
139
+ }
140
+ // Implement each file that needs it
141
+ for (const [targetFile] of filesToImplement) {
142
+ debugProcess(`Implementing ${targetFile}`);
143
+ let prompt;
144
+ if (context !== undefined && context.previousOutputs !== undefined && context.previousOutputs.length > 0) {
145
+ // Use retry prompt if we have previous context
146
+ prompt = buildRetryPrompt(targetFile, contextFiles, context.previousOutputs);
147
+ debugProcess(`Using retry prompt for attempt #${context.attemptNumber ?? 2}`);
148
+ }
149
+ else {
150
+ // Use initial prompt for first attempt
151
+ prompt = buildInitialPrompt(targetFile, contextFiles);
152
+ }
153
+ // Generate implementation with AI
154
+ const aiOutput = await generateTextWithAI(prompt, AI_PROVIDER);
155
+ const cleanedCode = extractCodeBlock(aiOutput);
156
+ // Write the implemented file
157
+ const filePath = path.join(sliceDir, targetFile);
158
+ await writeFile(filePath, cleanedCode, 'utf-8');
159
+ debugProcess(`Successfully implemented ${targetFile}`);
160
+ implementedFiles.push(targetFile);
161
+ // Update context for next file
162
+ contextFiles[targetFile] = cleanedCode;
163
+ }
164
+ return { success: true, filesImplemented: implementedFiles };
165
+ }
166
+ catch (error) {
167
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
168
+ debugProcess(`Implementation failed: ${errorMessage}`);
169
+ return { success: false, filesImplemented: [], error: errorMessage };
170
+ }
171
+ }
172
+ function logCommandDebugInfo(command) {
173
+ const { sliceDirectory, flowName, context } = command.data;
174
+ debug('Handling ImplementSliceCommand');
175
+ debug(' Slice directory: %s', sliceDirectory);
176
+ debug(' Flow name: %s', flowName);
177
+ debug(' Context provided: %s', context ? 'yes' : 'no');
178
+ if (context) {
179
+ debug(' Attempt number: %d', context.attemptNumber ?? 1);
180
+ }
181
+ debug(' Request ID: %s', command.requestId);
182
+ debug(' Correlation ID: %s', command.correlationId ?? 'none');
183
+ }
184
+ function createFailedEvent(command, error) {
185
+ return {
186
+ type: 'SliceImplementationFailed',
187
+ data: {
188
+ sliceDirectory: command.data.sliceDirectory,
189
+ flowName: command.data.flowName,
190
+ error,
191
+ },
192
+ timestamp: new Date(),
193
+ requestId: command.requestId,
194
+ correlationId: command.correlationId,
195
+ };
196
+ }
197
+ function createSuccessEvent(command, filesImplemented) {
198
+ return {
199
+ type: 'SliceImplemented',
200
+ data: {
201
+ sliceDirectory: command.data.sliceDirectory,
202
+ flowName: command.data.flowName,
203
+ filesImplemented,
204
+ },
205
+ timestamp: new Date(),
206
+ requestId: command.requestId,
207
+ correlationId: command.correlationId,
208
+ };
209
+ }
210
+ function logRetryContext(context) {
211
+ if (context !== undefined && context.previousOutputs !== undefined && context.previousOutputs.length > 0) {
212
+ debugProcess('Retrying with context from previous attempt #%d', context.attemptNumber ?? 1);
213
+ debugProcess('Previous outputs: %s', context.previousOutputs.substring(0, 500));
214
+ }
215
+ }
216
+ export async function handleImplementSliceCommand(command) {
217
+ const { sliceDirectory, flowName, context } = command.data;
218
+ logCommandDebugInfo(command);
219
+ try {
220
+ const sliceRoot = path.resolve(sliceDirectory);
221
+ debugHandler('Resolved paths:');
222
+ debugHandler(' Slice root: %s', sliceRoot);
223
+ if (!existsSync(sliceRoot)) {
224
+ debugHandler('ERROR: Slice directory not found at %s', sliceRoot);
225
+ return createFailedEvent(command, `Slice directory not found at: ${sliceRoot}`);
226
+ }
227
+ debugProcess('Starting slice implementation for: %s', sliceRoot);
228
+ logRetryContext(context);
229
+ const result = await implementSlice(sliceRoot, flowName, context);
230
+ if (!result.success) {
231
+ return createFailedEvent(command, result.error ?? 'Implementation failed');
232
+ }
233
+ debugResult('Process succeeded');
234
+ debugResult('Files implemented: %d', result.filesImplemented.length);
235
+ debugResult('Files: %s', result.filesImplemented.join(', '));
236
+ debugResult('Returning success event: SliceImplemented');
237
+ return createSuccessEvent(command, result.filesImplemented);
238
+ }
239
+ catch (error) {
240
+ debug('ERROR: Exception caught: %O', error);
241
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
242
+ return createFailedEvent(command, errorMessage);
243
+ }
244
+ }
245
+ export const implementSliceCommandHandler = {
246
+ name: 'ImplementSlice',
247
+ handle: async (command) => {
248
+ debug('CommandHandler executing for ImplementSlice');
249
+ const result = await handleImplementSliceCommand(command);
250
+ if (result.type === 'SliceImplemented') {
251
+ debug('Command handler completed: success');
252
+ console.log(`✅ Slice implementation completed successfully`);
253
+ console.log(` Flow: ${result.data.flowName}`);
254
+ console.log(` Files implemented: ${result.data.filesImplemented.length}`);
255
+ }
256
+ else {
257
+ debug('Command handler completed: failure - %s', result.data.error);
258
+ console.error(`❌ Slice implementation failed: ${result.data.error}`);
259
+ process.exit(1);
260
+ }
261
+ },
262
+ };
263
+ //# sourceMappingURL=implement-slice.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"implement-slice.js","sourceRoot":"","sources":["../../src/commands/implement-slice.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AACtF,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,MAAM,WAAW,CAAC;AAC3B,OAAO,WAAW,MAAM,OAAO,CAAC;AAEhC,MAAM,KAAK,GAAG,WAAW,CAAC,mBAAmB,CAAC,CAAC;AAC/C,MAAM,YAAY,GAAG,WAAW,CAAC,2BAA2B,CAAC,CAAC;AAC9D,MAAM,YAAY,GAAG,WAAW,CAAC,2BAA2B,CAAC,CAAC;AAC9D,MAAM,WAAW,GAAG,WAAW,CAAC,0BAA0B,CAAC,CAAC;AAE5D,sCAAsC;AACtC,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CrB,CAAC;AAgCF,yDAAyD;AACzD,SAAS,gBAAgB,CAAC,IAAY;IACpC,OAAO,IAAI;SACR,OAAO,CAAC,wBAA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AG,MAAM,2BAA2B,CAAC,OAAO,CAAC,CAAC;QAE1D,IAAI,MAAM,CAAC,IAAI,KAAK,kBAAkB,EAAE,CAAC;YACvC,KAAK,CAAC,oCAAoC,CAAC,CAAC;YAC5C,OAAO,CAAC,GAAG,CAAC,+CAA+C,CAAC,CAAC;YAC7D,OAAO,CAAC,GAAG,CAAC,YAAY,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;YAChD,OAAO,CAAC,GAAG,CAAC,yBAAyB,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC;QAC9E,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,yCAAyC,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACpE,OAAO,CAAC,KAAK,CAAC,kCAAkC,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;YACrE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;CACF,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { implementServerCommandHandler, handleImplementServerCommand, type ImplementServerCommand, type ServerImplementedEvent, type ServerImplementationFailedEvent, } from './commands/implement-server';
2
+ export { implementSliceCommandHandler, handleImplementSliceCommand, type ImplementSliceCommand, type SliceImplementedEvent, type SliceImplementationFailedEvent, } from './commands/implement-slice';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC3B,KAAK,+BAA+B,GACrC,MAAM,6BAA6B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC3B,KAAK,+BAA+B,GACrC,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,EAC1B,KAAK,8BAA8B,GACpC,MAAM,4BAA4B,CAAC"}
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export { implementServerCommandHandler, handleImplementServerCommand, } from './commands/implement-server.js';
2
+ export { implementSliceCommandHandler, handleImplementSliceCommand, } from './commands/implement-slice.js';
2
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAI7B,MAAM,6BAA6B,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAI7B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAI5B,MAAM,4BAA4B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auto-engineer/server-implementer",
3
- "version": "0.4.7",
3
+ "version": "0.4.8",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -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
- }
@@ -1,328 +0,0 @@
1
- import path from 'path';
2
- import fg from 'fast-glob';
3
- import { generateTextWithAI, getAvailableProviders } from '@auto-engineer/ai-gateway';
4
- import { readFile, writeFile, access } from 'fs/promises';
5
- import { execa } from 'execa';
6
- import { SYSTEM_PROMPT } from '../prompts/systemPrompt';
7
- import { extractCodeBlock } from '../utils/extractCodeBlock';
8
- import { runTests } from './runTests';
9
- const availableProviders = getAvailableProviders();
10
- const AI_PROVIDER = availableProviders[0];
11
- if (availableProviders.length === 0) {
12
- console.error(
13
- '❌ No AI providers configured. Please set one of: OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, or XAI_API_KEY',
14
- );
15
- process.exit(1);
16
- }
17
- export async function runSlice(sliceDir, flow) {
18
- const sliceName = path.basename(sliceDir);
19
- console.log(`✏️ Implementing slice: ${sliceName} for flow: ${flow}`);
20
- const contextFiles = await loadContextFiles(sliceDir);
21
- const filesToImplement = findFilesToImplement(contextFiles);
22
- for (const [targetFile] of filesToImplement) {
23
- await implementFileFromAI(sliceDir, targetFile, contextFiles);
24
- }
25
- const result = await runTestsAndTypecheck(sliceDir);
26
- reportTestAndTypecheckResults(sliceDir, flow, result);
27
- if (result.success) {
28
- console.log(`✅ All tests and checks passed on first attempt.`);
29
- return;
30
- }
31
- await retryFailedFiles(sliceDir, flow, result);
32
- if (result.failedTestFiles.length > 0) {
33
- await retryFailedTests(sliceDir, flow, result);
34
- }
35
- }
36
- async function retryFailedFiles(sliceDir, flow, initialResult) {
37
- let contextFiles = await loadContextFiles(sliceDir);
38
- let result = initialResult;
39
- for (let attempt = 1; attempt <= 5; attempt++) {
40
- if (result.failedTypecheckFiles.length === 0) {
41
- console.log(`✅ Typecheck issues resolved after attempt ${attempt - 1}`);
42
- break;
43
- }
44
- console.log(`🔁 Typecheck retry attempt ${attempt} for ${result.failedTypecheckFiles.length} files...`);
45
- contextFiles = await loadContextFiles(sliceDir);
46
- for (const filePath of result.failedTypecheckFiles) {
47
- const fileName = path.basename(filePath);
48
- const retryPrompt = buildRetryPrompt(fileName, contextFiles, result.testErrors, result.typecheckErrors);
49
- console.log(`🔧 Retrying typecheck error in ${fileName} in flow ${flow}...`);
50
- const aiOutput = await generateTextWithAI(retryPrompt, AI_PROVIDER);
51
- const cleanedCode = extractCodeBlock(aiOutput);
52
- await writeFile(path.join(sliceDir, fileName), cleanedCode, 'utf-8');
53
- console.log(`♻️ Updated ${fileName} to fix typecheck errors`);
54
- }
55
- result = await runTestsAndTypecheck(sliceDir);
56
- reportTestAndTypecheckResults(sliceDir, flow, result);
57
- }
58
- if (result.failedTypecheckFiles.length > 0) {
59
- console.log(`⚠️ Fixing tests caused typecheck errors. Retrying typecheck fixes...`);
60
- const typecheckOnlyResult = {
61
- ...result,
62
- testErrors: '', // Clear test errors since we're only fixing typecheck
63
- failedTestFiles: [], // Clear failed test files
64
- };
65
- result = await retryFailedFiles(sliceDir, path.basename(sliceDir), typecheckOnlyResult);
66
- // After fixing typecheck, re-run everything to get fresh results
67
- const freshResult = await runTestsAndTypecheck(sliceDir);
68
- reportTestAndTypecheckResults(sliceDir, flow, freshResult);
69
- result = freshResult;
70
- if (result.failedTestFiles.length === 0) {
71
- console.log(`✅ All test issues resolved after fixing type errors.`);
72
- }
73
- }
74
- return result;
75
- }
76
- async function loadContextFiles(sliceDir) {
77
- const files = await fg(['*.ts'], { cwd: sliceDir });
78
- const context = {};
79
- for (const file of files) {
80
- const absPath = path.join(sliceDir, file);
81
- context[file] = await readFile(absPath, 'utf-8');
82
- }
83
- return context;
84
- }
85
- function findFilesToImplement(contextFiles) {
86
- return Object.entries(contextFiles).filter(
87
- ([, content]) => content.includes('TODO:') || content.includes('IMPLEMENTATION INSTRUCTIONS'),
88
- );
89
- }
90
- function buildInitialPrompt(targetFile, context) {
91
- return `
92
- ${SYSTEM_PROMPT}
93
-
94
- ---
95
- 📄 Target file to implement: ${targetFile}
96
-
97
- ${context[targetFile]}
98
-
99
- ---
100
- 🧠 Other files in the same slice:
101
- ${Object.entries(context)
102
- .filter(([name]) => name !== targetFile)
103
- .map(([name, content]) => `// File: ${name}\n${content}`)
104
- .join('\n\n')}
105
-
106
- ---
107
- 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.
108
- `.trim();
109
- }
110
- function buildRetryPrompt(targetFile, context, testErrors, typeErrors) {
111
- return `
112
- ${SYSTEM_PROMPT}
113
-
114
- ---
115
- The previous implementation of ${targetFile} caused test or type-check failures.
116
-
117
- 📄 File to fix: ${targetFile}
118
-
119
- ${context[targetFile]}
120
-
121
- 🧠 Other files in the same slice:
122
- ${Object.entries(context)
123
- .filter(([name]) => name !== targetFile)
124
- .map(([name, content]) => `// File: ${name}\n${content}`)
125
- .join('\n\n')}
126
-
127
- 🧪 Test errors:
128
- ${testErrors || 'None'}
129
-
130
- 📐 Typecheck errors:
131
- ${typeErrors || 'None'}
132
-
133
- ---
134
- Return only the corrected full contents of ${targetFile}, no commentary, no markdown.
135
- `.trim();
136
- }
137
- async function implementFileFromAI(sliceDir, targetFile, contextFiles) {
138
- const filePath = path.join(sliceDir, targetFile);
139
- const prompt = buildInitialPrompt(targetFile, contextFiles);
140
- console.log(`🔮 Analysing and Implementing ${targetFile}`);
141
- const aiOutput = await generateTextWithAI(prompt, AI_PROVIDER);
142
- //console.log('AI output:', aiOutput);
143
- const cleanedCode = extractCodeBlock(aiOutput);
144
- await writeFile(filePath, cleanedCode, 'utf-8');
145
- console.log(`♻ Implemented ${targetFile}`);
146
- }
147
- export async function runTestsAndTypecheck(sliceDir) {
148
- const rootDir = await findProjectRoot(sliceDir);
149
- const testResult = await runTests(sliceDir, rootDir);
150
- const typecheckResult = await runTypecheck(sliceDir, rootDir);
151
- return {
152
- success: testResult.success && typecheckResult.success,
153
- failedTestFiles: testResult.failedTestFiles,
154
- failedTypecheckFiles: typecheckResult.failedTypecheckFiles,
155
- testErrors: testResult.testErrors,
156
- typecheckErrors: typecheckResult.typecheckErrors,
157
- };
158
- }
159
- async function retryFailedTests(sliceDir, flow, result) {
160
- let contextFiles = await loadContextFiles(sliceDir);
161
- for (let attempt = 1; attempt <= 5; attempt++) {
162
- if (result.failedTestFiles.length === 0) {
163
- console.log(`✅ Test failures resolved after attempt ${attempt - 1}`);
164
- break;
165
- }
166
- console.log(`🔁 Test retry attempt ${attempt} for ${result.failedTestFiles.length} files...`);
167
- const smartPrompt = `
168
- ${SYSTEM_PROMPT}
169
- ---
170
- 🧪 The current implementation has test failures.
171
-
172
- 📄 Test errors:
173
- ${result.testErrors || 'None'}
174
-
175
- 🧠 Full slice context:
176
- ${Object.entries(contextFiles)
177
- .map(([name, content]) => `// File: ${name}\n${content}`)
178
- .join('\n\n')}
179
-
180
- ---
181
- Please return the full corrected content of a single file (not a test file) that should be updated to fix the failing tests.
182
-
183
- Use this format:
184
- \`\`\`ts
185
- // File: <fileName>.ts
186
- <corrected code>
187
- \`\`\`
188
-
189
- No commentary or markdown outside the code block.
190
- `.trim();
191
- console.log('🔮 Asking AI to suggest a fix for test failures...');
192
- const aiOutput = await generateTextWithAI(smartPrompt, AI_PROVIDER);
193
- const cleaned = extractCodeBlock(aiOutput);
194
- const match = cleaned.match(/^\/\/ File: (.+?)\n([\s\S]*)/m);
195
- if (!match) {
196
- console.warn(`⚠️ Skipping retry. AI output didn't match expected format.`);
197
- break;
198
- }
199
- const [, fileName, code] = match;
200
- const absPath = path.join(sliceDir, fileName.trim());
201
- console.log('🔧 Applying AI fix to:', absPath);
202
- await writeFile(absPath, code.trim(), 'utf-8');
203
- console.log(`♻️ Updated ${fileName.trim()} to fix tests`);
204
- contextFiles = await loadContextFiles(sliceDir);
205
- result = await runTestsAndTypecheck(sliceDir);
206
- reportTestAndTypecheckResults(sliceDir, flow, result);
207
- // If test fix introduced a new type error, handle it before continuing
208
- if (result.failedTypecheckFiles.length > 0) {
209
- console.log(`⚠️ Fixing tests caused typecheck errors. Retrying typecheck fixes...`);
210
- result = await retryFailedFiles(sliceDir, flow, result);
211
- if (result.failedTestFiles.length === 0) {
212
- console.log(`✅ All test issues resolved after fixing type errors.`);
213
- break;
214
- }
215
- }
216
- contextFiles = await loadContextFiles(sliceDir);
217
- }
218
- if (result.failedTestFiles.length > 0) {
219
- console.error(`❌ Some test failures remain after retry attempts.`);
220
- for (const file of result.failedTestFiles) {
221
- console.log(` - ${path.relative(sliceDir, file)}`);
222
- }
223
- }
224
- }
225
- async function runTypecheck(sliceDir, rootDir) {
226
- try {
227
- const result = await execa('npx', ['tsc', '--noEmit'], {
228
- cwd: rootDir,
229
- stdio: 'pipe',
230
- reject: false,
231
- });
232
- const output = (result.stdout ?? '') + (result.stderr ?? '');
233
- if (result.exitCode !== 0 || output.includes('error')) {
234
- return await processTypecheckOutput(output, sliceDir, rootDir);
235
- }
236
- return { success: true, typecheckErrors: '', failedTypecheckFiles: [] };
237
- } catch (err) {
238
- const execaErr = err;
239
- const output = (execaErr.stdout ?? '') + (execaErr.stderr ?? '');
240
- console.error('TypeScript execution error:', output);
241
- const files = await fg(['*.ts'], { cwd: sliceDir, absolute: true });
242
- return { success: false, typecheckErrors: output, failedTypecheckFiles: files };
243
- }
244
- }
245
- function getTypecheckPatterns() {
246
- return [
247
- /^([^:]+\.ts)\(\d+,\d+\): error/gm,
248
- /error TS\d+: (.+) '([^']+\.ts)'/gm,
249
- /^([^:]+\.ts):\d+:\d+\s+-\s+error/gm,
250
- ];
251
- }
252
- function extractFailedFiles(output, patterns, rootDir, sliceDir) {
253
- const failedFiles = new Set();
254
- for (const pattern of patterns) {
255
- for (const match of output.matchAll(pattern)) {
256
- const filePath = match[1] ? path.resolve(rootDir, match[1]) : '';
257
- const notNodeModules = !filePath.includes('node_modules');
258
- const inSlice = sliceDir === undefined || filePath.startsWith(sliceDir);
259
- if (notNodeModules && inSlice) {
260
- failedFiles.add(filePath);
261
- }
262
- }
263
- }
264
- return Array.from(failedFiles);
265
- }
266
- async function processTypecheckOutput(output, sliceDir, rootDir) {
267
- const relativePath = path.relative(rootDir, sliceDir);
268
- const filtered = output
269
- .split('\n')
270
- .filter((line) => {
271
- const hasError = line.includes('error TS') || line.includes('): error');
272
- const notNodeModules = !line.includes('node_modules');
273
- const hasSlicePath = line.includes(relativePath) || line.includes(sliceDir);
274
- return hasError && notNodeModules && hasSlicePath;
275
- })
276
- .join('\n');
277
- if (filtered.trim() === '') {
278
- return { success: true, typecheckErrors: '', failedTypecheckFiles: [] };
279
- }
280
- const failedFiles = await processTypecheckFailure(filtered, rootDir, sliceDir);
281
- return {
282
- success: false,
283
- typecheckErrors: filtered,
284
- failedTypecheckFiles: failedFiles,
285
- };
286
- }
287
- async function processTypecheckFailure(output, rootDir, sliceDir) {
288
- const patterns = getTypecheckPatterns();
289
- let failed = extractFailedFiles(output, patterns, rootDir, sliceDir);
290
- if (failed.length === 0 && output.includes('error')) {
291
- failed = await fg(['*.ts'], { cwd: sliceDir, absolute: true });
292
- }
293
- return failed;
294
- }
295
- async function findProjectRoot(startDir) {
296
- let dir = startDir;
297
- while (dir !== path.dirname(dir)) {
298
- try {
299
- await access(path.join(dir, 'package.json'));
300
- return dir;
301
- } catch {
302
- dir = path.dirname(dir);
303
- }
304
- }
305
- throw new Error('❌ Could not find project root');
306
- }
307
- function reportTestAndTypecheckResults(sliceDir, flow, result) {
308
- const sliceName = path.basename(sliceDir);
309
- if (result.success) {
310
- console.log(`✅ All Tests and checks passed for: ${sliceName} in flow ${flow}`);
311
- return;
312
- }
313
- console.error(`❌ ${sliceName} in floe ${flow} failed tests or type-checks.`);
314
- if (result.failedTestFiles.length) {
315
- const files = result.failedTestFiles.map((f) => path.relative(sliceDir, f));
316
- console.log(`🧪 Failed test files: ${files.join(', ')}`);
317
- if (result.testErrors) {
318
- console.log(`📝 Test errors:\n${result.testErrors}`);
319
- }
320
- }
321
- if (result.failedTypecheckFiles.length) {
322
- const files = result.failedTypecheckFiles.map((f) => path.relative(sliceDir, f));
323
- console.log(`📐 Failed typecheck files: ${files.join(', ')}`);
324
- if (result.typecheckErrors) {
325
- console.log(`📝 Typecheck errors:\n${result.typecheckErrors}`);
326
- }
327
- }
328
- }
@@ -1,100 +0,0 @@
1
- import path from 'path';
2
- import fg from 'fast-glob';
3
- import { execa } from 'execa';
4
- import { existsSync } from 'fs';
5
- import { unlink } from 'fs/promises';
6
- import { readFile } from 'fs/promises';
7
- // eslint-disable-next-line complexity
8
- export async function runTests(sliceDir, rootDir) {
9
- console.log(`🔍 Running tests in ${path.basename(sliceDir)}...`);
10
- const testFiles = await fg(['*.spec.ts', '*.specs.ts'], { cwd: sliceDir });
11
- if (testFiles.length === 0) {
12
- console.warn(`⚠️ No test files found in ${sliceDir}`);
13
- return { success: true, testErrors: '', failedTestFiles: [] };
14
- } else {
15
- console.log(`🔍 Found test files in ${path.basename(sliceDir)}:`, testFiles);
16
- }
17
- const relativePaths = testFiles.map((f) => path.join(sliceDir, f).replace(`${rootDir}/`, ''));
18
- const reportPath = path.join(sliceDir, 'vitest-results.json');
19
- try {
20
- const { stdout, stderr } = await execa(
21
- 'npx',
22
- ['vitest', 'run', '--reporter=json', `--outputFile=${reportPath}`, ...relativePaths],
23
- {
24
- cwd: rootDir,
25
- stdio: 'pipe',
26
- reject: false,
27
- },
28
- );
29
- // Wait a bit for the file to be written
30
- await new Promise((resolve) => setTimeout(resolve, 100));
31
- // Check if the report file exists and read it
32
- if (existsSync(reportPath)) {
33
- try {
34
- const reportRaw = await readFile(reportPath, 'utf-8');
35
- const report = JSON.parse(reportRaw);
36
- const testResults = report.testResults ?? [];
37
- const failedFiles = testResults
38
- .filter((r) => r.status === 'failed')
39
- .map((r) => {
40
- const fileName = r.name ?? r.file;
41
- if (!fileName) {
42
- console.warn('⚠️ Skipping test result with missing name or file:', r);
43
- return path.join(sliceDir, 'unknown');
44
- }
45
- return path.join(sliceDir, path.basename(fileName));
46
- });
47
- const failedTestSummaries = testResults
48
- .filter((r) => r.status === 'failed')
49
- .map((r) => {
50
- const fileName = path.basename(r.name ?? r.file ?? 'unknown');
51
- if (r.assertionResults.length > 0) {
52
- const lines = r.assertionResults
53
- .filter((a) => a.status === 'failed')
54
- .map((a) => `❌ ${a.fullName}\n${a.failureMessages?.join('\n') ?? ''}`);
55
- return `📄 ${fileName}\n${lines.join('\n')}`;
56
- }
57
- // fallback: use top-level message
58
- if ('message' in r && typeof r.message === 'string' && r.message.trim() !== '') {
59
- return `📄 ${fileName}\n${r.message}`;
60
- }
61
- return `📄 ${fileName}\n⚠️ Test suite failed but no assertion or error message found.`;
62
- })
63
- .join('\n\n');
64
- return {
65
- success: failedFiles.length === 0,
66
- testErrors: failedTestSummaries || stdout || stderr || 'Tests failed but no error details available',
67
- failedTestFiles: failedFiles,
68
- };
69
- } catch (parseErr) {
70
- console.error('Failed to parse test results:', parseErr);
71
- return {
72
- success: false,
73
- testErrors: stdout || stderr || 'Failed to parse test results',
74
- failedTestFiles: testFiles.map((f) => path.join(sliceDir, f)),
75
- };
76
- }
77
- } else {
78
- // No report file, use stdout/stderr
79
- return {
80
- success: false,
81
- testErrors: stdout || stderr || 'Test execution failed - no report generated',
82
- failedTestFiles: testFiles.map((f) => path.join(sliceDir, f)),
83
- };
84
- }
85
- } catch (err) {
86
- const execaErr = err;
87
- const output = (execaErr.stdout ?? '') + (execaErr.stderr ?? '');
88
- console.error('Test execution error:', output);
89
- return {
90
- success: false,
91
- testErrors: output || 'Test execution failed with no output',
92
- failedTestFiles: testFiles.map((f) => path.join(sliceDir, f)),
93
- };
94
- } finally {
95
- // Clean up the report file
96
- if (existsSync(reportPath)) {
97
- await unlink(reportPath).catch(() => {});
98
- }
99
- }
100
- }
package/src/cli/index.js DELETED
@@ -1,21 +0,0 @@
1
- import 'dotenv/config';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
4
- import { existsSync } from 'fs';
5
- import { runFlows } from '../agent/runFlows';
6
- const __filename = fileURLToPath(import.meta.url);
7
- const isMain = process.argv[1] === __filename;
8
- if (isMain) {
9
- const base = process.argv[2];
10
- if (!base) {
11
- console.error('Usage: tsx src/cli/index.ts path/to/server/root');
12
- process.exit(1);
13
- }
14
- const serverRoot = path.resolve(base);
15
- const flowsDir = path.join(serverRoot, 'src', 'domain', 'flows');
16
- if (!existsSync(flowsDir)) {
17
- console.error(`❌ Flows directory not found at: ${flowsDir}`);
18
- process.exit(1);
19
- }
20
- void runFlows(flowsDir);
21
- }
@@ -1,43 +0,0 @@
1
- export const SYSTEM_PROMPT = `
2
- 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.
3
-
4
- Project Characteristics:
5
- - Architecture: sliced event-sourced CQRS (Command, Query, Reaction slices)
6
- - Language: TypeScript with type-graphql and Emmett
7
- - Each slice has scaffolded files with implementation instructions clearly marked with comments (e.g., '## IMPLEMENTATION INSTRUCTIONS ##') or TODOs.
8
- - Tests (e.g., *.specs.ts) must pass.
9
- - Type errors are not allowed.
10
-
11
- Your Goal:
12
- - Read the implementation instructions from the provided file.
13
- - Generate only the code needed to fulfill the instructions, nothing extra and provide back the whole file without the instructions.
14
- - Maintain immutability and adhere to functional best practices.
15
- - Use only the types and domain constructs already present in the slice.
16
- - Do not remove existing imports or types that are still referenced or required in the file.
17
- - Return the entire updated file, not just the modified parts and remove any TODO comments or instructions after implementing the logic
18
-
19
- Key rules:
20
- - Never modify code outside the TODO or instruction areas.
21
- - Ensure the code is production-ready and type-safe.
22
- - Follow the slice type conventions:
23
- - **Command slice**: validate command, inspect state, emit events, never mutate state. Uses graphql mutations.
24
- - **Reaction slice**: respond to events with commands.
25
- - **Query slice**: maintain projections based on events, do not emit or throw. Uses graphql queries.
26
- - All code must be TypeScript compliant and follow functional patterns.
27
- - If a test exists, make it pass.
28
- - Keep implementations minimal and idiomatic.
29
-
30
- Avoid:
31
- - Adding new dependencies.
32
- - Refactoring unrelated code.
33
- - Changing the structure of already scaffolded files unless instructed.
34
-
35
- You will receive:
36
- - The path of the file to implement.
37
- - The current contents of the file, with instruction comments.
38
- - Other relevant files from the same slice (e.g., types, test, state, etc.).
39
-
40
- You must:
41
- - Return the entire updated file (no commentary and remove all implementation instructions).
42
- - Ensure the output is valid TypeScript.
43
- `;
@@ -1,6 +0,0 @@
1
- export function extractCodeBlock(text) {
2
- return text
3
- .replace(/```(?:ts|typescript)?/g, '')
4
- .replace(/```/g, '')
5
- .trim();
6
- }